repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
oscaru/Prometeo | prometeo/js/Router.js | 2391 | /*
*
*basado : http://krasimirtsonev.com/blog/article/A-modern-JavaScript-router-in-100-lines-history-api-pushState-hash-url
* uso :
* Router
.add(/about/, function() {
console.log('about');
})
.add(/products\/(.*)\/edit\/(.*)/, function() {
console.log('products', arguments);
})
.add(function() {
console.log('default');
})
.go('/products/12/edit/22')
*/
function Router ($){
var routes = []
,_$ = $ || false
,self = this
;
// the current URL
function getFragment() {
var fragment = window.location.hash;
return clearSlashes(fragment);
}
function clearSlashes (path) {
return path.toString().replace(/\/$/, '').replace(/^\//, '');
}
//add routes
this.add = function(re, handler) {
if(typeof re == 'function') {
handler = re;
re = '';
}
routes.push({ re: re, handler: handler});
return this;
};
this.remove = function(param) {
for(var i=0, r; i<routes.length, r = routes[i]; i++) {
if(r.handler === param || r.re.toString() === param.toString()) {
routes.splice(i, 1);
return this;
}
}
return this;
};
this.flush = function() {
routes = [];
return this;
};
/**
*
* Match devuelve un array con el primer termino la propia consulta y las otras concurrencias : ejemplo
* '/products/12/edit/22'.match(/products\/(.*)\/edit\/(.*)/) ; devuelve : ["products/12/edit/22", "12", "22"]
*/
this.check = function(f) {
var fragment = f || getFragment();
var routesLength = routes.length;
for(var i=0; i<routesLength; i++) {
var match = fragment.match(routes[i].re);
if(match) {
match.shift();
routes[i].handler.apply({}, match);
return this;
}
}
return this;
}
this.go = function(path) {
path = path ? path : '';
window.location.hash = path;
return this;
}
this._routes = routes;
if(_$) $(window).bind('hashchange', function(e){ self.check(); });
$(document).ready(function(){
self.check();
})
};
| gpl-3.0 |
fearless359/simpleinvoices_zend2 | lang/el_GR/lang.php | 55178 | <?php
/*
* Script: lang.php
* Greek translation file
*
* Authors:
* Panos Milis
*
* Last edited:
* 2016-10-04
*
* License:
* GPL v3 or above
*/
/*
* "//1" means that the variable has been translated
* "//0" means that the variable has not been translated
* These values are used by a script to calculate how much of each file has been translated.
* Use the regex pattern :%s/;/ /1/;// 1\/\/1/g - remove the spaces
*/
#all
global $LANG;
if ($LANG) {} // eliminates unused warning
$LANG['about'] = "Σχετικά";//1
$LANG['account_info'] = "Πληροφορίες Λογαριασμών";//1
$LANG['actions'] = "Ενέργειες";//1
$LANG['add'] = "Add";//0
$LANG['add_biller'] = "Προσθήκη Πωλητή";//1
$LANG['add_customer'] = "Προσθήκη Πελάτη";//1
$LANG['add_invoice_item'] = "Προσθήκη Είδους";//1
$LANG['add_invoice_preference'] = "Τύποι Τιμολογίων";//1
$LANG['add_item'] = "Προσθήκη Είδους";//1
$LANG['add_new_biller'] = "Προσθήκη Νέου Πωλητή";//1
$LANG['add_new_invoice'] = "Προσθήκη Νέου Τιμολογίου";//1
$LANG['add_new_payment_type'] = "Προσθήκη Νέου Τρόπου Πληρωμής";//1
$LANG['add_new_preference'] = "Προσθήκη Νέου Τύπου Τιμολογίου";//1
$LANG['add_new_product'] = "Προσθήκη Νέου Προϊόντος";//1
$LANG['add_new_row'] = "Προσθήκη νέας σειράς";//1
$LANG['add_new_tax_rate'] = "Προσθήκη Νέου Φορολογικού Συντελεστή";//1
$LANG['add_payment_type'] = "Προσθήκη Τρόπου Πληρωμής";//1
$LANG['add_product'] = "Προσθήκη Προϊόντος";//1
$LANG['add_product_attribute'] = "Add Product Attribute";//0
$LANG['add_product_value'] = "Add Product Value";//0
$LANG['add_tax_rate'] = "Προσθήκη Φορολογικού Συντελεστή";//1
$LANG['address'] = "Διεύθυνση";//1
$LANG['address_city'] = "Διεύθυνση: Πόλη";//1
$LANG['address_country'] = "Διεύθυνση: Χώρα";//1
$LANG['address_state'] = "Διεύθυνση: Νομός";//1
$LANG['address_street'] = "Διεύθυνση: Όδος";//1
$LANG['address_zip'] = "Διεύθυνση: Ταχυδρομικός Κώδικας";//1
$LANG['age'] = "Ηλικία";//1
$LANG['aging'] = "Ενηλικίωση";//1
$LANG['all'] = "Όλα";//1
$LANG['all_reports'] = "All reports";//1
$LANG['amount'] = "Ποσό";//1
$LANG['as_template'] = "as template";//0
$LANG['attention_short'] = "Υπόψη";//1
$LANG['attribute'] = "Attribute";//0
$LANG['attribute_short'] = "Attr";//0
$LANG['back'] = "Πίσω";//1
$LANG['backup_database'] = "Εφεδρικά Δεδομένα";//1
$LANG['backup_database_now'] = "ΔΗΜΙΟΥΡΓΙΑ ΑΝΤΙΓΡΑΦΟΥ ΑΣΦΑΛΕΙΑΣ";//1
$LANG['backup_done'] = "Δημιουργήθηκε αντίγραφο των δεδομένων σας στο αρχείο %s , τώρα μπορείτε να συνεχίσετε την χρήση του Simple Invoice κανονικά";//1
$LANG['backup_howto'] = "Για να δημιουργήσετε ένα αντίγραφο ασφαλείας των δεδομένων του Simple Invoice κάντε κλικ στο παρακάτω σύνδεσμο";//1
$LANG['backup_note_to_file'] = "Αυτή η εργασία θα δημιουργήσει ένα αντίγραφο ασφαλείας των δεδομένων σας στον φάκελο αντιγράφων ασφαλείας";//1
$LANG['backup_your_database'] = "Δημιουργία backup δεδομένων";//1
$LANG['before_starting'] = "There are just a couple of things to do before you can start invoicing";//0
$LANG['biller'] = "Πωλητής";//1
$LANG['biller_details'] = "Στοιχεία Πωλητή";//1
$LANG['biller_edit'] = "Εισαγωγή Στοιχείων Πωλητή";//1
$LANG['biller_id'] = "Κωδικός Πωλητή";//1
$LANG['biller_name'] = "Όνομα Πωλητή";//1
$LANG['biller_sales'] = "Πωλήσεις Πωλητή";//1
$LANG['biller_sales_by_customer_totals'] = "Σύνολα Πωλητών ανά Πελάτη";//1
$LANG['biller_sales_total'] = "Συνολικές Πωλήσεις ανά Πωλητή";//1
$LANG['biller_to_add'] = "Προσθήκη Πωλητή";//1
$LANG['billers'] = "Πωλητές";//1
$LANG['blog'] = "Ιστολόγιο";//1
$LANG['cancel'] = "Ακύρωση";//1
$LANG['cannot_delete_first_row'] = "Η πρώτη γραμμή δεν μπορεί να διαγραφεί";//1
$LANG['change_log'] = "Αρχείο αλλαγών";//1
$LANG['city'] = "Πόλη";//1
$LANG['company_name'] = "SimpleInvoices";//0
$LANG['confirm_delete'] = "Θέλετε σίγουρα διαγραφή;";//1
$LANG['consulting'] = "Παροχής Υπηρεσιών";//1
$LANG['consulting_style'] = "Παροχής Υπηρεσιών";//1
$LANG['cost'] = "Κόστος";//1
$LANG['country'] = "Χώρα";//1
$LANG['create_invoice'] ="Δημιουργία Τιμολογίου";//1
$LANG['credit_card_details'] = "Πληροφορίες πιστωτικής κάρτας";//1
$LANG['credit_card_expiry_month'] = "Μήνας λήξεως πιστωτικής κάρτας";//1
$LANG['credit_card_expiry_year'] = "Έτος λήξεως πιστωτικής κάρτας";//1
$LANG['credit_card_holder_name'] = "Όνομα κατόχου πιστωτικής κάρτας";//1
$LANG['credit_card_number'] = "Αριθμός πιστωτικής κάρτας";//1
$LANG['credit_card_number_encrypted'] = "Ο αριθμός της πιστωτικής κάρτας έχει κρυπτογραφηθεί και δεν εμφανίζεται στο SimpleInvoices";//1
$LANG['credit_card_number_new'] = "Νέος αριθμός πιστωτικής κάρτας";//1
$LANG['credits'] = "Ευχαριστούμε τους...";//1
$LANG['currency_code'] = "Κωδικός νομίσματος";//1
$LANG['currency_sign'] = "Σύμβολο Νομίσματος";//1
$LANG['currency_sign_non_dollar'] = "Ευρώ, λίρα, μη σημάδι \$ διαβάστε αυτό";//1
$LANG['custom_field'] = "Ελεύθερο Πεδίο";//1
$LANG['custom_field1'] = "Ελεύθερο Πεδίο 1";//1
$LANG['custom_field2'] = "Ελεύθερο Πεδίο 2";//1
$LANG['custom_field3'] = "Ελεύθερο Πεδίο 3";//1
$LANG['custom_field4'] = "Ελεύθερο Πεδίο 4";//1
$LANG['custom_field_db_field_name'] = "Όνομα Πεδίου";//1
$LANG['custom_fields'] = "Ελεύθερα Πεδία";//1
$LANG['custom_fields_upper'] = "Ελεύθερα Πεδία";//1
$LANG['custom_label'] = "Έλευθερη ετικέτα";//1
$LANG['customer'] = "Πελάτης";//1
$LANG['customer_account'] = "Λογαριασμός Πελάτη";//1
$LANG['customer_add'] = "Προσθήκη Νέου Πελάτη";//1
$LANG['customer_contact'] = "Υπεύθυνος που ερχόμαστε σε επαφή";//1
$LANG['customer_department'] = "Τμήμα";//1
$LANG['customer_details'] = "Πληροφορίες Πελάτη";//1
$LANG['customer_edit'] = "Εισαγωγή Στοιχείων Πελάτη";//1
$LANG['customer_id'] = "Στοιχεία Πελάτη";//1
$LANG['customer_name'] = "Όνομα Πελάτη - Εταιρεία";//1
$LANG['customer_short'] = "Cust";//0
$LANG['customers'] = "Πελάτες";//1
$LANG['customise_settings'] = "Επεξεργασία ρυθμίσεων";//1
$LANG['dashboard'] = "Αρχικός πίνακας";//1
$LANG['database_backup'] = "Αντίγραφο ασφαλείας δεδομένων";//1
$LANG['database_log'] = "Database Log";//0
$LANG['database_upgrade_manager'] = "Διαχειριστής Αναβάθμισης Βάσης Δεδομένων";//1
$LANG['date'] = "Ημερομηνία";//1
$LANG['date_created'] = "Ημερομηνία Δημιουργίας";//1
$LANG['date_formatted'] = "Ημερομηνία Καταχώρησης";//1
$LANG['date_upper'] = "Καταληκτική Ημερομηνία";//1
$LANG['days'] = "Ημέρες";//1
$LANG['debtors'] = "Οφειλέτες";//1
$LANG['debtors_by_aging_periods'] = "Οφειλέτες ανά πωλητή και ενηλικίωση";//1
$LANG['debtors_by_amount_owed'] = "Οφειλέτες ανά τιμολόγιο και πωλητή";//1
$LANG['debtors_by_amount_owing_customer'] = "Οφειλέτες ανά σύνολο ανά πελάτη";//1
$LANG['decimal'] = "Δεκαδικά";//1
$LANG['default_biller'] = "Προεπιλεγμένος Πωλητής";//1
$LANG['default_customer'] = "Προεπιλεγμένος Πελάτης";//1
$LANG['default_inv_template'] = "Προεπιλεγμένη Φόρμα Τιμολογίου";//1
$LANG['default_invoice_preference'] = "Προεπιλεγμένες Ρυθμίσεις Τιμολογίου";//1
$LANG['default_number_items'] = "Προεπιλεγμένος Αριθμός Ειδών";//1
$LANG['default_payment_type'] = "Προεπιλεγμένος Τρόπος Πληρωμής";//1
$LANG['default_tax'] = "Φ.Π.Α.";//1
$LANG['delete'] = "Διαγραφή";//1
$LANG['delete_has_payments1'] = "δε μπορεί να διαγραφεί διότι περιέχει πληρωμές";//1
$LANG['delete_has_payments2'] = "recorded against it";//0
$LANG['delete_line_item'] = "Διαγραφή γραμμής είδους";//1
$LANG['delete_row'] = "Διαγραφή γραμμής";//1
$LANG['deleted'] = "έχει διαγραφεί";//1
$LANG['denied_page'] = "You are not allowed to view this page";//0
$LANG['description'] = "Περιγραφή";//1
$LANG['description_short'] = "Desc";//0
$LANG['details'] = "Στοιχεία";//1
$LANG['disable'] = "Ανενεργό";//1
$LANG['disabled'] = "Ανενεργό";//1
$LANG['displaying_inv'] = "Προβολή Τιμολογίων";//1
$LANG['displaying_items'] = "Displaying {from} to {to} of {total} items";//0
$LANG['domain'] = "Domain";//0
$LANG['dont_forget_to'] = "Μην ξεχάσω να";//1
$LANG['draft'] = "Πρόχειρο";//1
$LANG['due'] = "Λόγω";//1
$LANG['edit'] = "Αλλαγή";//1
$LANG['edit_view_tooltip'] = "Επεξεργασία";//1
$LANG['email'] = "Ε-μαιλ";//1
$LANG['email_bcc'] = "Email BCC (Blind Carbon Copy)";//0
$LANG['email_biller'] = "Ε-μαιλ πωλητή";//1
$LANG['email_biller_after_cron'] = "Email biller after each recurrence";//0
$LANG['email_customer'] = "Ε-μαιλ πελάτη";//1
$LANG['email_customer_after_cron'] = "Email customer after each recurrence";//0
$LANG['email_from'] = "Email From";//0
$LANG['email_quick'] = "Σύντομο Ε-μαιλ";//1
$LANG['email_statement_as_pdf'] = "Email statement as PDF";//0
$LANG['email_to'] = "Ε-μαιλ σε";//1
$LANG['enable'] = "Ενεργό";//1
$LANG['enabled'] = "Ενεργό";//1
$LANG['end_date'] = "Τελική ημερομηνία (εεεε-μμ-ηη)";//1
$LANG['end_date_short'] = "Τελική ημερομηνία";//1
$LANG['eway'] = "Eway";//1
$LANG['eway_customer_id'] = "Eway κωδικός πελάτη ID";//1
$LANG['eway_merchant_xml'] = "Eway merchant hosted XML";//0
$LANG['export_as'] = "Εξαγωγή ως";//1
$LANG['export_doc'] = "Export to DOC";//0
$LANG['export_doc_tooltip'] = "Εξαγωγή σε Word";//1
$LANG['export_pdf'] = "Εξαγωγή σε αρχείο Adobe";//1
$LANG['export_pdf_tooltip'] = "Εξαγωγή σε Adobe";//1
$LANG['export_tooltip'] = "Εξαγωγή";//1
$LANG['export_xls'] = "Export to XLS";//0
$LANG['export_xls_tooltip'] = "Εξαγωγή σε Excel";//1
$LANG['extensions'] = "Extensions";//0
$LANG['faqs'] = "Συχνές Ερωτήσεις";//1
$LANG['faqs_how'] = "Συχνές Ερωτήσεις - πως;";//1
$LANG['faqs_need'] = "Συχνές Ερωτήσεις - τί χρειάζομαι";//1
$LANG['faqs_type'] = "Συχνές Ερωτήσεις - τύπος;";//1
$LANG['faqs_what'] = "Συχνές Ερωτήσεις- τί";//1
$LANG['fax'] = "Φαξ";//1
$LANG['filter_by_dates'] = "Φίλτρο ανά ημερομηνία";//1
$LANG['filters'] = "Φίλτρα";//1
$LANG['financial_status'] = "Financial status";//0
$LANG['for'] = "for";//0
$LANG['format_tooltip'] = "Τροποποίηση - Εργαλεία Βοήθειας";//1
$LANG['forum'] = "Συζητήσεις";//1
$LANG['free'] = "Δωρεάν";//1
$LANG['from'] = "From";//0
$LANG['fwrite_error'] = "Did you get fwrite errors?";//0
$LANG['get_help'] = "Βοήθεια";//1
$LANG['getting_started'] = "Ξεκινώντας";//1
$LANG['gross_total'] = "Μικτό Σύνολο";//1
$LANG['hello'] = " Γεία σου";//1
$LANG['help'] = "Βοήθεια";//1
$LANG['help_age'] = "The 'Age' field indicates how long the invoice has been unpaid for. If the invoice was created on the 1st of the month, at the 21st of that month if the invoice still had not been made in full the invoice 'Age' would be 21 days.<br /><br />If the invoice has been paid in full then the 'Age' field will be blank.";//0
$LANG['help_backup_database'] = "For the backup to work the webserver user(hopefully you're running Apache) must have read/write permissions to the database_backups directory in the SimpleInvoices folder<br /><br />Also if you are extra paranoid (like me :) ) about your data I recommend using phpMyAdmin. This backup script should work fine but if require 'enterprise grade' backup reliability phpMyAdmin rocks.<br /><br />Note: If you are using SimpleInvoices in the demo environment on SourceForge, backups won't work due to setup of their servers.";//0
$LANG['help_backup_database_fwrite'] = "<b>Got fwrite() errors?</b><br />If you received fwrite() errors when atempting to backup your SimpleInvoices database this means that the webserver user(hopefully you're running Apache) doesn't have read/write permissions to the tmp/database_backups directory in the SimpleInvoices folder<br /><br />Please change the permissions on this directory and attempt the backup again. To change the permissions of the tmp/database_backups directory in Unix/Linix/OSX cd to the Simple Invoice directory (<i>cd /var/www/html/simpleinvoices</i>) and then issue the chmod command to give the webserver user read/write permissions (<i>chmod -Rv 777 tmp/database_backups</i>)";//0
$LANG['help_blog'] = "Ιστολόγιο simple Invoices";//1
$LANG['help_community_forums'] = "Συζητήσεις κοινότητας";//1
$LANG['help_cost'] = "'Cost' refers to the the cost that this product costs you - this is used for inventory and profit calculation purposes";//0
$LANG['help_currency_code'] = "Currency code is the 3 letter abbreviation for your currency of choice. ie. for US Dollars is 'USD' etc.. Note: this field is used for online payment methods like Paypal to define to currency";//0
$LANG['help_custom_fields'] = "This field is a 'Custom Field'. This means that the label can be defined as whatever you want (ie. Barcode, Tax number, MSN, etc...). <br /><br />To edit or view existing 'Custom Fields' please select the Custom Fields option from the Options menu.";//0
$LANG['help_customer_contact'] = "The 'Attn.' or Customer Contact field allow you to specify a contact within your customers business.<br /><br />This is usefull if you customer has many employees and you need to directly specify on the invoice who within your customers business this invoice is for.<br /><br /> ie. Within the customer 'Springfield Power Plant' you may want to specify Mr Burns (or Smithers) as the customer contact as they are the person who gets the invoice.<br /><br />So an Invoice will look like <br /><br />Customer: Springfield Power Plant<br />Attn.: Mr Burns<br />";//0
$LANG['help_database_patches'] = "<b>Database patches need to be applied</b><br />There are database patches that need to be applied, please select 'Database Upgrade Manager' from the Options menu and follow the instructions.<br /><br />The 'Database Upgrade Manager' is how Simple Invocies manages modification to the structure of the SimpleInvoices database. With each new release there may be 'Database patches' that need to be applied. Database Upgrade Manage looks after these database patches.<br /><br />Database patches are individual modifications to the SimpleInvoices database. With a new release there may be multiple patches that need to be applied.";//0
$LANG['help_default_invoice_template_text'] = "<b>Note</b><br />The value you enter into the detault invoice template MUST be the actual folder name of the template you wish to select. The invoice templates folders are located in (./templates/invoices/)<br /><br />";//0
$LANG['help_delete'] = "By enabling Delete, you will be able to delete any invoices you no longer want via the Quick View of that invoice.<br /><br />To delete an invoice, enable this option, then go to the Manage Invoice page and select the Quick View for the invoice you wish to delete. In the Quick View screen there will now be a delete option in the actions menu. Click this button and follow the prompts - Your invoice will now be deleted.<br /><br />Note: Currently only invoices can be deleted, but in the near future this will be extended to all the other sections (ie. billers, customers, etc..)";//0
$LANG['help_email_bcc'] = "This field is not mandatory and gets the default value from the Billers email address.<br /><br />It's recommended that you BCC yourself onto this email so that you also get a copy of it. This way you know for sure that the email has been correctly sent and you always have a backup copy of the email.<br /><br /><i>Note: You can add multiple email addresses here - just use eith , or ; to split the addresses</i>";//0
$LANG['help_email_cc'] = "This field is not mandatory. Here you can specify any email address you want to CC but cannot add more than 1 email address in this field<br /><br /><i>Note: You can add multiple email addresses here - just use eith , or ; to split the addresses</i>";//0
$LANG['help_email_from'] = "This field is a mandatory field and gets the default value from the Billers email address. You can change this email address as you require but cannot add more than 1 email address in this field<br /><br /><i>Note: There can be only 1 email address in this field</i>";//0
$LANG['help_email_to'] = "This field is a mandatory field and gets the default value from the Customers email address. You can change this email address as you require<br /><br /><i>Note: You can add multiple email addresses here - just use either , or ; to split the addresses</i>";//0
$LANG['help_insert_biller_text'] = "To select no logo please select '_default_blank_logo.png' from the list.<br /><br />To add additional logos into SimpleInvoices, copy the logo file into the logo directory in the SimpleInvoices folder.";//0
$LANG['help_inv_pref_currency_sign'] = "This is the curreny symbol that will be used through-out the invoice. <br /><br /><b>Note:</b> Euro, Pound etc.. please use the html code for you currency sign in this field. Refer to the list of html codes on the following website for your non $ currency sign <a href='http://www.ascii.cl/htmlcodes.htm'>http://www.ascii.cl/htmlcodes.htm</a>. <br /><br />This is required so that PDF can work correctly with non $ symbols<br /><br /> &#163; is the html code for the Pound,<br /> &#8364; for the Euro, etc..";//0
$LANG['help_inv_pref_description'] = "This is the name of the set of preference - it's not used on the invoice itself, just in the creation of the invoice when you select from the drop down list which Invoice Preference you wish to use.";//0
$LANG['help_inv_pref_invoice_detail_heading'] = "This is what will appear as the heading of the footer/details section of the invoice.";//0
$LANG['help_inv_pref_invoice_detail_line'] = "This is the text that appear under the details/footer heading. Normally used to define payment terms etc.";//0
$LANG['help_inv_pref_invoice_enabled'] = "This allows you to specify if the 'Invoice Preference' is enabled or disabled. If the 'Invoice Preference' is disabled then you will no longer be able to select it during the creation of a new invoice.";//0
$LANG['help_inv_pref_invoice_heading'] = "This is the heading of the invoice and will be displayed at the top of the invoice.";//0
$LANG['help_inv_pref_invoice_numbering_group'] = "An invoice can have different numbering ranges depending on the invoice preference selected. ie. you can have quote 1 and invoice 1. <br /> <br />This field indicates which 'group' you want this preference to number like. If you group mulitple invoice preferences together then all invoices etc.. created using these preferences will increment in the same range. If you leave this blank this invoice prefernece will increment in its own range.";//0
$LANG['help_inv_pref_invoice_payment_method'] = "This is the where you specify how you would like the customer to pay you, ie Cheque/money order/electronic funds transfer/etc.";//0
$LANG['help_inv_pref_invoice_wording'] = "This is what the wording of the invoice will be - ie if you enter Quote - in the Manage Invoices screen it'll say Quote in the invoice type field and through that invoice it'll say Quote instead of invoice ie. Quote ID, Quote Date, etc..";//0
$LANG['help_inv_pref_locale'] = "Τοπικοποίηση";//1
$LANG['help_inv_pref_payment_line1_name'] = "This is where you can specify the payment line 1 name i.e. 'Account name'.";//0
$LANG['help_inv_pref_payment_line1_value'] = "This is where you can specify the payment line 1 value i.e. The name of your back account - 'H. & M. Simpson'.";//0
$LANG['help_inv_pref_payment_line2_name'] = "This is where you can specify the payment line 2 name i.e. 'Account number'.";//0
$LANG['help_inv_pref_payment_line2_value'] = "This is where you can specify the payment line 2 name i.e. Account number '0123-4567-89'.";//0
$LANG['help_inv_pref_status'] = "An invoice can have a status of 'Draft' or 'Real'. Draft indicates that this is a similar to a quote and is not included in the sales reports. 'Real' means that is a real invoice and is included in the sales reports.";//0
$LANG['help_inv_pref_what_the'] = "Invoice Preferences allows you to define the wording of the invoice. You can have as many different 'Invoice Preferences' defined in SimpleInvoices as you want, but you can only select 1 'Invoice Preference' per invoice.<br /><br />ie. If you wanted the heading of the invoice to say 'Moes Tavern - Invoice' instead of the default 'Invoice', you can edit the 'Invoice heading' field in the relevant Invoice Preference to achieve this result";//0
$LANG['help_invoice_create'] = "Creating invoices is easy. Once a biller and customer have been entered into SimpleInvoices all you need to do is select an invoice type from the 'Invoice +' menu, fill in the details and click 'Save Invoice'.";//0
$LANG['help_invoice_custom_fields'] = "Need more fields in the invoice screen? Want your own fields like 'Purchase Order', 'Project name' etc..<br /><br />SimpleInvoices allows you to add whatever fields you want into the invoices. These are called 'custom fields', to edit or setup your own fields select Custom Fields from the Options menu.";//0
$LANG['help_invoice_types'] = "In SimpleInvoices there are 2 types of invoices available.<br /><br />An <b>Itemized Invoice</b> is an invoice that list many different items in the same invoice, with optional notes area for each line item - think accounting/legal firms or a grocery store invoice.<br/ ><br />A <b>Total Invoice</b> is an invoice like that from a plumber that lists the actions and then has one price and the tax associated.";//0
$LANG['help_logging'] = "To log actions performed in SimpleInvoices enable this option. This creates a log in the database of what actions were performed.<br /><br />Note: At the moment the only way to view the log is in the database, soon we'll incorparte a nice log viewer into SimpleInvoices.";//0
$LANG['help_mailing_list'] = "Mailing List";//0
$LANG['help_manage_custom_fields'] = "Custom Fields are special fields that you can label as whatever you need.<br /><br />This page allows you to define up to 4 custom fields for each of the following: products, customers, billers, and invoices.<br /><br />Once you define a label of one of the fields, this field will become available for use. Ie. if you edit 'Invoice :: Custom field 1' and set the label as 'Project name', the next time you create an invoice there'll be a new field in the invoice screen called 'Project name'";//0
$LANG['help_mysql4'] = "As you are using MySQL 4 or below as your database server some features of SimpleInvoices have been disabled. Some sql queries in SimpleInvoices have taken advantage of new features in MySQL 5, so things like the quick reports here on the start page, some debtors reports and a few other features of SimpleInvoices have been disabled.";//0
$LANG['help_new_password'] = "If you want to change the user password fill in this field.<br /><br />NOTE: if you don't want to change the user password just leave this field blank.";//0
$LANG['help_process_payment_auto_amount'] = "The value in the <b>Amount</b> field automatically defaults to the amount owed for the selected invoice. This field is editable and you can change the amount to the actual amount received.<br /><br />This field defaults to the amount owed as the most common payment amount to be processed is the same as the amount owed.";//0
$LANG['help_process_payment_details'] = "Once an invoice has been selected in the 'Invoice ID' field, the biller name, customer name. total of the invoice, amount already paid and the amount outstanding will be displayed in the 'Details' section of the Process Payment screen.<br /><br />If you don't see any information in the 'Details' section either you haven't selected a valid invoice in the 'Invoice ID' or you have not entered the invoice ID correctly. Please refer to Invoice ID on this page on how to enter the invoice ID correctly.";//0
$LANG['help_process_payment_inv_id'] = "To select an invoice to process a payment against please enter the invoice number in the 'Invoice ID' field. This field is an 'auto-complete' field which means that say if you have 12 invoices in your database, when you enter '1' into this field it will return a drop down list of all the invoices with '1' in its <b>Invoice ID</b>.<br /><br />So invoices 1,10,11, and 12 will be returned if you enter '1'. To select the required invoice either use the navigations keys on your keyboard and click enter on the invoice of use your mouse and click on the invoice.<br /><br />Once an invoice has been selected using the above process all the details for this invoice will be displayed in the 'Details' section of the Process Payment screen.";//0
$LANG['help_reports_xsl'] = "<b>Report errors</b><br />If you received a 'OOOOPS, THERE'S AN ERROR HERE.' error when you attempted to run a report in SimpleInvoices this means that your version of PHP doesn't have the correct extentions installed(or enabled).<br /><br />If your running a Windows server and using WAMP5 please refer to the page on the SimpleInvoices wiki for information on how to fix this http://simpleinvoices.org/wiki/doku.php?id=how_to_i_get_reports_working_in_windows_wamp5<br /><br />If your running Unix/Linux and PHP5 please make sure you have the xsl extension installed and enabled in your php.ini. On Ubuntu GNU/Linux please install the php-xsl package for PHP5 <br /><br />If your using PHP4 please make sure that your PHP has Sablotron support '--enable-xslt'<br /><br />Note: If you are using SimpleInvoices in the demo environment on SourceForge reports won't work due to setup of their servers.";//0
$LANG['help_required_field'] = "This is a mandatory field. You have to enter a value in this field before you can save the form<br /><br />";//0
$LANG['help_si_help'] = "Βοήθεια SimpleInvoices ";//1
$LANG['help_simple_invoices'] = "SimpleInvoices is a basic invoicing system designed with simplicity and functionality in mind. Catering for the neds of small organisations and home users.<br /><br />For more information please refer to the SimpleInvoices website:<a href='http://www.simpleinvoices.org' target='_blank'> <b>http://www.simpleinvoices.org</b></a>";//0
$LANG['help_street2'] = "The field 'Street Address 2' is used when the street address for the biller or customer is either too long to fit one one line or contains multiple parts.<br /><br />ie. the street address 'Level 234, 325 South Malvern Road' can be seperated into <br /><br />Street: Level 234<br />Street Address 2: 325 South Malvern Road";//0
$LANG['help_tax_rate_sign'] = "A tax can be either a percentage based (ie. Sales Tax 10%) or a flat money values (ie. $10 or £20).<br /><br />The $ in the drop down only indicates that this will be a flat money rate and it doesnt indicate the currency symbol. The 'invoice preference' that you use dictates what the currency symbol will be in your invoices.";//0
$LANG['help_text'] = "<b>Warning</b><br /><br />Please backup your SimpleInvoices database before running the database update, just incase anything bad happens.<br /><br />To backup the database, select 'Backup Database' from the Options menu, or use phpMyAdmin(if you have this installed) to back up the database.";//0
$LANG['help_user_role'] = "There are 3 roles available <br /><br />Administrator:<br />which has access to all of SimpleInvoices<br /><br />User:<br />which has read/write acess to all of SimpleInvoices but with no access to the Settings menu <br /><br />Viewer:<br />which has read-only version of User.";//0
$LANG['help_what_are_custom_fields'] = "Custom Fields are special fields in billers, products, customers, and invoices that you can label as whatever you want.<br /><br />Wish there was a Tax ID field in biller, just go to the Custom Fields page and define one of the blank Biller Custom Fields as Tax ID.<br /><br />Now when you go to edit a Biller there'll be a new field there called Tax ID or whatever you specified it as.";//0
$LANG['help_wheres_the_edit_button'] = "In the Manage Payment screen there is no 'Edit' button. This is to provide a proper 'audit trail' of payments recorded in SimpleInvoices.<br /><br />If you've made a mistake with a payment entry the best option is to reverse the entry and entery it again correctly<br /><br />Reverse the entry - what the?<br /> This basically means just doing a negative entry for the same amount as the original entry.<br /><br />ie.<br />If your entered $110<br />but you should've entered $1100<br />to reverse this entry enter -$110 against the same invoice and then enter the correct amount of $1100";//0
$LANG['hide_details'] = "Απόκρυψη Στοιχείων";//1
$LANG['home'] = "Αρχική Σελίδα";//1
$LANG['id'] = "Κωδικός";//1
$LANG['ie_10_for_10'] = "* π.χ 10 για 10";//1
$LANG['include_online_payment'] = "Include online payment";//0
$LANG['included'] = "Συμπεριλαμβανομένου";//1
$LANG['insert_biller'] = "Εισαγωγή Πωλητή";//1
$LANG['insert_customer'] = "Εισαγωγή Πελάτη";//1
$LANG['insert_payment_type'] = "Εισαγωγή Τρόπου Πληρωμής";//1
$LANG['insert_preference'] = "Εισαγωγή Τύπου";//1
$LANG['insert_product'] = "Εισαγωγή Προϊόντος";//1
$LANG['insert_product_attribute'] = "Insert Product Attribute";//0
$LANG['insert_product_value'] = "Insert Product Value";//0
$LANG['insert_tax_rate'] = "Εισαγωγή Φορολογικού Συντελεστή";//1
$LANG['installation'] = "Εγκατάσταση";//1
$LANG['inv'] = "Τιμολόγιο";//1
$LANG['inv_consulting'] = "Παροχής Υπηρεσιών";//1
$LANG['inv_itemized'] = "Πώλησης Ειδών";//1
$LANG['inv_pref'] = "Τύπος Τιμολογίου";//1
$LANG['inv_pref_short'] = "Pref";//0
$LANG['inv_total'] = "Γενικής Μορφής";//1
$LANG['inventory'] = "Αποθήκη";//1
$LANG['invoice'] = "Τιμολόγιο";//1
$LANG['invoice_create'] = "Invoice Create";//0
$LANG['invoice_detail_heading'] = "Τίτλος Πλαισίου Στοιχείων";//1
$LANG['invoice_detail_line'] = "Γραμμή Υπενθύμισης";//1
$LANG['invoice_footer'] = "Υποσέλιδο Τιμολογίου";//1
$LANG['invoice_heading'] = "Τίτλος Τιμολογίου";//1
$LANG['invoice_id'] = "Αριθμός Τιμολογίου";//1
$LANG['invoice_listings'] = "Λίστα Τιμολογίων";//1
$LANG['invoice_number'] = "Νούμερο Τιμολογίου";//1
$LANG['invoice_numbering_group'] = "Invoice numbering group";//0
$LANG['invoice_payment_line_1_name'] = "1η γραμμή Πληρωμής - Όνομα";//1
$LANG['invoice_payment_line_1_value'] = "1η γραμμή Πληρωμής - Αξία";//1
$LANG['invoice_payment_line_2_name'] = "2η γραμμή Πληρωμής - Όνομα";//1
$LANG['invoice_payment_line_2_value'] = "2η γραμμή Πληρωμής - Αξία";//1
$LANG['invoice_payment_method'] = "Τρόπος Πληρωμής Τιμολογίων";//1
$LANG['invoice_preference_to_add'] = "Προσθήκη Τύπου Τιμολογίου";//1
$LANG['invoice_preferences'] = "Ρυθμίσεις Τύπων Τιμολογίων";//1
$LANG['invoice_start'] = "Invoice Start";//0
$LANG['invoice_summary'] = "Σύνοψη Τιμολογίου";//1
$LANG['invoice_type'] = "Τύπος Τιμολογίου";//1
$LANG['invoice_wording'] = "Τίτλος 2 Τιμολογίου";//1
$LANG['invoices'] = "Παραστατικά";//1
$LANG['item'] = "Είδος";//1
$LANG['itemised'] = "Πώληση Ειδών";//1
$LANG['itemised_style'] = "Πώλησης ειδών";//1
$LANG['language'] = "Γλώσσες";//1
$LANG['large_dataset'] = "Large dataset";//0
$LANG['license'] = "Άδεια Χρήσης";//1
$LANG['list'] = "Λίστα";//1
$LANG['loading'] = "Φόρτωση";//1
$LANG['locale'] = "Locale";//0
$LANG['logging'] = "Καταγραφή Κινήσεων";//1
$LANG['login'] = "Σύνδεση";//1
$LANG['logo_file'] = "Λογότυπο";//1
$LANG['logout'] = "Αποσύνδεση";//1
$LANG['manage'] = "Διαχειρίζομαι";//1
$LANG['manage_billers'] = "Διαχειρίζομαι Πωλητές";//1
$LANG['manage_custom_fields'] = "Διαχειρίζομαι Ελεύθερα Πεδία";//1
$LANG['manage_customers'] = "Διαχειρίζομαι Πελάτες";//1
$LANG['manage_data'] = "Διαχειρίζομαι Δεδομένα";//1
$LANG['manage_existing_invoice'] = "Διαχειρίζομαι Υπάρχοντα Τιμολόγια";//1
$LANG['manage_invoice_preferences'] = "Διαχειρίζομαι Τύπους Τιμολογίων";//1
$LANG['manage_invoices'] = "Διαχειρίζομαι Τιμολόγια";//1
$LANG['manage_payment_types'] = "Διαχειρίζομαι Τρόπους Πληρωμής";//1
$LANG['manage_payments'] = "Διαχειρίζομαι Πληρωμές";//1
$LANG['manage_preferences'] = "Διαχειρίζομαι Τύπους Τιμολογίων";//1
$LANG['manage_product_attributes'] = "Manage Product Attributes";//0
$LANG['manage_product_values'] = "Manage Product Value";//0
$LANG['manage_products'] = "Διαχειρίζομαι Προϊόντα";//1
$LANG['manage_tax_rates'] = "Διαχειρίζομαι Φορολογικούς Συντελεστές";//1
$LANG['mandatory_fields'] = "Υποχρεωτικά Πεδία";//1
$LANG['message'] = "Message";//0
$LANG['mobile_phone'] = "Κινητό Τηλέφωνο";//1
$LANG['mobile_short'] = "Κινητό Τηλ.";//1
$LANG['money'] = "Χρηματική";//1
$LANG['monthly_sales_per_year'] = "Monthly Sales and Payments per year";//0
$LANG['months'] = "μήνες";//1
$LANG['more_info'] = "Περισσότερα...";//1
$LANG['mysql4_features_disabled'] = "Χρησιμοποιείτε MySQL 4 , κάποιες λειτουργίες έχουν απενεργοποιηθεί";//1
$LANG['name'] = "Name";//0
$LANG['need_help'] = "Χρειάζεσαι βοήθεια;";//1
$LANG['new_inventory_movement'] = "New inventory movement";//0
$LANG['new_invoice'] = "Νέο παραστατικό";//1
$LANG['new_invoice_consulting'] = "Νέο Παροχής Υπηρεσιών";//1
$LANG['new_invoice_itemised'] = "Νέα Πώλησης Ειδών";//1
$LANG['new_invoice_total'] = "Νέο Γενικό";//1
$LANG['new_password'] = "New password";//0
$LANG['new_recurrence'] = "New recurrence";//0
$LANG['no'] = "Όχι";//1
$LANG['no_billers'] = "There have been no billers created. Click the 'Add New Biller' button above to create one";//0
$LANG['no_crons'] = "There have been no invoice recurrences created. Click the 'New recurrence' buttom above to create one";//0
$LANG['no_customers'] = "There have been no customers created. Click the 'Add New Customer' buttom above to create one";//0
$LANG['no_defaults'] = "Δεν Υπάρχουν Προεπιλογές";//1
$LANG['no_help_page'] = "There is no help page created for the requested topic";//0
$LANG['no_inventory_movements'] = "There have been no inventory movements recorded. Click the 'New Inventory movement' button above to create one";//0
$LANG['no_invoices'] = "There have been no invoices created. Click the 'Add a new Invoice' button above to create an invoice";//0
$LANG['no_items'] = "Δεν βρέθηκαν είδη";//1
$LANG['no_payment_types'] = "There have been no payment types created. Click the 'Add New Payment Type' button above to create one";//0
$LANG['no_payments'] = "There are no payments recorded. Click the 'Process Payment' button above to enter a payment received";//0
$LANG['no_payments_customer'] = "There are no payments recorded for this customer. Click the 'Process Payment' button above to enter a payment received";//0
$LANG['no_payments_invoice'] = "There are no payments recorded for this invoice. Click the 'Process Payment for this Invoice' button above to enter a payment received";//0
$LANG['no_preferences'] = "There have been no invoice preferences created. Click the 'Add Invoice Preference' button above to create one";//0
$LANG['no_products'] = "There have been no products created. Click the 'Add New Product' button above to create one";//0
$LANG['no_tax_rates'] = "There have been no tax rates created. Click the 'Add New Tax Rate' button above to create one";//0
$LANG['no_users'] = "There have been no users created. Click the 'Add User' button above to create one";//0
$LANG['none'] = "none";//0
$LANG['note'] = "Σημείωση";//1
$LANG['note_as_description'] = "Χρήση σημείωσης ως περιγραφή είδους γραμμής";//1
$LANG['note_attributes'] = "Note Attributes";//0
$LANG['note_expand'] = "Show line item description by default";//0
$LANG['notes'] = "Σημειώσεις";//1
$LANG['notes_opt'] = "Σημειώσεις_προαιρετικά";//1
$LANG['number_of_taxes_per_line_item'] = "Number of taxes per line item";//0
$LANG['number_short'] = "Αριθμός";//1
$LANG['of'] = "από";//1
$LANG['online_payment_id'] = "Αριθμός online πληρωμής";//1
$LANG['open'] = "Άνοιγμα";//1
$LANG['optional'] = "Προαιρετικά";//1
$LANG['options'] = "Επιλογές";//1
$LANG['other'] = "Other";//0
$LANG['owing'] = "Υπόλοιπο";//1
$LANG['page'] = "Σελίδα";//1
$LANG['paid'] = "Πληρωμή";//1
$LANG['password'] = "Password";//0
$LANG['payment'] = "Πληρωμή";//1
$LANG['payment_id'] = "Κωδικός Πληρωμής";//1
$LANG['payment_type'] = "Τρόπος Πληρωμής";//1
$LANG['payment_type_description'] = "Περιγραφή Τρόπου Πληρωμής";//1
$LANG['payment_type_details'] = "Λεπτομέρειες Τρόπου Πληρωμής";//1
$LANG['payment_type_edit'] = "Εισαγωγή Στοιχείων Τρόπου Πληρωμής";//1
$LANG['payment_type_id'] = "Κωδικός Τρόπου Πληρωμής";//1
$LANG['payment_type_method'] = "Τρόπος Πληρωμής";//1
$LANG['payment_type_to_add'] = "Προσθήκη Τρόπου Πληρωμής";//1
$LANG['payment_types'] = "Τρόποι Πληρωμής";//1
$LANG['payments'] = "Πληρωμές";//1
$LANG['payments_filtered'] = "Φιλτραρισμένες Πληρωμές";//1
$LANG['payments_filtered_customer'] = "Payments Filtered by customer";//0
$LANG['payments_filtered_invoice'] = "Φιλτραρισμένες Πληρωμές ανά Τιμολόγιο";//1
$LANG['paymentsgateway'] = "PaymentsGateway.com";//0
$LANG['paymentsgateway_api_id'] = "PaymentsGateway API ID";//0
$LANG['paypal'] = "PayPal";//0
$LANG['paypal_business_name'] = "PayPal business name";//0
$LANG['paypal_link'] = "PayPal link";//0
$LANG['paypal_notify_url'] = "PayPal notify url";//0
$LANG['paypal_return_url'] = "PayPal return url";//0
$LANG['people'] = "Πρόσωπα";//1
$LANG['phone'] = "Τηλέφωνο";//1
$LANG['phone_short'] = "Τηλεφ.";//1
$LANG['plugin_not_registered'] = "Ανενεργό";//1
$LANG['plugin_register'] = "Εγγραφή";//1
$LANG['plugin_registered'] = "Εγγεγραμμένος";//1
$LANG['plugin_unregister'] = "Διαγραφή";//1
$LANG['powered_by'] = "Powered by";//0
$LANG['preference'] = "preference";//0
$LANG['preference_id'] = "Κωδικός Τύπου";//1
$LANG['preferences'] = "Ρυθμίσεις";//1
$LANG['prepare_simple_invoices'] = "Προετοιμασία...";//1
$LANG['price'] = "Price";//0
$LANG['print_preview'] = "Προεπισκόπηση Εκτύπωσης";//1
$LANG['print_preview_tooltip'] = "Προεπισκόπηση Εκτύπωσης";//1
$LANG['process'] = "Process";//0
$LANG['process_payment'] = "Πληρωμή";//1
$LANG['process_payment_auto_amount'] = "Process Payment Auto Amount";//0
$LANG['process_payment_details'] = "Process Payment Details";//0
$LANG['process_payment_for'] = "Διαδικασία Πληρωμής για";//1
$LANG['process_payment_inv_id'] = "Process Payment Invoice ID";//0
$LANG['process_payment_via_eway'] = "Process Payment via Eway";//0
$LANG['processing'] = "Processing, please wait ...";//0
$LANG['product'] = "Προϊόν";//1
$LANG['product_attribute'] = "Product Attribute";//0
$LANG['product_attributes'] = "Product Attributes";//0
$LANG['product_description'] = "Περιγραφή Είδους";//1
$LANG['product_description_prompt'] = "You must enter a description for the product";//0
$LANG['product_edit'] = "Εισαγωγή Στοιχείων Προϊόντος";//1
$LANG['product_enabled'] = "Ενεργό";//1
$LANG['product_id'] = "Κωδικός Είδους";//1
$LANG['product_sales'] = "Πωλήσεις Προϊόντων";//1
$LANG['product_to_add'] = "Προσθήκη Προϊόντος";//1
$LANG['product_unit_price'] = "Τιμή Μονάδας";//1
$LANG['product_value'] = "Product Value";//0
$LANG['product_values'] = "Product Values";//0
$LANG['products'] = "Προϊόντα";//1
$LANG['products_by_customer'] = "Προϊόντα ανά Πελάτη";//1
$LANG['products_sold_customer_total'] = "Συνολικά Πωληθέντα Προϊόντα ανά Πελάτη";//1
$LANG['products_sold_total'] = "Συνολικά Πωληθέντα Προϊόντα";//1
$LANG['profit'] = "Κέρδος";//1
$LANG['profit_per_invoice'] = "Κέρδος ανα τιμολόγιο";//1
$LANG['provision_of'] = "Προσφορά από";//1
$LANG['quantity'] = "Ποσότητα";//1
$LANG['quantity_short'] = "Ποσότητα";//1
$LANG['quick_view'] = "Quick View";//0
$LANG['quick_view_of'] = "Γρήγορη Προβολή";//1
$LANG['quick_view_tooltip'] = "Γρήγορη Προβολή";//1
$LANG['rate'] = "Rate";//0
$LANG['real'] = "Πραγματικό";//1
$LANG['recur_each'] = "Επαναλαμβάνονται κάθε";//1
$LANG['recurrence'] = "Επανάληψη";//1
$LANG['recurrence_type'] = "Recurrence_type";//0
$LANG['register'] = "Εγγραφή";//1
$LANG['reorder_level'] = "Reorder level";//0
$LANG['reports'] = "Αναφορές";//1
$LANG['required_field'] = "Υποχρεωτικό πεδίο";//1
$LANG['role'] = "Role";//1
$LANG['run_report'] = "Εκτέλεση αναφοράς";//1
$LANG['sales'] = "Πωλήσεις";//1
$LANG['sales_by_customers'] = "Πωλήσεις ανά Πελάτη";//1
$LANG['sales_report'] = "Αναφορές";//1
$LANG['sanity_check'] = "Προσεκτικός Έλεγχος";//1
$LANG['save'] = "Αποθήκευση";//1
$LANG['save_biller'] = "Αποθήκευση Πωλητή";//1
$LANG['save_biller_failure'] = "Αποτυχής Αποθήκευση Πωλητή";//1
$LANG['save_biller_success'] = "Επιτυχής Αποθήκευση Πωλητή";//1
$LANG['save_cron_failure'] = "Something went wrong, please try saving the recurrence again<br />";//0
$LANG['save_cron_success'] = "Recurrence successfully saved, <br /> you will be redirected to the Manage Recurrences page";//0
$LANG['save_custom_field'] = "Αποθήκευση Ελεύθερου Πεδίου";//1
$LANG['save_custom_field_failure'] = "Αποτυχής Αποθήκευση Ελεύθερου Πεδίου";//1
$LANG['save_custom_field_success'] = "Επιτυχής Αποθήκευση Ελεύθερου Πεδίου";//1
$LANG['save_customer'] = "Αποθήκευση Πελάτη";//1
$LANG['save_customer_failure'] = "Αποτυχής Αποθήκευση Πελάτη";//1
$LANG['save_customer_success'] = "Επιτυχής Αποθήκευση Πελάτη";//1
$LANG['save_defaults'] = "Αποθήκευση Προεπιλεγμένων Ρυθμίσεων";//1
$LANG['save_defaults_failure'] = "Αποτυχής Αποθήκευση Προεπιλεγμένων Ρυθμίσεων";//1
$LANG['save_defaults_success'] = "Επιτυχής Αποθήκευση Προεπιλεγμένων Ρυθμίσεων";//1
$LANG['save_eway_check_failed'] = "Eway transaction did not proceed as it appears the invoice has already been paid or the customer or biller does not have the required Eway details";//0
$LANG['save_eway_failure'] = "Something went wrong with the Eway transaction - refer tmp/log/si.log for details, please try Eway transaction again";//0
$LANG['save_eway_success'] = "Eway transaction successful,<br /> you will be redirected back to the Manage Payments page";//0
$LANG['save_inventory_failure'] = "Something went wrong, please try saving the inventory movement again";//0
$LANG['save_inventory_success'] = "Processing inventory movement, <br /> you will be redirected to Manage Inventory";//0
$LANG['save_invoice'] = "Αποθήκευση Τιμολογίου";//1
$LANG['save_invoice_failure'] = "Αποτυχής Αποθήκευση Τιμολογίου";//1
$LANG['save_invoice_items_success'] = "Επιτυχής Αποθήκευση Προϊόντων Τιμολογίων";//1
$LANG['save_invoice_success'] = "Επιτυχής Αποθήκευση Τιμολογίου";//1
$LANG['save_payment_failure'] = "Αποτυχής Αποθήκευση Πληρωμής";//1
$LANG['save_payment_invoice_success'] = "Επιτυχής Αποθήκευση Τιμολογίου που Πληρώθηκε";//1
$LANG['save_payment_success'] = "Επιτυχής Αποθήκευση Πληρωμής";//1
$LANG['save_payment_type'] = "Αποθήκευση Τρόπου Πληρωμής";//1
$LANG['save_payment_type_failure'] = "Αποτυχής Αποθήκευση Τρόπου Πληρωμής";//1
$LANG['save_payment_type_success'] = "Επιτυχής Αποθήκευση Τρόπου Πληρωμής";//1
$LANG['save_preference_failure'] = "Αποτυχής Αποθήκευση Ρυθμίσεων";//1
$LANG['save_preference_success'] = "Επιτυχής Αποθήκευση Ρυθμίσεων";//1
$LANG['save_product'] = "Αποθήκευση Προϊόντος";//1
$LANG['save_product_failure'] = "Αποτυχής Αποθήκευση Προϊόντος";//1
$LANG['save_product_success'] = "Επιτυχής Αποθήκευση Προϊόντος";//1
$LANG['save_tax_rate'] = "Αποθήκευση Φορολογικού Συντελεστή";//1
$LANG['save_tax_rate_failure'] = "Αποτυχής Αποθήκευση Φορολογικού Συντελεστή";//1
$LANG['save_tax_rate_success'] = "Επιτυχής Αποθήκευση Φορολογικού Συντελεστή";//1
$LANG['save_user_failure'] = "Something went wrong, please try saving the user again<br />";//0
$LANG['save_user_success'] = "User successfully saved, <br /> you will be redirected to the Manage Users page";//0
$LANG['select_invoice'] = "Επιλογή Τιμολογίου";//1
$LANG['settings'] = "Ρυθμίσεις";//1
$LANG['setup_add_customer'] = "Προσθήκη πελάτη, κλικ";//1
$LANG['setup_add_inv_pref'] = "Add an invoice preference, click ";//0
$LANG['setup_add_products'] = "Πρόσθεσε λίγα προιόντα , κλικ";//1
$LANG['setup_add_taxrate'] = "Add a tax rate, click ";//0
$LANG['setup_as_biller'] = "Setup yourself as biller, click ";//0
$LANG['setup_create_invoices'] = "Go nuts creating invoices, click ";//0
$LANG['setup_customisation'] = "If you need to customise some of the settings (ie. language, default items, etc..), click ";//0
$LANG['shortcut'] = "Σύντομη Εισαγωγή";//1
$LANG['show_details'] = "Προβολή Λεπτομερειών";//1
$LANG['show_only_unpaid_invoices'] = "Εμφάνιση μόνο απλήρωτων τιμολογίων";//1
$LANG['simple_invoices'] = "SimpleInvoices";//0
$LANG['start_date'] = "Αρχική ημερομηνία (εεεε-μμ-ηη)";//1
$LANG['start_date_short'] = "Αρχική ημερομηνία";//1
$LANG['start_working'] = "Start working";//0
$LANG['state'] = "Νομός";//1
$LANG['statement'] = "Κατάσταση";//1
$LANG['statement_for_the_period'] = "Καταστάσεις περιόδου";//1
$LANG['statement_of_invoices'] = "Καταστάσεις τιμολογίων";//1
$LANG['statement_summary'] = "Σύνολο κατάστασης";//1
$LANG['statements'] = "Αναφορές";//1
$LANG['stats'] = "Σημαντικά Στατιστικά";//1
$LANG['stats_biller'] = "Μεγαλύτερος Πωλητής";//1
$LANG['stats_customer'] = "Μεγαλύτερος Πελάτης";//1
$LANG['stats_debtor'] = "Μεγαλύτερος Οφειλέτης";//1
$LANG['status'] = "Κατάσταση";//1
$LANG['street'] = "Διεύθυνση";//1
$LANG['street2'] = "Δίευθυνση";//1
$LANG['sub_total'] = "Υποσύνολο";//1
$LANG['subject'] = "Subject";//0
$LANG['sum'] = "Άθροισμα";//1
$LANG['summary'] = "Περίληψη";//1
$LANG['summary_of_accounts'] = "Περίληψη Λογαριασμών";//1
$LANG['system_defaults'] = "Προεπιλογές Συστήματος";//1
$LANG['system_preferences'] = "Ρυθμίσεις Συστήματος";//1
$LANG['tax'] = "Φόρος";//1
$LANG['tax_amount'] = "Ποσό φόρου";//1
$LANG['tax_description'] = "Περιγραφή Φόρου";//1
$LANG['tax_id'] = "Κωδικός Φόρου";//1
$LANG['tax_percentage'] = "Ποσοστό Φόρου";//1
$LANG['tax_rate'] = "Φορολογικός Συντελεστής";//1
$LANG['tax_rate_details'] = "Λεπτομέρειες Φορολογικού Συντελεστή";//1
$LANG['tax_rate_id'] = "Κωδικός Φορολογικού Συντελεστή";//1
$LANG['tax_rate_to_add'] = "Προσθήκη Φορολογικού Συντελεστή";//1
$LANG['tax_rates'] = "Ρυθμίσεις Φ.Π.Α.";//1
$LANG['tax_total'] = "Συνολικός Φόρος";//1
$LANG['telephone_short'] = "Τηλ.";//1
$LANG['thank_you'] = "Thank you for choosing SimpleInvoices!";//0
$LANG['thank_you_inv'] = "Thank you for invoicing with ";//0
$LANG['title_module_billers'] = "Πωλητές";//1
$LANG['title_module_cron'] = "Money / Recurrence";//0
$LANG['title_module_custom_fields'] = "Διαχείριση ελεύθερων πεδίων";//1
$LANG['title_module_customers'] = "Πελάτες";//1
$LANG['title_module_index'] = "Αρχική";//1
$LANG['title_module_invoices'] = "Παραστατικά";//1
$LANG['title_module_options'] = "Ρυθμίσεις";//1
$LANG['title_module_payment_types'] = "Ρυθμίσεις τύπων πληρωμών";//1
$LANG['title_module_payments'] = "Πληρωμές";//1
$LANG['title_module_preferences'] = "Επιλογές τιμολόγησης";//1
$LANG['title_module_product_attribute'] = "Products / Product Attributes";//0
$LANG['title_module_product_value'] = "Products / Product Values";//0
$LANG['title_module_products'] = "Προϊόντα";//1
$LANG['title_module_reports'] = "Αρχική / Αναφορές";//1
$LANG['title_module_system_defaults'] = "Ρυθμίσεις Συστήματος";//1
$LANG['title_module_tax_rates'] = "Ρυθμίσεις Φ.Π.Α.";//1
$LANG['title_module_user'] = "Χρήστες";//1
$LANG['title_view_index'] = "Πίνακας ελέγχου";//1
$LANG['to'] = "To";//0
$LANG['to_lowercase'] = "to";//0
$LANG['toggle_status'] = "Εναλλαγή κατάστασης";//1
$LANG['total'] = "Σύνολο";//1
$LANG['total_amount'] = "Συνολικό Ποσό";//1
$LANG['total_by_aging_periods'] = "Ενηλικίωση Εισπράξεων/Οφειλών";//1
$LANG['total_invoices'] = "Σύνολο Τιμολογίων";//1
$LANG['total_owed'] = "Total Owed";//0
$LANG['total_owed_per_customer'] = "Συνολικές Οφειλές ανά Πελάτη";//1
$LANG['total_owing'] = "Συνολικές Οφειλές";//1
$LANG['total_paid'] = "Συνολικές Πληρωμές";//1
$LANG['total_sales'] = "Σύνολο Πωλήσεων";//1
$LANG['total_sales_by_customer'] = "Σύνολο Πωλήσεων ανά Πελάτη";//1
$LANG['total_style'] = "Γενικό Τιμολόγιο";//1
$LANG['total_taxes'] = "Συνολικοί Φόροι";//1
$LANG['total_uppercase'] = "Σύνολο";//1
$LANG['totals'] = "Σύνολα";//1
$LANG['type'] = "Τύπος";//1
$LANG['unit_cost'] = "Κόστος";//1
$LANG['unit_price'] = "Τιμή Μονάδος";//1
$LANG['unpaid_invoices'] = "Απλήρωτα τιμολόγια";//1
$LANG['upgrading_simple_invoices'] = "Αναβάθμιση";//1
$LANG['user_add'] = "Add User";//0
$LANG['users'] = "Χρήστες";//1
$LANG['using_simple_invoices'] = "Χρήση...";//1
$LANG['value'] = "Αξία";//1
$LANG['view'] = "Προβολή";//1
$LANG['visible'] = "Ορατό";//1
$LANG['want_more_fields'] = "Περισσότερα Πεδία";//1
$LANG['warning_eway'] = "<b>Note:</b> You are about to charge your customers credit card<br /> - make sure you know what you're doing!!";//0
$LANG['weeks'] = "εβδομάδες";//1
$LANG['welcome'] = "Καλώς Ήρθατε ";//1
$LANG['what_are_custom_fields'] = "Τί είναι τα Ελεύθερα Πεδία";//1
$LANG['whats_all_this_inv_pref'] = "Τί είναι όλοι αυτοί οι Τύποι Τιμολογίων";//1
$LANG['whats_this_page_about'] = "Τι αφορά αυτή η σελίδα";//1
$LANG['wheres_the_edit_button'] = "Που είναι το Πλήκτρο Εισαγωγής/Αλλαγής Στοιχείων";//1
$LANG['years'] = "έτη";//1
$LANG['yes'] = "Yes";//1
$LANG['your_reports'] = "Οι εκτυπώσεις μου";//1
$LANG['zip'] = "Ταχ. Κωδ.";//1
| gpl-3.0 |
2014c2g5/2014cadp | wsgi/local_data/brython_programs/oop1.py | 1605 | class Point():
# px: 點的 x 座標
# py: 點的 y 座標
# pn: 點的名稱
# A: 點物件
# name, x, y are the attributes of the class
# name, x, y 為點類別的物件屬性
# x, y, name are global variables, x, y are float and name is string
def __init__(self, px=None, py=None, pn=None, A=None):
# A is a Point, pn is a String, px, py is coordinates,
self.px = px
self.py = py
self.pn = pn
self.A = A
# 只有 pn 與 A
if (pn != None and A != None and px == None and py == None):
self.name = pn
self.x = A.x
self.y = A.y
# 只有 px 與 py
elif (px != None and py != None and pn == None):
self.name = ""
self.x = self.px
self.y = self.py
# 只有 px, py, pn
elif (px != None and py != None and pn != None):
self.name = pn
self.x = px
self.y = py
else:
# 完全不指定輸入變數
# all arguments are None
self.name = ""
self.x = 0.0
self.y = 0.0
p2 = Point(px=4, py=5, pn="這是點物件")
p3 = Point(pn="直接用點物件定義點", A=p2)
print(p2.x, p2.y, p2.name, p3.x, p3.y, p3.name)
p1 = Point(px=0, py=5, pn="指定點的 x 與 y 座標")
print(p1.x, p1.y, p1.name)
p4 =Point(A=p3, pn="這是 p4 點")
print(p4.name, p4.x, p4.y)
# Pythonic way to argument overloading
def sum(*summands):
result = 0
for summand in summands:
result += summand
return result
print(sum(1, 2, 3, 4)) | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/weaponskills/power_slash.lua | 1966 | -----------------------------------
-- Power Slash
-- Great Sword weapon skill
-- Skill level: 30
-- Delivers a single-hit attack. params.crit varies with TP.
-- Modifiers: STR:60% ; VIT:60%
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
-- ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
-- wscs are in % so 0.2=20%
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
-- critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP)
params.crit100 = 0.4; params.crit200=0.7; params.crit300=1.0;
params.canCrit = true;
-- accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6; params.vit_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (criticalHit) then
local duration = 60 * (tp / 1000) * (1 + (tp - 1000) / 2000);
player:addStatusEffect(EFFECT_ATTACK_BOOST_II,15,0,duration);
player:addStatusEffect(EFFECT_REGAIN, 2,3,duration);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
scemino/nscumm | Platforms/NScumm.Platform_UWP/Properties/AssemblyInfo.cs | 1086 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NScumm.Platform_UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NScumm.Platform_UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | gpl-3.0 |
northern-bites/nao-man | noggin/typeDefs/Location.py | 3667 | from math import (degrees,
hypot)
from ..util import MyMath
class Location (object):
def __init__(self, x = 0, y = 0, z = 0):
self.x = x
self.y = y
self.z = z
def __eq__(self, other):
return (self.x == other.x and
self.y == other.y and
self.z == other.z)
def __ne__(self, other):
return not (self.x == other.x and
self.y == other.y and
self.z == other.z)
def dist(self, other):
''' returns euclidian dist'''
# HACK HACK HACK HACK for infinity values HACK HACK
if other.x == float('inf') or \
other.y == float('inf'):
print "WE HAVE AN INFINITY = ", self.x, self.y, other.x, other.y
return 10000
return hypot(other.y - self.y, other.x - self.x)
def getTargetHeading(self, target):
'''determine the heading from one location to another'''
return MyMath.sub180Angle(degrees(MyMath.safe_atan2(target.y - self.y,
target.x - self.x)))
def visible():
pass
def inScanRange():
pass
class RobotLocation(Location):
def __init__(self, xP = 0, yP = 0, h = 0):
Location.__init__(self, xP, yP)
self.h = h
def getRelativeBearing(self, other):
'''return relative heading from robot localization to abs x,y on field'''
return MyMath.sub180Angle((degrees(MyMath.safe_atan2(other.y - self.y,
other.x - self.x))) - self.h)
def headingTo(self, other):
'''determine the heading facing a target x, y'''
return MyMath.sub180Angle(degrees(MyMath.safe_atan2(other.y - self.y,
other.x - self.x)))
def spinDirToPoint(self, other):
"""
Advanced function to get the spin direction for a given point.
"""
LEFT_SPIN = 1
RIGHT_SPIN = -1
spinDir = 0
targetH = self.getRelativeBearing(other)
if abs(self.h - targetH) < 5:
spinDir = 0
elif targetH == 0:
spinDir = -MyMath.sign(self.h)
elif targetH == (180 or -180):
spinDir = MyMath.sign(self.h)
elif MyMath.sign(targetH) == MyMath.sign(self.h):
spinDir = MyMath.sign(targetH - self.h)
elif self.h < 0:
if (self.h + 180) >= targetH:
spinDir = LEFT_SPIN
else: # h+180 < targetH
spinDir = RIGHT_SPIN
else: # h>0
if (self.h - 180) >= targetH:
spinDir = LEFT_SPIN
else:
spinDir = RIGHT_SPIN
return spinDir
def spinDirToHeading(self, targetH):
"""
Advanced function to get the spin direction for a given heading.
"""
LEFT_SPIN = 1
RIGHT_SPIN = -1
spinDir = 0
if abs(self.h - targetH) < 5:
spinDir = 0
elif targetH == 0:
spinDir = -MyMath.sign(self.h)
elif targetH == (180 or -180):
spinDir = MyMath.sign(self.h)
elif MyMath.sign(targetH) == MyMath.sign(self.h):
spinDir = MyMath.sign(targetH - self.h)
elif self.h < 0:
if (self.h + 180) >= targetH:
spinDir = LEFT_SPIN
else: # h+180 < targetH
spinDir = RIGHT_SPIN
else: # h>0
if (self.h - 180) >=targetH:
spinDir = LEFT_SPIN
else:
spinDir = RIGHT_SPIN
return spinDir
| gpl-3.0 |
RadioCanut/site-radiocanut | plugins-dist/porte_plume/lang/paquet-porte_plume_nl.php | 582 | <?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/paquet-porte_plume?lang_cible=nl
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// P
'porte_plume_description' => 'Penhouder is een rekbare werkbalk voor SPIP die gebruik van [MarkItUp->http://markitup.jaysalvat.com/home/] javascript library maakt.',
'porte_plume_nom' => 'Penhouder',
'porte_plume_slogan' => 'Een penhouder om mooi te schrijven'
);
| gpl-3.0 |
myappleguy/mautic | app/bundles/InstallBundle/Configurator/Step/CheckStep.php | 11393 | <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\InstallBundle\Configurator\Step;
use Mautic\InstallBundle\Configurator\Form\CheckStepType;
/**
* Check Step.
*/
class CheckStep implements StepInterface
{
/**
* Flag if the configuration file is writable
*
* @var bool
*/
private $configIsWritable;
/**
* Path to the kernel root
*
* @var string
*/
private $kernelRoot;
/**
* Absolute path to cache directory
*
* @var string
*/
public $cache_path = '%kernel.root_dir%/cache';
/**
* Absolute path to log directory
*
* @var string
*/
public $log_path = '%kernel.root_dir%/logs';
/**
* Set the domain URL for use in getting the absolute URL for cli/cronjob generated URLs
*
* @var string
*/
public $site_url;
/**
* Set the name of the source that installed Mautic
*
* @var string
*/
public $install_source = 'Mautic';
/**
* Constructor
*
* @param boolean $configIsWritable Flag if the configuration file is writable
* @param string $kernelRoot Kernel root path
*/
public function __construct($configIsWritable, $kernelRoot, $baseUrl)
{
$this->configIsWritable = $configIsWritable;
$this->kernelRoot = $kernelRoot;
$this->site_url = $baseUrl;
}
/**
* {@inheritdoc}
*/
public function getFormType()
{
return new CheckStepType();
}
/**
* {@inheritdoc}
*/
public function checkRequirements()
{
$messages = array();
if (version_compare(PHP_VERSION, '5.3.16', '==')) {
$messages[] = 'mautic.install.buggy.php.version';
}
if (!is_dir(dirname($this->kernelRoot) . '/vendor/composer')) {
$messages[] = 'mautic.install.composer.dependencies';
}
if (!$this->configIsWritable) {
$messages[] = 'mautic.install.config.unwritable';
}
if (!is_writable($this->kernelRoot . '/cache')) {
$messages[] = 'mautic.install.cache.unwritable';
}
if (!is_writable($this->kernelRoot . '/logs')) {
$messages[] = 'mautic.install.logs.unwritable';
}
$timezones = array();
foreach (\DateTimeZone::listAbbreviations() as $abbreviations) {
foreach ($abbreviations as $abbreviation) {
$timezones[$abbreviation['timezone_id']] = true;
}
}
if (!isset($timezones[date_default_timezone_get()])) {
$messages[] = 'mautic.install.timezone.not.supported';
}
if (get_magic_quotes_gpc()) {
$messages[] = 'mautic.install.magic_quotes_enabled';
}
if (!function_exists('json_encode')) {
$messages[] = 'mautic.install.function.jsonencode';
}
if (!function_exists('session_start')) {
$messages[] = 'mautic.install.function.sessionstart';
}
if (!function_exists('ctype_alpha')) {
$messages[] = 'mautic.install.function.ctypealpha';
}
if (!function_exists('token_get_all')) {
$messages[] = 'mautic.install.function.tokengetall';
}
if (!function_exists('simplexml_import_dom')) {
$messages[] = 'mautic.install.function.simplexml';
}
if (!extension_loaded('mcrypt')) {
$messages[] = 'mautic.install.extension.mcrypt';
}
if (function_exists('apc_store') && ini_get('apc.enabled')) {
$minimumAPCversion = version_compare(PHP_VERSION, '5.4.0', '>=') ? '3.1.13' : '3.0.17';
if (!version_compare(phpversion('apc'), $minimumAPCversion, '>=')) {
$messages[] = 'mautic.install.apc.version';
}
}
$unicodeIni = version_compare(PHP_VERSION, '5.4.0', '>=') ? 'zend.detect_unicode' : 'detect_unicode';
// Commented for now, no idea what this check was actually supposed to be doing in the distro bundle
/*if (ini_get($unicodeIni)) {
$messages[] = 'mautic.install.detect.unicode';
}*/
if (extension_loaded('suhosin')) {
$cfgValue = ini_get('suhosin.executor.include.whitelist');
if (!call_user_func(create_function('$cfgValue', 'return false !== stripos($cfgValue, "phar");'), $cfgValue)) {
$messages[] = 'mautic.install.suhosin.whitelist';
}
}
if (extension_loaded('xdebug')) {
if (ini_get('xdebug.show_exception_trace')) {
$messages[] = 'mautic.install.xdebug.exception.trace';
}
if (ini_get('xdebug.scream')) {
$messages[] = 'mautic.install.xdebug.scream';
}
}
$pcreVersion = defined('PCRE_VERSION') ? (float) PCRE_VERSION : null;
if (is_null($pcreVersion)) {
$messages[] = 'mautic.install.function.pcre';
}
return $messages;
}
/**
* {@inheritdoc}
*/
public function checkOptionalSettings()
{
$phpSupportData = array(
'5.3' => array(
'security' => '2013-07-11',
'eos' => '2014-08-14',
),
'5.4' => array(
'security' => '2014-09-14',
'eos' => '2015-09-14',
),
'5.5' => array(
'security' => '2015-07-10',
'eos' => '2016-07-10'
),
'5.6' => array(
'security' => '2016-08-28',
'eos' => '2017-08-28'
),
);
$messages = array();
// Check the PHP version's support status
$activePhpVersion = PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;
// Do we have the PHP version's data?
if (isset($phpSupportData[$activePhpVersion])) {
// First check if the version has reached end of support
$today = new \DateTime();
$phpEndOfSupport = new \DateTime($phpSupportData[$activePhpVersion]['eos']);
if ($phpNotSupported = $today > $phpEndOfSupport) {
$messages[] = 'mautic.install.php.version.not.supported';
}
// If the version is still supported, check if it has reached security support only
$phpSecurityOnlyDate = new \DateTime($phpSupportData[$activePhpVersion]['security']);
if (!$phpNotSupported && $today > $phpSecurityOnlyDate) {
$messages[] = 'mautic.install.php.version.has.only.security.support';
}
}
if (version_compare(PHP_VERSION, '5.3.8', '<')) {
$messages[] = 'mautic.install.php.version.annotations';
}
if (version_compare(PHP_VERSION, '5.4.0', '=')) {
$messages[] = 'mautic.install.php.version.dump';
}
if ((PHP_MINOR_VERSION == 3 && PHP_RELEASE_VERSION < 18) || (PHP_MINOR_VERSION == 4 && PHP_RELEASE_VERSION < 8)) {
$messages[] = 'mautic.install.php.version.pretty.error';
}
$pcreVersion = defined('PCRE_VERSION') ? (float) PCRE_VERSION : null;
if (!is_null($pcreVersion)) {
if (version_compare($pcreVersion, '8.0', '<')) {
$messages[] = 'mautic.install.pcre.version';
}
}
if (extension_loaded('xdebug')) {
$cfgValue = ini_get('xdebug.max_nesting_level');
if (!call_user_func(create_function('$cfgValue', 'return $cfgValue > 100;'), $cfgValue)) {
$messages[] = 'mautic.install.xdebug.nesting';
}
}
// We set a default timezone in the app bootstrap, but advise the user if their PHP config is missing it
if (!ini_get('date.timezone')) {
$messages[] = 'mautic.install.date.timezone.not.set';
}
if (!class_exists('\\DomDocument')) {
$messages[] = 'mautic.install.module.phpxml';
}
if (!function_exists('mb_strlen')) {
$messages[] = 'mautic.install.function.mbstring';
}
if (!function_exists('iconv')) {
$messages[] = 'mautic.install.function.iconv';
}
if (!function_exists('utf8_decode')) {
$messages[] = 'mautic.install.function.xml';
}
if (function_exists('imap_open')) {
$messages[] = 'mautic.install.extension.imap';
}
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
if (!function_exists('posix_isatty')) {
$messages[] = 'mautic.install.function.posix';
}
}
if (!class_exists('\\Locale')) {
$messages[] = 'mautic.install.module.intl';
}
if (class_exists('\\Collator')) {
try {
if (is_null(new \Collator('fr_FR'))) {
$messages[] = 'mautic.install.intl.config';
}
} catch (\Exception $exception) {
$messages[] = 'mautic.install.intl.config';
}
}
if (class_exists('\\Locale')) {
if (defined('INTL_ICU_VERSION')) {
$version = INTL_ICU_VERSION;
} else {
try {
$reflector = new \ReflectionExtension('intl');
ob_start();
$reflector->info();
$output = strip_tags(ob_get_clean());
preg_match('/^ICU version +(?:=> )?(.*)$/m', $output, $matches);
$version = $matches[1];
} catch (\ReflectionException $exception) {
$messages[] = 'mautic.install.module.intl';
// Fake the version here for the next check
$version = '4.0';
}
}
if (version_compare($version, '4.0', '<')) {
$messages[] = 'mautic.install.intl.icu.version';
}
}
$accelerator =
(extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'))
||
(extension_loaded('apc') && ini_get('apc.enabled'))
||
(extension_loaded('Zend OPcache') && ini_get('opcache.enable'))
||
(extension_loaded('xcache') && ini_get('xcache.cacher'))
||
(extension_loaded('wincache') && ini_get('wincache.ocenabled'))
;
if (!$accelerator) {
$messages[] = 'mautic.install.accelerator';
}
return $messages;
}
/**
* {@inheritdoc}
*/
public function getTemplate()
{
return 'MauticInstallBundle:Install:check.html.php';
}
/**
* {@inheritdoc}
*/
public function update(StepInterface $data)
{
$parameters = array();
foreach ($data as $key => $value) {
// Exclude keys from the config
if (!in_array($key, array('configIsWritable', 'kernelRoot'))) {
$parameters[$key] = $value;
}
}
return $parameters;
}
}
| gpl-3.0 |
directus/directus | app/src/utils/geometry/basemap.ts | 3181 | import { Style, RasterSource } from 'maplibre-gl';
import getSetting from '@/utils/get-setting';
import maplibre from 'maplibre-gl';
import { getTheme } from '@/utils/get-theme';
export type BasemapSource = {
name: string;
type: 'raster' | 'tile' | 'style';
url: string;
tileSize?: number;
attribution?: string;
};
const defaultBasemap: BasemapSource = {
name: 'OpenStreetMap',
type: 'raster',
url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png',
tileSize: 256,
attribution: '© OpenStreetMap contributors',
};
const baseStyle: Style = {
version: 8,
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf',
};
export function getBasemapSources(): BasemapSource[] {
if (getSetting('mapbox_key')) {
return [getDefaultMapboxBasemap(), defaultBasemap, ...(getSetting('basemaps') || [])];
}
return [defaultBasemap, ...(getSetting('basemaps') || [])];
}
export function getStyleFromBasemapSource(basemap: BasemapSource): Style | string {
setMapboxAccessToken(basemap.url);
if (basemap.type == 'style') {
return basemap.url;
} else {
const style: Style = { ...baseStyle };
const source: RasterSource = { type: 'raster' };
if (basemap.attribution) source.attribution = basemap.attribution;
if (basemap.type == 'raster') {
source.tiles = expandUrl(basemap.url);
source.tileSize = basemap.tileSize || 512;
}
if (basemap.type == 'tile') {
source.url = basemap.url;
}
style.layers = [{ id: basemap.name, source: basemap.name, type: 'raster' }];
style.sources = { [basemap.name]: source };
return style;
}
}
function expandUrl(url: string): string[] {
const urls = [];
let match = /\{([a-z])-([a-z])\}/.exec(url);
if (match) {
// char range
const startCharCode = match[1].charCodeAt(0);
const stopCharCode = match[2].charCodeAt(0);
let charCode;
for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) {
urls.push(url.replace(match[0], String.fromCharCode(charCode)));
}
return urls;
}
match = /\{(\d+)-(\d+)\}/.exec(url);
if (match) {
// number range
const stop = parseInt(match[2], 10);
for (let i = parseInt(match[1], 10); i <= stop; i++) {
urls.push(url.replace(match[0], i.toString()));
}
return urls;
}
match = /\{(([a-z0-9]+)(,([a-z0-9]+))+)\}/.exec(url);
if (match) {
// csv
const subdomains = match[1].split(',');
for (const subdomain of subdomains) {
urls.push(url.replace(match[0], subdomain));
}
return urls;
}
urls.push(url);
return urls;
}
function setMapboxAccessToken(styleURL: string): void {
styleURL = styleURL.replace(/^mapbox:\//, 'https://api.mapbox.com/styles/v1');
try {
const url = new URL(styleURL);
if (url.host == 'api.mapbox.com') {
const token = url.searchParams.get('access_token');
if (token) maplibre.accessToken = token;
}
} catch {
return;
}
}
function getDefaultMapboxBasemap(): BasemapSource {
const defaultMapboxBasemap: BasemapSource = {
name: 'Mapbox',
type: 'style',
url: 'mapbox://styles/directus/cktaiz31c509n18nrxj63zdy6',
};
if (getTheme() === 'dark') {
defaultMapboxBasemap.url = 'mapbox://styles/directus/cktaixyhk2joh17lrb5i8zs22';
}
return defaultMapboxBasemap;
}
| gpl-3.0 |
hartwigmedical/hmftools | hmf-common/src/main/java/com/hartwig/hmftools/common/doid/DoidDatamodelCheckerFactory.java | 4003 | package com.hartwig.hmftools.common.doid;
import java.util.Map;
import com.google.common.collect.Maps;
import com.hartwig.hmftools.common.utils.json.JsonDatamodelChecker;
import org.jetbrains.annotations.NotNull;
final class DoidDatamodelCheckerFactory {
private DoidDatamodelCheckerFactory() {
}
@NotNull
static JsonDatamodelChecker doidObjectChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("graphs", true);
return new JsonDatamodelChecker("DoidObject", map);
}
@NotNull
static JsonDatamodelChecker doidGraphsChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("nodes", true);
map.put("edges", true);
map.put("id", true);
map.put("meta", true);
map.put("equivalentNodesSets", true);
map.put("logicalDefinitionAxioms", true);
map.put("domainRangeAxioms", true);
map.put("propertyChainAxioms", true);
return new JsonDatamodelChecker("DoidGraphs", map);
}
@NotNull
static JsonDatamodelChecker doidNodeChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("type", false);
map.put("lbl", false);
map.put("id", true);
map.put("meta", false);
return new JsonDatamodelChecker("DoidNode", map);
}
@NotNull
static JsonDatamodelChecker doidEdgeChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("sub", true);
map.put("pred", true);
map.put("obj", true);
return new JsonDatamodelChecker("DoidEdge", map);
}
@NotNull
static JsonDatamodelChecker doidGraphMetaDataChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("xrefs", true);
map.put("basicPropertyValues", true);
map.put("version", false);
map.put("subsets", true);
return new JsonDatamodelChecker("DoidGraphMetaData", map);
}
@NotNull
static JsonDatamodelChecker doidLogicalDefinitionAxiomChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("definedClassId", true);
map.put("genusIds", true);
map.put("restrictions", true);
return new JsonDatamodelChecker("DoidLogicalDefinitionAxiom", map);
}
@NotNull
static JsonDatamodelChecker doidRestrictionChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("propertyId", true);
map.put("fillerId", true);
return new JsonDatamodelChecker("DoidRestriction", map);
}
@NotNull
static JsonDatamodelChecker doidSynonymChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("pred", true);
map.put("val", true);
map.put("xrefs", true);
return new JsonDatamodelChecker("DoidSynonym", map);
}
@NotNull
static JsonDatamodelChecker doidDefinitionChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("xrefs", true);
map.put("val", true);
return new JsonDatamodelChecker("DoidDefinition", map);
}
@NotNull
static JsonDatamodelChecker doidBasicPropertyValueChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("pred", true);
map.put("val", true);
return new JsonDatamodelChecker("DoidBasicPropertyValue", map);
}
@NotNull
static JsonDatamodelChecker doidMetadataXrefChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("val", true);
return new JsonDatamodelChecker("DoidMetadataXref", map);
}
@NotNull
static JsonDatamodelChecker doidMetadataChecker() {
Map<String, Boolean> map = Maps.newHashMap();
map.put("xrefs", false);
map.put("synonyms", false);
map.put("basicPropertyValues", false);
map.put("definition", false);
map.put("subsets", false);
return new JsonDatamodelChecker("DoidMetadata", map);
}
}
| gpl-3.0 |
jusabatier/georchestra | security-proxy/src/main/java/org/georchestra/security/Proxy.java | 57032 | /*
* Copyright (C) 2009-2016 by the geOrchestra PSC
*
* This file is part of geOrchestra.
*
* geOrchestra is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* geOrchestra is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* geOrchestra. If not, see <http://www.gnu.org/licenses/>.
*/
package org.georchestra.security;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.message.BasicNameValuePair;
import org.georchestra.commons.configuration.GeorchestraConfiguration;
import org.georchestra.ogcservstatistics.log4j.OGCServiceMessageFormatter;
import org.georchestra.security.permissions.Permissions;
import org.georchestra.security.permissions.UriMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
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.RequestParam;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import com.google.common.io.Closer;
/**
* This proxy provides an indirect access to a remote host to retrieve data.
* Useful to overcome security constraints on client side.
* <p>
* There are two primary ways that the paths can be encoded:
* <ul>
* <li>The full url to forward to is encoded in a parameter called "url"</li>
* <li>The url is encoded as part of the path. Then the target should be
* defined (either in the targets-mapping.properties file of the datadir or in
* the targets map property of the proxyservlet.xml file)</li>
* </ul>
* Examples:
* <p>
* Assume the default target is http://xyz.com and the targets are:
* x:http://x.com, y:https://y.com
* </p>
* <ul>
* <li>http://this.com/context/path -- gives -- http://xyz.com/path</li>
* <li>http://this.com/context/x/path -- gives -- http://x.com/path</li>
* <li>http://this.com/context/y/path -- gives -- https://y.com/path</li>
* </ul>
* </li>
* </ul>
* </p>
*
* @author yoann.buch@gmail.com
* @author jesse.eichar@camptocamp.com
*/
@Controller
@RequestMapping("/*")
public class Proxy {
protected static final Log logger = LogFactory.getLog(Proxy.class.getPackage().getName());
protected static final Log statsLogger = LogFactory.getLog(Proxy.class.getPackage().getName() + ".statistics");
protected static final Log commonLogger = LogFactory.getLog(Proxy.class.getPackage().getName() + ".statistics-common");
protected enum RequestType {
GET, POST, DELETE, PUT, TRACE, OPTIONS, HEAD
}
@Autowired
private GeorchestraConfiguration georchestraConfiguration;
/**
* must be defined
*/
private String defaultTarget;
private Map<String, String> targets = Collections.emptyMap();
/**
* must be defined
*/
private HeadersManagementStrategy headerManagement = new HeadersManagementStrategy();
private FilterRequestsStrategy strategyForFilteringRequests = new AcceptAllRequests();
private List<String> requireCharsetContentTypes = Collections.emptyList();
private String defaultCharset = "UTF-8";
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private Permissions proxyPermissions = new Permissions();
private String proxyPermissionsFile;
private Integer httpClientTimeout = 300000;
public void setHttpClientTimeout(Integer timeout) {
this.httpClientTimeout = timeout;
}
public Integer getHttpClientTimeout() {
return httpClientTimeout;
}
public void init() throws Exception {
if (targets != null) {
for (String url : targets.values()) {
new URL(url); // test that it is a valid URL
}
}
if (proxyPermissionsFile != null) {
Closer closer = Closer.create();
try {
final ClassLoader classLoader = Proxy.class.getClassLoader();
InputStream inStream = closer.register(classLoader.getResourceAsStream(proxyPermissionsFile));
Map<String, Class<?>> aliases = Maps.newHashMap();
aliases.put(Permissions.class.getSimpleName().toLowerCase(), Permissions.class);
aliases.put(UriMatcher.class.getSimpleName().toLowerCase(), UriMatcher.class);
XStreamMarshaller unmarshaller = new XStreamMarshaller();
unmarshaller.setAliasesByType(aliases);
setProxyPermissions((Permissions) unmarshaller.unmarshal(new StreamSource(inStream)));
} finally {
closer.close();
}
}
// georchestra datadir autoconfiguration
// dependency injection / properties setter() are made by Spring before
// init() call
if ((georchestraConfiguration != null) && (georchestraConfiguration.activated())) {
logger.info("geOrchestra configuration detected, reconfiguration in progress ...");
Properties pTargets = georchestraConfiguration.loadCustomPropertiesFile("targets-mapping");
targets.clear();
for (String target : pTargets.stringPropertyNames()) {
targets.put(target, pTargets.getProperty(target));
}
logger.info("Done.");
}
}
/* ---------- start work around for no gateway option -------------- */
private Gateway gateway = new Gateway();
@RequestMapping(value = "/gateway", method = { GET, POST })
public void gateway(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
gateway.loadCredentialsPage(request, response);
}
@RequestMapping(value = "/testPage", method = { GET })
public void testPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
gateway.testPage(response);
}
/* ---------- end work around for no gateway option -------------- */
@RequestMapping(params = "login", method = { GET, POST })
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException {
String uri = request.getRequestURI();
if (uri.startsWith("sec")) {
uri = uri.substring(3);
} else if (uri.startsWith("/sec")) {
uri = uri.substring(4);
}
URIBuilder uriBuilder = new URIBuilder(uri);
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = (String) parameterNames.nextElement();
if (!"login".equals(paramName)) {
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
uriBuilder.setParameter(paramName, paramValues[i]);
}
}
}
redirectStrategy.sendRedirect(request, response, uriBuilder.build().toString());
}
@RequestMapping("/services_monitoring")
public void servicesMonitoring(HttpServletRequest request, HttpServletResponse response) throws IOException {
(new ServicesMonitoring(this.georchestraConfiguration.loadCustomPropertiesFile("targets-mapping"))).checkServices(request, response);
}
@RequestMapping(params = { "login", "url" }, method = { GET, POST })
public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws ServletException, IOException {
redirectStrategy.sendRedirect(request, response, sURL);
}
// ----------------- Method calls where request is encoded in a url
// parameter of request ----------------- //
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.POST)
public void handleUrlPOSTRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.POST, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.GET)
public void handleUrlGETRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.GET, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.DELETE)
public void handleUrlDELETERequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.DELETE, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.HEAD)
public void handleUrlHEADRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.HEAD, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.OPTIONS)
public void handleUrlOPTIONSRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.OPTIONS, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.PUT)
public void handleUrlPUTRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.PUT, sURL);
}
@RequestMapping(params = { "url", "!login" }, method = RequestMethod.TRACE)
public void handleUrlTRACERequest(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String sURL) throws IOException {
handleUrlParamRequest(request, response, RequestType.TRACE, sURL);
}
private void handleUrlParamRequest(HttpServletRequest request, HttpServletResponse response, RequestType type, String sURL) throws IOException {
if (request.getRequestURI().startsWith("/sec/proxy/")) {
testLegalContentType(request);
URL url;
InetAddress remoteAddress;
try {
url = new URL(sURL);
remoteAddress = InetAddress.getByName(url.getHost());
} catch (MalformedURLException e) { // not an url
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
} catch (UnknownHostException e){
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
/*
* Disallow :
* - Class C IP address (isSiteLocalAddress())
* - not allowed urls defined in permissions.xml
* - URL defined is target-mappings.xml (urlIsProtected())
*/
if (remoteAddress.isSiteLocalAddress() || proxyPermissions.isDenied(url) || urlIsProtected(request, url)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "URL is not allowed.");
return;
}
handleRequest(request, response, type, sURL, false);
} else {
handlePathEncodedRequests(request, response, type);
}
}
/**
* Indicates whether the requested URL is a one protected by the
* Security-proxy or not, e.g. urlIsProtected(mapfishapp) will generally
* return true (unless if mapfishapp is not configured on this geOrchestra
* instance, which is probably unlikely).
*
* @param request
* the HttpServletRequest
* @param url
* the requested url
* @return true if the url is protected by the SP, false otherwise.
*
* @throws IOException
*/
private boolean urlIsProtected(HttpServletRequest request, URL url) throws IOException {
if (isSameServer(request, url)) {
String requestURI = url.getPath();
String[] requestSegments = splitRequestPath(requestURI);
for (String target : targets.values()) {
if (samePathPrefix(requestSegments, target)) {
return true;
}
}
}
return false;
}
private boolean isSameServer(HttpServletRequest request, URL url) {
try {
return InetAddress.getByName(request.getServerName()).equals(InetAddress.getByName(url.getHost()));
} catch (UnknownHostException e) {
logger.error("Unknown host: " + request.getServerName());
return false;
}
}
private boolean samePathPrefix(String[] requestSegments, String target) throws MalformedURLException {
String[] targetSegments = splitRequestPath(new URL(target).getPath());
for (int i = 0; i < targetSegments.length; i++) {
String targetSegment = targetSegments[i];
if (!targetSegment.equals(requestSegments[i])) {
return false;
}
}
return true;
}
private String[] splitRequestPath(String requestURI) {
String[] requestSegments;
if (requestURI.charAt(0) == '/') {
requestSegments = StringUtils.split(requestURI.substring(1), '/');
} else {
requestSegments = StringUtils.split(requestURI, '/');
}
return requestSegments;
}
/**
* Since the URL param can access any url we need to control what it can
* request so it is not used for nefarious purposes. We are basing the
* control on contentType because it is supposed to be able to access any
* server.
*/
private void testLegalContentType(HttpServletRequest request) {
String contentType = request.getContentType();
if (contentType == null) {
return;
}
// focus only on type, not on the text encoding
String type = contentType.split(";")[0];
for (String validTypeContent : requireCharsetContentTypes) {
if (!validTypeContent.equals(type)) {
return;
}
}
throw new IllegalArgumentException("ContentType " + contentType
+ " is not permitted to be requested when the request is made through the URL parameter form.");
}
// ----------------- Method calls where request is encoded in path of
// request ----------------- //
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.GET)
public void handleGETRequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.GET);
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.POST)
public void handlePOSTRequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.POST);
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.DELETE)
public void handleDELETERequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.DELETE);
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.HEAD)
public void handleHEADRequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.HEAD);
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.OPTIONS)
public void handleOPTIONSRequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.OPTIONS);
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.PUT)
public void handlePUTRequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.PUT);
}
/**
* Default redirection to defaultTarget. By default returns a 302 redirect to '/header/'. The
* parameter can be customized in the security-proxy.properties file.
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/", params = { "!url", "!login" })
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(defaultTarget);
return;
}
@RequestMapping(params = { "!url", "!login" }, method = RequestMethod.TRACE)
public void handleTRACERequest(HttpServletRequest request, HttpServletResponse response) {
handlePathEncodedRequests(request, response, RequestType.TRACE);
}
// ----------------- Implementation methods ----------------- //
private String buildForwardRequestURL(HttpServletRequest request) {
String forwardRequestURI = request.getRequestURI();
String contextPath = request.getServletPath() + request.getContextPath();
if (forwardRequestURI.length() <= contextPath.length()) {
forwardRequestURI = "/";
} else {
forwardRequestURI = forwardRequestURI.substring(contextPath.length());
}
forwardRequestURI = forwardRequestURI.replaceAll("//", "/");
return forwardRequestURI;
}
/**
* Main entry point for methods where the request path is encoded in the
* path of the URL
*/
private void handlePathEncodedRequests(HttpServletRequest request, HttpServletResponse response, RequestType requestType) {
try {
String contextPath = request.getServletPath() + request.getContextPath();
String forwardRequestURI = buildForwardRequestURL(request);
logger.debug("handlePathEncodedRequests: -- Handling Request: " + requestType + ":" + forwardRequestURI + " from: " + request.getRemoteAddr());
String sURL = findTarget(forwardRequestURI);
if (sURL == null) {
response.sendError(404);
return;
}
URL url;
try {
url = new URL(sURL);
} catch (MalformedURLException e) {
throw new MalformedURLException(sURL + " is not a valid URL");
}
boolean sameHostAndPort = false;
try {
sameHostAndPort = isSameHostAndPort(request, url);
} catch (UnknownHostException e) {
logger.error("Unknown host in requested URL", e);
response.sendError(503);
return;
}
if (sameHostAndPort && (isRecursiveCallToProxy(forwardRequestURI, contextPath) || isRecursiveCallToProxy(url.getPath(), contextPath))) {
response.sendError(403, forwardRequestURI + " is a recursive call to this service. That is not a legal request");
}
if (request.getQueryString() != null && !isFormContentType(request)) {
StringBuilder query = new StringBuilder("?");
Enumeration paramNames = request.getParameterNames();
boolean needCasValidation = false;
while (paramNames.hasMoreElements()) {
String name = (String) paramNames.nextElement();
String[] values = request.getParameterValues(name);
for (String string : values) {
if (query.length() > 1) {
query.append('&');
}
// special case: if we have a ticket parameter and no
// authentication principal, we need to validate/open
// the session against CAS server
if ((request.getUserPrincipal() == null)
&& (name.equals(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER))) {
needCasValidation = true;
} else {
query.append(name);
query.append('=');
query.append(URLEncoder.encode(string, "UTF-8"));
}
}
}
sURL += query;
if ((needCasValidation) && (urlIsProtected(request, new URL(sURL)))) {
// loginUrl: sends a redirect to the client with a ?login (or &login if other arguments)
// since .*login patterns are protected by the SP, this would trigger an authentication
// onto CAS (which should succeed if the user is already connected onto the platform).
String loginUrl = String.format("%s%s%s", request.getPathInfo(), query, "login");
redirectStrategy.sendRedirect(request, response, loginUrl);
return;
}
}
handleRequest(request, response, requestType, sURL, true);
} catch (IOException e) {
logger.error("Error connecting to client", e);
}
}
private boolean isSameHostAndPort(HttpServletRequest request, URL url) throws IOException {
return isSameServer(request, url) && url.getPort() == request.getServerPort();
}
private String findTarget(String requestURI) {
String[] segments;
if (requestURI.charAt(0) == '/') {
segments = requestURI.substring(1).split("/");
} else {
segments = requestURI.split("/");
}
if (segments.length == 0) {
return null;
}
String target = targets.get(segments[0]);
if (target == null) {
return null;
} else {
StringBuilder builder = new StringBuilder("/");
for (int i = 1; i < segments.length; i++) {
String segment = segments[i];
builder.append(segment);
if (i + 1 < segments.length)
builder.append("/");
}
if (requestURI.endsWith("/") && builder.charAt(builder.length() - 1) != '/') {
builder.append('/');
}
return concat(target, builder);
}
}
private String concat(String target, StringBuilder builder) {
if (target == null) {
return null;
}
String target2 = target;
if (target.endsWith("/")) {
target2 = target.substring(0, target.length() - 1);
}
if (builder.charAt(0) != '/') {
builder.insert(0, '/');
}
return target2 + builder;
}
private String findMatchingTarget(HttpServletRequest request) {
String requestURI = buildForwardRequestURL(request);
return findMatchingTarget(requestURI);
}
private String findMatchingTarget(String requestURI) {
String[] segments = splitRequestPath(requestURI);
if (segments.length == 0) {
return null;
}
if (targets.containsKey(segments[0])) {
return segments[0];
} else {
return null;
}
}
private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse, RequestType requestType, String sURL, boolean localProxy) {
HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling();
RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build();
htb.setDefaultRequestConfig(config);
//
// Handle http proxy for external request.
// Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128)
htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
HttpClient httpclient = htb.build();
HttpResponse proxiedResponse = null;
int statusCode = 500;
try {
URL url = null;
try {
url = new URL(sURL);
} catch (MalformedURLException e) { // not an url
finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
// HTTP protocol is required
if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) {
finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "HTTP protocol expected. \"" + url.getProtocol() + "\" used.");
return;
}
// check if proxy must filter on final host
if (!strategyForFilteringRequests.allowRequest(url)) {
finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Host \"" + url.getHost() + "\" is not allowed to be requested");
return;
}
logger.debug("Final request -- " + sURL);
HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL);
headerManagement.configureRequestHeaders(request, proxyingRequest);
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Header[] originalHeaders = proxyingRequest.getHeaders("sec-orgname");
String org = "";
for (Header originalHeader : originalHeaders) {
org = originalHeader.getValue();
}
// no OGC SERVICE log if request going through /proxy/?url=
if (!request.getRequestURI().startsWith("/sec/proxy/")) {
String [] roles = new String[] {""};
try {
Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles");
if (rolesHeaders.length > 0) {
roles = rolesHeaders[0].getValue().split(";");
}
} catch (Exception e) {
logger.error("Unable to compute roles");
}
statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles));
}
} catch (Exception e) {
logger.error("Unable to log the request into the statistics logger", e);
}
if (localProxy) {
//
// Hack for geoserver
// Should not be here. We must use a ProxyTarget class and
// define
// if Host header should be forwarded or not.
//
request.getHeader("Host");
proxyingRequest.setHeader("Host", request.getHeader("Host"));
if (logger.isDebugEnabled()) {
logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue() + " for proxy request.");
}
}
proxiedResponse = executeHttpRequest(httpclient, proxyingRequest);
StatusLine statusLine = proxiedResponse.getStatusLine();
statusCode = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
if (reasonPhrase != null && statusCode > 399) {
if (logger.isWarnEnabled()) {
logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase);
}
if (statusCode == 401) {
//
// Handle case of basic authentication.
//
Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate");
finalResponse.setHeader("WWW-Authenticate", (authHeader == null) ? "Basic realm=\"Authentication required\"" : authHeader.getValue());
}
// 403 and 404 are handled by specific JSP files provided by the
// security-proxy webapp
if ((statusCode == 404) || (statusCode == 403)) {
finalResponse.sendError(statusCode);
return;
}
}
headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse, this.targets);
if (statusCode == 302 || statusCode == 301) {
adjustLocation(request, proxiedResponse, finalResponse);
}
// get content type
String contentType = null;
if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) {
contentType = proxiedResponse.getEntity().getContentType().getValue();
logger.debug("content-type detected: " + contentType);
}
// content type has to be valid
if (isCharsetRequiredForContentType(contentType)) {
doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType);
} else {
logger.debug("charset not required for contentType: " + contentType);
doHandleRequest(request, finalResponse, requestType, proxiedResponse);
}
} catch (IOException e) {
// connection problem with the host
logger.error("Exception occured when trying to connect to the remote host: ", e);
try {
finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} catch (IOException e2) {
// error occured while trying to return the
// "service unavailable status"
finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} finally {
httpclient.getConnectionManager().shutdown();
}
}
@VisibleForTesting
protected HttpResponse executeHttpRequest(HttpClient httpclient, HttpRequestBase proxyingRequest) throws IOException {
return httpclient.execute(proxyingRequest);
}
private void copyLocationHeaders(HttpResponse proxiedResponse, HttpServletResponse finalResponse) {
for (Header locationHeader : proxiedResponse.getHeaders("Location")) {
finalResponse.addHeader(locationHeader.getName(), locationHeader.getValue());
}
}
private void adjustLocation(HttpServletRequest request, HttpResponse proxiedResponse, HttpServletResponse finalResponse) {
if (logger.isDebugEnabled()) {
logger.debug("adjustLocation called for request: " + request.getRequestURI());
}
String target = findMatchingTarget(request);
if (logger.isDebugEnabled()) {
logger.debug("adjustLocation found target: " + target + " for request: " + request.getRequestURI());
}
if (target == null) {
copyLocationHeaders(proxiedResponse, finalResponse);
return;
}
String baseURL = targets.get(target);
URI baseURI = null;
try {
baseURI = new URI(baseURL);
} catch (URISyntaxException e) {
copyLocationHeaders(proxiedResponse, finalResponse);
return;
}
for (Header locationHeader : proxiedResponse.getHeaders("Location")) {
if (logger.isDebugEnabled()) {
logger.debug("adjustLocation process header: " + locationHeader.getValue());
}
try {
URI locationURI = new URI(locationHeader.getValue());
URI resolvedURI = baseURI.resolve(locationURI);
if (logger.isDebugEnabled()) {
logger.debug("Test location header: " + resolvedURI.toString() + " against: " + baseURI.toString());
}
if (resolvedURI.toString().startsWith(baseURI.toString())) {
// proxiedResponse.removeHeader(locationHeader);
String newLocation = "/" + target + "/" + resolvedURI.toString().substring(baseURI.toString().length());
finalResponse.addHeader("Location", newLocation);
// Header newLocationHeader = new BasicHeader("Location",
// newLocation);
if (logger.isDebugEnabled()) {
logger.debug("adjustLocation from: " + locationHeader.getValue() + " to " + newLocation);
}
// proxiedResponse.addHeader(newLocationHeader);
} else {
finalResponse.addHeader(locationHeader.getName(), locationHeader.getValue());
}
} catch (URISyntaxException e) {
finalResponse.addHeader(locationHeader.getName(), locationHeader.getValue());
}
}
}
/**
* Direct copy of response
*/
private void doHandleRequest(HttpServletRequest request, HttpServletResponse finalResponse, RequestType requestType, HttpResponse proxiedResponse)
throws IOException {
org.apache.http.StatusLine statusLine = proxiedResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
finalResponse.setStatus(statusCode);
HttpEntity entity = proxiedResponse.getEntity();
if (entity != null) {
// Send the Response
OutputStream outputStream = finalResponse.getOutputStream();
try {
entity.writeTo(outputStream);
} finally {
outputStream.flush();
outputStream.close();
}
}
}
private URI buildUri(URL url) throws URISyntaxException {
// Let URI constructor encode Path part
URI uri = new URI(url.getProtocol(),
url.getUserInfo(),
url.getHost(),
url.getPort(),
url.getPath(),
null, // Don't use query part because URI constructor will try to double encode it
// (query part is already encoded in sURL)
url.getRef());
// Reconstruct URL with encoded path from URI class and others parameters from URL class
StringBuilder rawUrl = new StringBuilder(url.getProtocol() + "://" + url.getHost());
if(url.getPort() != -1)
rawUrl.append(":" + String.valueOf(url.getPort()));
rawUrl.append(uri.getRawPath()); // Use encoded version from URI class
if(url.getQuery() != null)
rawUrl.append("?" + url.getQuery()); // Use already encoded query part
return new URI(rawUrl.toString());
}
private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL) throws IOException {
HttpRequestBase targetRequest;
try {
// Split URL
URL url = new URL(sURL);
URI uri = buildUri(url);
switch (requestType) {
case GET: {
logger.debug("New request is: " + sURL + "\nRequest is GET");
HttpGet get = new HttpGet(uri);
targetRequest = get;
break;
}
case POST: {
logger.debug("New request is: " + sURL + "\nRequest is POST");
HttpPost post = new HttpPost(uri);
HttpEntity entity;
request.setCharacterEncoding("UTF8");
if (isFormContentType(request)) {
logger.debug("Post is recognized as a form post.");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String[] v = request.getParameterValues(name);
for (String value : v) {
NameValuePair nv = new BasicNameValuePair(name, value);
parameters.add(nv);
}
}
String charset = request.getCharacterEncoding();
try {
Charset.forName(charset);
} catch (Throwable t) {
charset = null;
}
if (charset == null) {
charset = defaultCharset;
}
entity = new UrlEncodedFormEntity(parameters, charset);
post.setEntity(entity);
} else {
logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
int contentLength = request.getContentLength();
ServletInputStream inputStream = request.getInputStream();
entity = new InputStreamEntity(inputStream, contentLength);
}
post.setEntity(entity);
targetRequest = post;
break;
}
case TRACE: {
logger.debug("New request is: " + sURL + "\nRequest is TRACE");
HttpTrace post = new HttpTrace(uri);
targetRequest = post;
break;
}
case OPTIONS: {
logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");
HttpOptions post = new HttpOptions(uri);
targetRequest = post;
break;
}
case HEAD: {
logger.debug("New request is: " + sURL + "\nRequest is HEAD");
HttpHead post = new HttpHead(uri);
targetRequest = post;
break;
}
case PUT: {
logger.debug("New request is: " + sURL + "\nRequest is PUT");
HttpPut put = new HttpPut(uri);
put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));
targetRequest = put;
break;
}
case DELETE: {
logger.debug("New request is: " + sURL + "\nRequest is DELETE");
HttpDelete delete = new HttpDelete(uri);
targetRequest = delete;
break;
}
default: {
String msg = requestType + " not yet supported";
logger.error(msg);
throw new IllegalArgumentException(msg);
}
}
} catch (URISyntaxException e) {
logger.error("ERROR creating URI from " + sURL, e);
throw new IOException(e);
}
return targetRequest;
}
private boolean isFormContentType(HttpServletRequest request) {
if (request.getContentType() == null) {
return false;
}
String contentType = request.getContentType().split(";")[0].trim();
boolean equalsIgnoreCase = "application/x-www-form-urlencoded".equalsIgnoreCase(contentType);
return equalsIgnoreCase;
}
/**
* For certain requests (OGC Web services mainly), the charset is absolutely
* required. So for certain content types (xml-based normally) this method
* is called to detect the charset of the data. This method is a slow way of
* transferring data, so data of any significant size should not enter this
* method.
*/
private void doHandleRequestCharsetRequired(HttpServletRequest orignalRequest, HttpServletResponse finalResponse, RequestType requestType,
HttpResponse proxiedResponse, String contentType) {
InputStream streamFromServer = null;
OutputStream streamToClient = null;
try {
/*
* Here comes the tricky part because some host send files without
* the charset in the header, therefore we do not know how they are
* text encoded. It can result in serious issues on IE browsers when
* parsing those files. There is a workaround which consists to read
* the encoding within the file. It is made possible because this
* proxy mainly forwards xml files. They all have the encoding
* attribute in the first xml node.
*
* This is implemented as follows:
*
* A. The content type provides a charset: Nothing special, just
* send back the stream to the client B. There is no charset
* provided: The encoding has to be extracted from the file. The
* file is read in ASCII, which is common to many charsets, like
* that the encoding located in the first not can be retrieved. Once
* the charset is found, the content-type header is overridden and
* the charset is appended.
*
* /!\ Special case: whenever data are compressed in gzip/deflate
* the stream has to be uncompressed and re-compressed
*/
boolean isCharsetKnown = proxiedResponse.getEntity().getContentType().getValue().toLowerCase().contains("charset");
// String contentEncoding =
// getContentEncoding(proxiedResponse.getAllHeaders());
String contentEncoding = getContentEncoding(proxiedResponse.getHeaders("Content-Encoding"));
if (logger.isDebugEnabled()) {
String cskString = "\tisCharSetKnown=" + isCharsetKnown;
String cEString = "\tcontentEncoding=" + contentEncoding;
logger.debug("Charset is required so verifying that it has been added to the headers\n" + cskString + "\n" + cEString);
}
if (contentEncoding == null || isCharsetKnown) {
// A simple stream can do the job for data that is not in
// content encoded
// but also for data content encoded with a known charset
streamFromServer = proxiedResponse.getEntity().getContent();
streamToClient = finalResponse.getOutputStream();
} else if (!isCharsetKnown && ("gzip".equalsIgnoreCase(contentEncoding) || "x-gzip".equalsIgnoreCase(contentEncoding))) {
// the charset is unknown and the data are compressed in gzip
// we add the gzip wrapper to be able to read/write the stream
// content
streamFromServer = new GZIPInputStream(proxiedResponse.getEntity().getContent());
streamToClient = new GZIPOutputStream(finalResponse.getOutputStream());
} else if ("deflate".equalsIgnoreCase(contentEncoding) && !isCharsetKnown) {
// same but with deflate
streamFromServer = new DeflaterInputStream(proxiedResponse.getEntity().getContent());
streamToClient = new DeflaterOutputStream(finalResponse.getOutputStream());
} else {
doHandleRequest(orignalRequest, finalResponse, requestType, proxiedResponse);
return;
}
byte[] buf = new byte[1024]; // read maximum 1024 bytes
int len; // number of bytes read from the stream
boolean first = true; // helps to find the encoding once and only
// once
String s = ""; // piece of file that should contain the encoding
while ((len = streamFromServer.read(buf)) > 0) {
if (first && !isCharsetKnown) {
// charset is unknown try to find it in the file content
for (int i = 0; i < len; i++) {
s += (char) buf[i]; // get the beginning of the file as
// ASCII
}
// s has to be long enough to contain the encoding
if (s.length() > 200) {
if (logger.isTraceEnabled()) {
logger.trace("attempting to read charset from: " + s);
}
String charset = getCharset(s); // extract charset
if (charset == null) {
if (logger.isTraceEnabled()) {
logger.trace("unable to find charset from raw ASCII data. Trying to unzip it");
}
// the charset cannot be found, IE users must be
// warned
// that the request cannot be fulfilled, nothing
// good would happen otherwise
}
if (charset == null) {
String guessedCharset = null;
if (logger.isDebugEnabled()) {
logger.debug("unable to find charset so using the first one from the accept-charset request header");
}
String calculateDefaultCharset = calculateDefaultCharset(orignalRequest);
if (calculateDefaultCharset != null) {
guessedCharset = calculateDefaultCharset;
if (logger.isDebugEnabled()) {
logger.debug("hopefully the server responded with this charset: " + calculateDefaultCharset);
}
} else {
guessedCharset = defaultCharset;
if (logger.isDebugEnabled()) {
logger.debug("unable to find charset, so using default:" + defaultCharset);
}
}
String adjustedContentType = proxiedResponse.getEntity().getContentType().getValue() + ";charset=" + guessedCharset;
finalResponse.setHeader("Content-Type", adjustedContentType);
first = false; // we found the encoding, don't try
// to do it again
finalResponse.setCharacterEncoding(guessedCharset);
} else {
if (logger.isDebugEnabled()) {
logger.debug("found charset: " + charset);
}
String adjustedContentType = proxiedResponse.getEntity().getContentType().getValue() + ";charset=" + charset;
finalResponse.setHeader("Content-Type", adjustedContentType);
first = false; // we found the encoding, don't try
// to do it again
finalResponse.setCharacterEncoding(charset);
}
}
}
// for everyone, the stream is just forwarded to the client
streamToClient.write(buf, 0, len);
}
} catch (IOException e) {
// connection problem with the host
e.printStackTrace();
} finally {
IOException exc = close(streamFromServer);
exc = close(streamToClient, exc);
if (exc != null) {
logger.error("Error closing streams", exc);
}
}
}
private String calculateDefaultCharset(HttpServletRequest originalRequest) {
String acceptCharset = originalRequest.getHeader("accept-charset");
String calculatedCharset = null;
if (acceptCharset != null) {
calculatedCharset = acceptCharset.split(",")[0];
}
return calculatedCharset;
}
private IOException close(Closeable stream, IOException... previousExceptions) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
if (previousExceptions.length > 0) {
return previousExceptions[0];
}
return e;
}
if (previousExceptions.length > 0) {
return previousExceptions[0];
}
return null;
}
/**
* Extract the encoding from a string which is the header node of an xml
* file
*
* @param header
* String that should contain the encoding attribute and its
* value
* @return the charset. null if not found
*/
private String getCharset(String header) {
Pattern pattern = null;
String charset = null;
try {
// use a regexp but we could also use string functions such as
// indexOf...
pattern = Pattern.compile("encoding=(['\"])([A-Za-z]([A-Za-z0-9._]|-)*)");
} catch (Exception e) {
throw new RuntimeException("expression syntax invalid");
}
Matcher matcher = pattern.matcher(header);
if (matcher.find()) {
String encoding = matcher.group();
charset = encoding.split("['\"]")[1];
}
return charset;
}
/**
* Gets the encoding of the content sent by the remote host: extracts the
* content-encoding header
*
* @param headers
* headers of the HttpURLConnection
* @return null if not exists otherwise name of the encoding (gzip,
* deflate...)
*/
private String getContentEncoding(Header[] headers) {
if (headers == null || headers.length == 0) {
if (logger.isDebugEnabled()) {
logger.debug("No content-encoding header for this request.");
}
return null;
}
for (Header header : headers) {
// Header header = headers[i];
String headerName = header.getName();
if (logger.isDebugEnabled()) {
logger.debug("Check content-encoding against header: " + headerName + " : " + header.getValue());
}
if (headerName != null && "Content-Encoding".equalsIgnoreCase(headerName)) {
return header.getValue();
}
}
return null;
}
/**
* Check if the content type is accepted by the proxy
*
* @param contentType
* @return true: valid; false: not valid
*/
protected boolean isCharsetRequiredForContentType(final String contentType) {
if (contentType == null) {
return false;
}
// focus only on type, not on the text encoding
String type = contentType.split(";")[0];
for (String validTypeContent : requireCharsetContentTypes) {
logger.debug(contentType + " vs " + validTypeContent + "=" + (validTypeContent.equalsIgnoreCase(type)));
if (validTypeContent.equalsIgnoreCase(type)) {
return true;
}
}
return false;
}
private String[] filter(String[] one) {
ArrayList<String> result = new ArrayList<String>();
for (String string : one) {
if (string.length() > 0) {
result.add(string);
}
}
return result.toArray(new String[result.size()]);
}
/**
* Check to see if the call is recursive based on forwardRequestURI
* startsWith contextPath
*/
private boolean isRecursiveCallToProxy(String forwardRequestURI, String contextPath) {
String[] one = forwardRequestURI.split("/");
String[] two = contextPath.split("/");
one = filter(one);
two = filter(two);
if (one.length < two.length) {
return false;
}
boolean match = true;
for (int i = 0; i < two.length && i < one.length; i++) {
String s2 = two[i];
String s1 = one[i];
match &= s2.equalsIgnoreCase(s1);
}
return match;
}
public void setDefaultTarget(String defaultTarget) {
this.defaultTarget = defaultTarget;
}
public void setTargets(Map<String, String> targets) {
this.targets = targets;
}
public void setContextpath(String contextpath) {
// this.contextpath = contextpath;
}
public void setHeaderManagement(HeadersManagementStrategy headerManagement) {
this.headerManagement = headerManagement;
}
public void setRequireCharsetContentTypes(List<String> requireCharsetContentTypes) {
this.requireCharsetContentTypes = requireCharsetContentTypes;
}
public void setStrategyForFilteringRequests(FilterRequestsStrategy strategyForFilteringRequests) {
this.strategyForFilteringRequests = strategyForFilteringRequests;
}
public void setDefaultCharset(String defaultCharset) {
try {
Charset.forName(defaultCharset);
} catch (Throwable t) {
throw new IllegalArgumentException(defaultCharset + " is not supporte by current JVM");
}
this.defaultCharset = defaultCharset;
}
/**
*
* @param redirectStrategy
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
public void setProxyPermissionsFile(String proxyPermissionsFile) {
this.proxyPermissionsFile = proxyPermissionsFile;
}
public void setProxyPermissions(Permissions proxyPermissions) throws UnknownHostException {
this.proxyPermissions = proxyPermissions;
this.proxyPermissions.init();
}
public Permissions getProxyPermissions() {
return proxyPermissions;
}
}
| gpl-3.0 |
POPBL-6/middleware | src/test/java/tests/datatests/MessagesTests.java | 3866 | package tests.datatests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import data.Message;
import data.MessagePublication;
import data.MessagePublish;
import data.MessageReader;
import data.MessageSubscribe;
import data.MessageUnsubscribe;
public class MessagesTests {
private MessagePublish msgPublish;
private MessagePublication msgPublication;
private MessageSubscribe msgSubscribe;
private MessageUnsubscribe msgUnsubscribe;
@Rule
public Timeout globalTimeout = Timeout.seconds(10);
@Before
public void init() throws Exception {
msgPublish = new MessagePublish("Topic","Object","ASCII");
msgPublication = new MessagePublication(new MessagePublish("Topico",8),"Sender",7777);
msgSubscribe = new MessageSubscribe("Topico1","Topico2","Topico3");
msgUnsubscribe = new MessageUnsubscribe("Topico4","Topico5");
msgUnsubscribe.setCharset("ASCII");
}
@Test
public void testMessageFromByteArray() throws Exception {
assertTrue(Message.fromByteArray(msgPublish.toByteArray()) instanceof MessagePublish);
assertTrue(Message.fromByteArray(msgPublication.toByteArray()) instanceof MessagePublication);
assertTrue(Message.fromByteArray(msgSubscribe.toByteArray()) instanceof MessageSubscribe);
assertTrue(Message.fromByteArray(msgUnsubscribe.toByteArray()) instanceof MessageUnsubscribe);
}
@Test
public void testMessageReader() throws Exception {
MessageReader<Integer> reader = new MessageReader<Integer>();
assertEquals("testMessageReader bad read",8,reader.readObject(msgPublication).intValue());
}
@Test
public void testMessagePublishSerialization() throws Exception {
byte[] serialized = msgPublish.toByteArray();
MessagePublish msg2 = new MessagePublish(serialized);
assertEquals("testMessagePublishSerialization bad topic","Topic",msg2.getTopic());
assertEquals("testMessagePublishSerialization bad data","Object",msg2.getDataObject());
assertEquals("testMessagePublishSerialization bad charset","ASCII",msg2.getCharset());
}
@Test
public void testMessagePublicationSerialization() throws Exception {
byte[] serialized = msgPublication.toByteArray();
MessagePublication msg2 = new MessagePublication(serialized);
assertEquals("testMessagePublicationSerialization bad topic","Topico",msg2.getTopic());
assertEquals("testMessagePublicationSerialization bad data",8,msg2.getDataObject());
assertEquals("testMessagePublicationSerialization bad charset",Message.DEFAULT_CHARSET,msg2.getCharset());
assertEquals("testMessagePublicationSerialization bad sender","Sender",msg2.getSender());
assertEquals("testMessagePublicationSerialization bad timestamp", 7777,msg2.getTimestamp());
}
@Test
public void testMessageSubscribeSerialization() throws Exception {
byte[] serialized = msgSubscribe.toByteArray();
MessageSubscribe msg2 = new MessageSubscribe(serialized);
assertEquals("testMessageSubscribeSerialization bad charset",Message.DEFAULT_CHARSET,msg2.getCharset());
assertEquals("testMessageSubscribeSerialization bad topic1","Topico1",msg2.getTopics()[0]);
assertEquals("testMessageSubscribeSerialization bad topic2","Topico2",msg2.getTopics()[1]);
assertEquals("testMessageSubscribeSerialization bad topic3","Topico3",msg2.getTopics()[2]);
}
@Test
public void testMessageUnubscribeSerialization() throws Exception {
byte[] serialized = msgUnsubscribe.toByteArray();
MessageUnsubscribe msg2 = new MessageUnsubscribe(serialized);
assertEquals("testMessageUnubscribeSerialization bad charset","ASCII",msg2.getCharset());
assertEquals("testMessageUnubscribeSerialization bad topic1","Topico4",msg2.getTopics()[0]);
assertEquals("testMessageUnubscribeSerialization bad topic2","Topico5",msg2.getTopics()[1]);
}
}
| gpl-3.0 |
javocsoft/JavocsoftToolboxAS | toolbox/src/main/java/es/javocsoft/android/lib/toolbox/net/ssl/DefaultSSLBypassHttpClient.java | 4650 | package es.javocsoft.android.lib.toolbox.net.ssl;
import android.content.Context;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class is used to customize the behaviour of the Default HTTP client.
* <br><br>
* <b>IMPORTANT</b>: In this case, we ignore any SSL error in the connection. It is not recommendable
* in production environemnts. To avoid the need of this class usage, try to use a valid server
* certificate by a valid and known CA.
*
* @author JavocSoft, 2017
* @since 2017
* @version 1.0.0
*
*/
public class DefaultSSLBypassHttpClient extends DefaultHttpClient {
final Context context;
/**
* This Trust Manager accepts all certificates.
*/
public static final TrustManager EasyTrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
/**
* A custom DefaultHttpClient that accepts any certificate in a HTTPS connection.
*
* @param context
*/
public DefaultSSLBypassHttpClient(Context context) {
this.context = context;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
//AUXILIAR
/**
* Creates a custom SSL Socket Factory that trust ALL.
*/
private MySSLSocketFactory newSslSocketFactory() {
try {
KeyStore trusted = KeyStore.getInstance("BKS");
try {
trusted.load(null, null);
} finally {}
MySSLSocketFactory sslfactory = new MySSLSocketFactory(trusted);
sslfactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return sslfactory;
} catch (Exception e) {
throw new AssertionError(e);
}
}
/**
* Custom SSLSocketFactory that accepts any certificate ignoring
* any SSL error.
*/
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
}
| gpl-3.0 |
clingray/clingray-windows | ClingClient/ipc/ClingIPCCommand.cs | 670 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClingClient.ipc
{
[Serializable()]
public class ClingStartupCommand
{
public ClingStartupCommand()
{
}
public ClingStartupCommand(int action, string parameter)
{
this.action = action;
this.parameter = parameter;
}
public int action { get; set; }
public string parameter { get; set; }
public override string ToString()
{
return string.Format("action: {0}, parameter: {1}", action, parameter);
}
}
}
| gpl-3.0 |
forestbiotech-lab/sRNA-Portal-workflow | routes/db.js | 2523 | var express = require('express');
var router = express.Router();
var resolveHelper=require('./../components/miRNADB/helpers/resolveHelper');
var resolveCall = resolveHelper.resolveCall
/// --------- Call Declaration ----------------------------------------
var sequenceSearch = require('./../components/miRNADB/sequenceSearch2');
var nameSearch = require('./../components/miRNADB/nameSearch2');
var getFeatures = require('./../components/miRNADB/getFeatures');
var linkedMatureMiRNA = require('./../components/miRNADB/linkedMatureMiRNA');
var getAssayDataWithAnnotations=require('./../components/miRNADB/getAssayDataWithAnnotations')
var exportFile=require('./../components/miRNADB/exportFile')
/// --------------End -------------------------------------------------
/* GET sequences search */
router.get('/sequence', function(req, res, next) {
var errMsg="API Router /sequence get - "
var call=sequenceSearch
resolveCall(call,req,res,errMsg)
});
/* GET names search */
router.get('/name', function(req, res, next) {
var errMsg="API Router /name get - "
var call=nameSearch
resolveCall(call,req,res,errMsg)
});
/* GET feature */
router.get('/feature', function(req, res, next) {
var errMsg="API Router /feature get - "
var call=getFeatures
resolveCall(call,req,res,errMsg)
});
/* GET linked mature miRNA for graph */
router.get('/linkedMatureMiRNA', function(req, res, next) {
var errMsg="API Router /feature get - "
var call=linkedMatureMiRNA
resolveCall(call,req,res,errMsg)
});
router.get('/assaydata/:study', function(req, res, next) {
var errMsg="api Router /assayDat get - "
var call=getAssayDataWithAnnotations
resolveCall(call,req,res,errMsg)
});
router.get('/assaydata/:study/raw_reads.tsv',function(req,res,next){
exportFile.rawReadsFile(req).then(data=>{
res.set('Content-Type','text/tsv')
res.send(data)
},rej=>{
res.status(400).json(rej)
})
})
router.get('/assays/:study/matrix/outputs.tsv',function(req,res){
exportFile.assayOutputsFile(req).then(data=>{
res.set('Content-Type','text/tsv')
res.send(data)
},rej=>{
res.status(400).json(rej)
})
})
router.get('/assays/:study/design/study_design.tsv',function(req,res){
exportFile.studyDesignFile(req).then(data=>{
res.set('Content-Type','text/tsv')
res.send(data)
},rej=>{
res.status(400).json(rej)
})
})
router.get('/*',function(req,res){
let errMsg="API Router - Call is not defined"
let status=400
res.status(status).json(errMsg)
})
module.exports = router;
| gpl-3.0 |
jakey766/web_base | src/main/java/com/pk/service/admin/SysRoleService.java | 3188 | package com.pk.service.admin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pk.dao.admin.SysRoleDao;
import com.pk.dao.admin.SysRoleMenuDao;
import com.pk.framework.vo.PageResultVO;
import com.pk.framework.vo.PageSearchVO;
import com.pk.framework.vo.Result;
import com.pk.model.admin.SysRole;
import com.pk.model.admin.SysRoleMenu;
import com.pk.vo.admin.SysRoleMenuSearchVO;
@Service()
public class SysRoleService {
@Autowired
private SysRoleDao sysRoleDao;
@Autowired
private SysRoleMenuDao sysRoleMenuDao;
public List<SysRole> loadAll(){
return sysRoleDao.list(new PageSearchVO());
}
public Result list(PageSearchVO svo){
PageResultVO page = new PageResultVO();
int count = sysRoleDao.count(svo);
int totalPage = svo.getSize() < 1 ? 1 : (count + svo.getSize() - 1) / svo.getSize();
if(count > 0){
page.setList(sysRoleDao.list(svo));
}
page.setCount(count);
page.setPage(svo.getPage());
page.setPageCount(totalPage);
return Result.SUCCESS(page);
}
@Transactional
public Result add(SysRole role, String menus){
sysRoleDao.insert(role);
persistRoleMenu(role, menus);
return Result.SUCCESS(role);
}
@Transactional
public Result update(SysRole role, String menus){
sysRoleDao.update(role);
persistRoleMenu(role, menus);
return Result.SUCCESS(role);
}
@Transactional
public Result delete(int id){
sysRoleDao.delete(id);
return Result.SUCCESS();
}
public SysRole get(int id){
return sysRoleDao.get(id);
}
/**
* 更新角色-菜单关联
* @param role
* @param menus
*/
private void persistRoleMenu(SysRole role, String menus){
String[] ids = StringUtils.split(menus, ",");
List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
for(String id:ids){
if(id.length()<1)
continue;
SysRoleMenu rmenu = new SysRoleMenu();
rmenu.setRoleId(role.getId());
rmenu.setMenuId(Integer.parseInt(id));
list.add(rmenu);
}
sysRoleMenuDao.deleteByRoleId(role.getId());
sysRoleMenuDao.insertBatch(list);
}
public Map<String, Object> getWithMenuIds(int id) {
SysRole role = sysRoleDao.get(id);
if(role==null)
return null;
Map<String, Object> map = new HashMap<String, Object>();
map.put("role", role);
List<Integer> roleIds = new ArrayList<Integer>();
roleIds.add(role.getId());
SysRoleMenuSearchVO svo = new SysRoleMenuSearchVO();
svo.setRoleIds(roleIds);
List<SysRoleMenu> menus = sysRoleMenuDao.search(svo);
List<Integer> menuIds = new ArrayList<Integer>();
if(menus!=null){
for(SysRoleMenu menu:menus){
menuIds.add(menu.getMenuId());
}
}
map.put("menuIds", menuIds);
roleIds = null;
menus = null;
role = null;
svo = null;
return map;
}
}
| gpl-3.0 |
CuteHuiHui/htm | ht/src/main/java/com/yc/ht/service/SongService.java | 544 | package com.yc.ht.service;
import java.util.List;
import com.yc.ht.entity.PaginationBean;
import com.yc.ht.entity.Song;
public interface SongService {
List<Song> listSong();
List<Song> findSongById(String soid);
List<Song> findSongByName(String soname);
List<Song> findSongAndSingerById(String soid);
Song findSongName(Song song);
PaginationBean<Song> listSong(String pageS,String currP);
boolean removeSong(String soid);
boolean modifySong(Song song);
boolean addSong(Song song);
}
| gpl-3.0 |
VosDerrick/Volsteria | src/main/java/slimeknights/tconstruct/tools/common/client/GuiCraftingStation.java | 2386 | package slimeknights.tconstruct.tools.common.client;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import slimeknights.mantle.client.gui.GuiModule;
import slimeknights.tconstruct.tools.common.client.module.GuiSideInventory;
import slimeknights.tconstruct.tools.common.inventory.ContainerCraftingStation;
import slimeknights.tconstruct.tools.common.inventory.ContainerSideInventory;
import slimeknights.tconstruct.tools.common.inventory.ContainerTinkerStation;
import slimeknights.tconstruct.tools.common.tileentity.TileCraftingStation;
@SideOnly(Side.CLIENT)
public class GuiCraftingStation extends GuiTinkerStation {
private static final ResourceLocation BACKGROUND = new ResourceLocation("textures/gui/container/crafting_table.png");
protected final TileCraftingStation tile;
public GuiCraftingStation(InventoryPlayer playerInv, World world, BlockPos pos, TileCraftingStation tile) {
super(world, pos, (ContainerTinkerStation) tile.createContainer(playerInv, world, pos));
this.tile = tile;
if(inventorySlots instanceof ContainerCraftingStation) {
ContainerCraftingStation container = (ContainerCraftingStation) inventorySlots;
ContainerSideInventory chestContainer = container.getSubContainer(ContainerSideInventory.class);
if(chestContainer != null) {
if(chestContainer.getTile() instanceof TileEntityChest) {
// Fix: chests don't update their single/double chest status clientside once accessed
((TileEntityChest) chestContainer.getTile()).doubleChestHandler = null;
}
this.addModule(new GuiSideInventory(this, chestContainer, chestContainer.getSlotCount(), chestContainer.columns));
}
}
}
public boolean isSlotInChestInventory(Slot slot) {
GuiModule module = getModuleForSlot(slot.slotNumber);
return module instanceof GuiSideInventory;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
drawBackground(BACKGROUND);
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
}
| gpl-3.0 |
ruslanchasep/opencart | upload/admin/controller/sale/order.php | 74809 | <?php
class ControllerSaleOrder extends Controller {
private $error = array();
public function index() {
$this->load->language('sale/order');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('sale/order');
$this->getList();
}
public function add() {
$this->load->language('sale/order');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('sale/order');
$this->getForm();
}
public function edit() {
$this->load->language('sale/order');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('sale/order');
$this->getForm();
}
protected function getList() {
if (isset($this->request->get['filter_order_id'])) {
$filter_order_id = $this->request->get['filter_order_id'];
} else {
$filter_order_id = null;
}
if (isset($this->request->get['filter_customer'])) {
$filter_customer = $this->request->get['filter_customer'];
} else {
$filter_customer = null;
}
if (isset($this->request->get['filter_order_status'])) {
$filter_order_status = $this->request->get['filter_order_status'];
} else {
$filter_order_status = null;
}
if (isset($this->request->get['filter_total'])) {
$filter_total = $this->request->get['filter_total'];
} else {
$filter_total = null;
}
if (isset($this->request->get['filter_date_added'])) {
$filter_date_added = $this->request->get['filter_date_added'];
} else {
$filter_date_added = null;
}
if (isset($this->request->get['filter_date_modified'])) {
$filter_date_modified = $this->request->get['filter_date_modified'];
} else {
$filter_date_modified = null;
}
if (isset($this->request->get['sort'])) {
$sort = $this->request->get['sort'];
} else {
$sort = 'o.order_id';
}
if (isset($this->request->get['order'])) {
$order = $this->request->get['order'];
} else {
$order = 'DESC';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$url = '';
if (isset($this->request->get['filter_order_id'])) {
$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
}
if (isset($this->request->get['filter_customer'])) {
$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_order_status'])) {
$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
}
if (isset($this->request->get['filter_total'])) {
$url .= '&filter_total=' . $this->request->get['filter_total'];
}
if (isset($this->request->get['filter_date_added'])) {
$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
}
if (isset($this->request->get['filter_date_modified'])) {
$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
}
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
);
$data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'], 'SSL');
$data['shipping'] = $this->url->link('sale/order/shipping', 'token=' . $this->session->data['token'], 'SSL');
$data['add'] = $this->url->link('sale/order/add', 'token=' . $this->session->data['token'], 'SSL');
$data['orders'] = array();
$filter_data = array(
'filter_order_id' => $filter_order_id,
'filter_customer' => $filter_customer,
'filter_order_status' => $filter_order_status,
'filter_total' => $filter_total,
'filter_date_added' => $filter_date_added,
'filter_date_modified' => $filter_date_modified,
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $this->config->get('config_limit_admin'),
'limit' => $this->config->get('config_limit_admin')
);
$order_total = $this->model_sale_order->getTotalOrders($filter_data);
$results = $this->model_sale_order->getOrders($filter_data);
foreach ($results as $result) {
$data['orders'][] = array(
'order_id' => $result['order_id'],
'customer' => $result['customer'],
'status' => $result['status'],
'total' => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
'shipping_code' => $result['shipping_code'],
'view' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
'edit' => $this->url->link('sale/order/edit', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
);
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_list'] = $this->language->get('text_list');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['text_missing'] = $this->language->get('text_missing');
$data['text_loading'] = $this->language->get('text_loading');
$data['column_order_id'] = $this->language->get('column_order_id');
$data['column_customer'] = $this->language->get('column_customer');
$data['column_status'] = $this->language->get('column_status');
$data['column_total'] = $this->language->get('column_total');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_date_modified'] = $this->language->get('column_date_modified');
$data['column_action'] = $this->language->get('column_action');
$data['entry_return_id'] = $this->language->get('entry_return_id');
$data['entry_order_id'] = $this->language->get('entry_order_id');
$data['entry_customer'] = $this->language->get('entry_customer');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_date_added'] = $this->language->get('entry_date_added');
$data['entry_date_modified'] = $this->language->get('entry_date_modified');
$data['button_invoice_print'] = $this->language->get('button_invoice_print');
$data['button_shipping_print'] = $this->language->get('button_shipping_print');
$data['button_add'] = $this->language->get('button_add');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_filter'] = $this->language->get('button_filter');
$data['button_view'] = $this->language->get('button_view');
$data['button_ip_add'] = $this->language->get('button_ip_add');
$data['token'] = $this->session->data['token'];
if (isset($this->request->post['selected'])) {
$data['selected'] = (array)$this->request->post['selected'];
} else {
$data['selected'] = array();
}
$url = '';
if (isset($this->request->get['filter_order_id'])) {
$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
}
if (isset($this->request->get['filter_customer'])) {
$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_order_status'])) {
$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
}
if (isset($this->request->get['filter_total'])) {
$url .= '&filter_total=' . $this->request->get['filter_total'];
}
if (isset($this->request->get['filter_date_added'])) {
$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
}
if (isset($this->request->get['filter_date_modified'])) {
$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
}
if ($order == 'ASC') {
$url .= '&order=DESC';
} else {
$url .= '&order=ASC';
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['sort_order'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.order_id' . $url, 'SSL');
$data['sort_customer'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, 'SSL');
$data['sort_status'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=status' . $url, 'SSL');
$data['sort_total'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.total' . $url, 'SSL');
$data['sort_date_added'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_added' . $url, 'SSL');
$data['sort_date_modified'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_modified' . $url, 'SSL');
$url = '';
if (isset($this->request->get['filter_order_id'])) {
$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
}
if (isset($this->request->get['filter_customer'])) {
$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_order_status'])) {
$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
}
if (isset($this->request->get['filter_total'])) {
$url .= '&filter_total=' . $this->request->get['filter_total'];
}
if (isset($this->request->get['filter_date_added'])) {
$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
}
if (isset($this->request->get['filter_date_modified'])) {
$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
}
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
$pagination = new Pagination();
$pagination->total = $order_total;
$pagination->page = $page;
$pagination->limit = $this->config->get('config_limit_admin');
$pagination->url = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
$data['pagination'] = $pagination->render();
$data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));
$data['filter_order_id'] = $filter_order_id;
$data['filter_customer'] = $filter_customer;
$data['filter_order_status'] = $filter_order_status;
$data['filter_total'] = $filter_total;
$data['filter_date_added'] = $filter_date_added;
$data['filter_date_modified'] = $filter_date_modified;
$this->load->model('localisation/order_status');
$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
$data['sort'] = $sort;
$data['order'] = $order;
$data['store'] = HTTPS_CATALOG;
// API login
$this->load->model('user/api');
$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
if ($api_info) {
$data['api_id'] = $api_info['api_id'];
$data['api_key'] = $api_info['key'];
$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
} else {
$data['api_id'] = '';
$data['api_key'] = '';
$data['api_ip'] = '';
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('sale/order_list.tpl', $data));
}
public function getForm() {
$this->load->model('customer/customer');
$data['heading_title'] = $this->language->get('heading_title');
$data['text_form'] = !isset($this->request->get['order_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_default'] = $this->language->get('text_default');
$data['text_select'] = $this->language->get('text_select');
$data['text_none'] = $this->language->get('text_none');
$data['text_loading'] = $this->language->get('text_loading');
$data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
$data['text_product'] = $this->language->get('text_product');
$data['text_voucher'] = $this->language->get('text_voucher');
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['entry_store'] = $this->language->get('entry_store');
$data['entry_customer'] = $this->language->get('entry_customer');
$data['entry_customer_group'] = $this->language->get('entry_customer_group');
$data['entry_firstname'] = $this->language->get('entry_firstname');
$data['entry_lastname'] = $this->language->get('entry_lastname');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_telephone'] = $this->language->get('entry_telephone');
$data['entry_fax'] = $this->language->get('entry_fax');
$data['entry_comment'] = $this->language->get('entry_comment');
$data['entry_affiliate'] = $this->language->get('entry_affiliate');
$data['entry_address'] = $this->language->get('entry_address');
$data['entry_company'] = $this->language->get('entry_company');
$data['entry_address_1'] = $this->language->get('entry_address_1');
$data['entry_address_2'] = $this->language->get('entry_address_2');
$data['entry_city'] = $this->language->get('entry_city');
$data['entry_postcode'] = $this->language->get('entry_postcode');
$data['entry_zone'] = $this->language->get('entry_zone');
$data['entry_zone_code'] = $this->language->get('entry_zone_code');
$data['entry_country'] = $this->language->get('entry_country');
$data['entry_product'] = $this->language->get('entry_product');
$data['entry_option'] = $this->language->get('entry_option');
$data['entry_quantity'] = $this->language->get('entry_quantity');
$data['entry_to_name'] = $this->language->get('entry_to_name');
$data['entry_to_email'] = $this->language->get('entry_to_email');
$data['entry_from_name'] = $this->language->get('entry_from_name');
$data['entry_from_email'] = $this->language->get('entry_from_email');
$data['entry_theme'] = $this->language->get('entry_theme');
$data['entry_message'] = $this->language->get('entry_message');
$data['entry_amount'] = $this->language->get('entry_amount');
$data['entry_currency'] = $this->language->get('entry_currency');
$data['entry_shipping_method'] = $this->language->get('entry_shipping_method');
$data['entry_payment_method'] = $this->language->get('entry_payment_method');
$data['entry_coupon'] = $this->language->get('entry_coupon');
$data['entry_voucher'] = $this->language->get('entry_voucher');
$data['entry_reward'] = $this->language->get('entry_reward');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['column_product'] = $this->language->get('column_product');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['button_save'] = $this->language->get('button_save');
$data['button_cancel'] = $this->language->get('button_cancel');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_back'] = $this->language->get('button_back');
$data['button_product_add'] = $this->language->get('button_product_add');
$data['button_voucher_add'] = $this->language->get('button_voucher_add');
$data['button_apply'] = $this->language->get('button_apply');
$data['button_upload'] = $this->language->get('button_upload');
$data['button_remove'] = $this->language->get('button_remove');
$data['button_ip_add'] = $this->language->get('button_ip_add');
$data['tab_order'] = $this->language->get('tab_order');
$data['tab_customer'] = $this->language->get('tab_customer');
$data['tab_payment'] = $this->language->get('tab_payment');
$data['tab_shipping'] = $this->language->get('tab_shipping');
$data['tab_product'] = $this->language->get('tab_product');
$data['tab_voucher'] = $this->language->get('tab_voucher');
$data['tab_total'] = $this->language->get('tab_total');
$data['token'] = $this->session->data['token'];
$url = '';
if (isset($this->request->get['filter_order_id'])) {
$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
}
if (isset($this->request->get['filter_customer'])) {
$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_order_status'])) {
$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
}
if (isset($this->request->get['filter_total'])) {
$url .= '&filter_total=' . $this->request->get['filter_total'];
}
if (isset($this->request->get['filter_date_added'])) {
$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
}
if (isset($this->request->get['filter_date_modified'])) {
$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
}
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
);
$data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');
if (isset($this->request->get['order_id'])) {
$order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);
}
if (!empty($order_info)) {
$data['order_id'] = $this->request->get['order_id'];
$data['store_id'] = $order_info['store_id'];
$data['customer'] = $order_info['customer'];
$data['customer_id'] = $order_info['customer_id'];
$data['customer_group_id'] = $order_info['customer_group_id'];
$data['firstname'] = $order_info['firstname'];
$data['lastname'] = $order_info['lastname'];
$data['email'] = $order_info['email'];
$data['telephone'] = $order_info['telephone'];
$data['fax'] = $order_info['fax'];
$data['account_custom_field'] = $order_info['custom_field'];
$this->load->model('customer/customer');
$data['addresses'] = $this->model_customer_customer->getAddresses($order_info['customer_id']);
$data['payment_firstname'] = $order_info['payment_firstname'];
$data['payment_lastname'] = $order_info['payment_lastname'];
$data['payment_company'] = $order_info['payment_company'];
$data['payment_address_1'] = $order_info['payment_address_1'];
$data['payment_address_2'] = $order_info['payment_address_2'];
$data['payment_city'] = $order_info['payment_city'];
$data['payment_postcode'] = $order_info['payment_postcode'];
$data['payment_country_id'] = $order_info['payment_country_id'];
$data['payment_zone_id'] = $order_info['payment_zone_id'];
$data['payment_custom_field'] = $order_info['payment_custom_field'];
$data['payment_method'] = $order_info['payment_method'];
$data['payment_code'] = $order_info['payment_code'];
$data['shipping_firstname'] = $order_info['shipping_firstname'];
$data['shipping_lastname'] = $order_info['shipping_lastname'];
$data['shipping_company'] = $order_info['shipping_company'];
$data['shipping_address_1'] = $order_info['shipping_address_1'];
$data['shipping_address_2'] = $order_info['shipping_address_2'];
$data['shipping_city'] = $order_info['shipping_city'];
$data['shipping_postcode'] = $order_info['shipping_postcode'];
$data['shipping_country_id'] = $order_info['shipping_country_id'];
$data['shipping_zone_id'] = $order_info['shipping_zone_id'];
$data['shipping_custom_field'] = $order_info['shipping_custom_field'];
$data['shipping_method'] = $order_info['shipping_method'];
$data['shipping_code'] = $order_info['shipping_code'];
// Products
$data['order_products'] = array();
$products = $this->model_sale_order->getOrderProducts($this->request->get['order_id']);
foreach ($products as $product) {
$data['order_products'][] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']),
'quantity' => $product['quantity'],
'price' => $product['price'],
'total' => $product['total'],
'reward' => $product['reward']
);
}
// Vouchers
$data['order_vouchers'] = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);
$data['coupon'] = '';
$data['voucher'] = '';
$data['reward'] = '';
$data['order_totals'] = array();
$order_totals = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);
foreach ($order_totals as $order_total) {
// If coupon, voucher or reward points
$start = strpos($order_total['title'], '(') + 1;
$end = strrpos($order_total['title'], ')');
if ($start && $end) {
$data[$order_total['code']] = substr($order_total['title'], $start, $end - $start);
}
}
$data['order_status_id'] = $order_info['order_status_id'];
$data['comment'] = $order_info['comment'];
$data['affiliate_id'] = $order_info['affiliate_id'];
$data['affiliate'] = $order_info['affiliate_firstname'] . ' ' . $order_info['affiliate_lastname'];
$data['currency_code'] = $order_info['currency_code'];
} else {
$data['order_id'] = 0;
$data['store_id'] = '';
$data['customer'] = '';
$data['customer_id'] = '';
$data['customer_group_id'] = $this->config->get('config_customer_group_id');
$data['firstname'] = '';
$data['lastname'] = '';
$data['email'] = '';
$data['telephone'] = '';
$data['fax'] = '';
$data['customer_custom_field'] = array();
$data['addresses'] = array();
$data['payment_firstname'] = '';
$data['payment_lastname'] = '';
$data['payment_company'] = '';
$data['payment_address_1'] = '';
$data['payment_address_2'] = '';
$data['payment_city'] = '';
$data['payment_postcode'] = '';
$data['payment_country_id'] = '';
$data['payment_zone_id'] = '';
$data['payment_custom_field'] = array();
$data['payment_method'] = '';
$data['payment_code'] = '';
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_postcode'] = '';
$data['shipping_country_id'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_custom_field'] = array();
$data['shipping_method'] = '';
$data['shipping_code'] = '';
$data['order_products'] = array();
$data['order_vouchers'] = array();
$data['order_totals'] = array();
$data['order_status_id'] = $this->config->get('config_order_status_id');
$data['comment'] = '';
$data['affiliate_id'] = '';
$data['affiliate'] = '';
$data['currency_code'] = $this->config->get('config_currency');
$data['coupon'] = '';
$data['voucher'] = '';
$data['reward'] = '';
}
// Stores
$this->load->model('setting/store');
$data['stores'] = array();
$data['stores'][] = array(
'store_id' => 0,
'name' => $this->language->get('text_default'),
'href' => HTTP_CATALOG
);
$results = $this->model_setting_store->getStores();
foreach ($results as $result) {
$data['stores'][] = array(
'store_id' => $result['store_id'],
'name' => $result['name'],
'href' => $result['url']
);
}
// Customer Groups
$this->load->model('customer/customer_group');
$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
// Custom Fields
$this->load->model('customer/custom_field');
$data['custom_fields'] = array();
$filter_data = array(
'sort' => 'cf.sort_order',
'order' => 'ASC'
);
$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);
foreach ($custom_fields as $custom_field) {
$data['custom_fields'][] = array(
'custom_field_id' => $custom_field['custom_field_id'],
'custom_field_value' => $this->model_customer_custom_field->getCustomFieldValues($custom_field['custom_field_id']),
'name' => $custom_field['name'],
'value' => $custom_field['value'],
'type' => $custom_field['type'],
'location' => $custom_field['location'],
'sort_order' => $custom_field['sort_order']
);
}
$this->load->model('localisation/order_status');
$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
$this->load->model('localisation/country');
$data['countries'] = $this->model_localisation_country->getCountries();
$this->load->model('localisation/currency');
$data['currencies'] = $this->model_localisation_currency->getCurrencies();
$data['voucher_min'] = $this->config->get('config_voucher_min');
$this->load->model('sale/voucher_theme');
$data['voucher_themes'] = $this->model_sale_voucher_theme->getVoucherThemes();
// API login
$this->load->model('user/api');
$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
if ($api_info) {
$data['api_id'] = $api_info['api_id'];
$data['api_key'] = $api_info['key'];
$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
} else {
$data['api_id'] = '';
$data['api_key'] = '';
$data['api_ip'] = '';
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('sale/order_form.tpl', $data));
}
public function info() {
$this->load->model('sale/order');
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info) {
$this->load->language('sale/order');
$this->document->setTitle($this->language->get('heading_title'));
$data['heading_title'] = $this->language->get('heading_title');
$data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_customer_detail'] = $this->language->get('text_customer_detail');
$data['text_option'] = $this->language->get('text_option');
$data['text_store'] = $this->language->get('text_store');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_customer'] = $this->language->get('text_customer');
$data['text_customer_group'] = $this->language->get('text_customer_group');
$data['text_email'] = $this->language->get('text_email');
$data['text_telephone'] = $this->language->get('text_telephone');
$data['text_invoice'] = $this->language->get('text_invoice');
$data['text_reward'] = $this->language->get('text_reward');
$data['text_affiliate'] = $this->language->get('text_affiliate');
$data['text_order'] = sprintf($this->language->get('text_order'), $this->request->get['order_id']);
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_comment'] = $this->language->get('text_comment');
$data['text_account_custom_field'] = $this->language->get('text_account_custom_field');
$data['text_payment_custom_field'] = $this->language->get('text_payment_custom_field');
$data['text_shipping_custom_field'] = $this->language->get('text_shipping_custom_field');
$data['text_browser'] = $this->language->get('text_browser');
$data['text_ip'] = $this->language->get('text_ip');
$data['text_forwarded_ip'] = $this->language->get('text_forwarded_ip');
$data['text_user_agent'] = $this->language->get('text_user_agent');
$data['text_accept_language'] = $this->language->get('text_accept_language');
$data['text_history'] = $this->language->get('text_history');
$data['text_history_add'] = $this->language->get('text_history_add');
$data['text_loading'] = $this->language->get('text_loading');
$data['column_product'] = $this->language->get('column_product');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_notify'] = $this->language->get('entry_notify');
$data['entry_comment'] = $this->language->get('entry_comment');
$data['button_invoice_print'] = $this->language->get('button_invoice_print');
$data['button_shipping_print'] = $this->language->get('button_shipping_print');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_cancel'] = $this->language->get('button_cancel');
$data['button_generate'] = $this->language->get('button_generate');
$data['button_reward_add'] = $this->language->get('button_reward_add');
$data['button_reward_remove'] = $this->language->get('button_reward_remove');
$data['button_commission_add'] = $this->language->get('button_commission_add');
$data['button_commission_remove'] = $this->language->get('button_commission_remove');
$data['button_history_add'] = $this->language->get('button_history_add');
$data['button_ip_add'] = $this->language->get('button_ip_add');
$data['tab_history'] = $this->language->get('tab_history');
$data['tab_additional'] = $this->language->get('tab_additional');
$data['token'] = $this->session->data['token'];
$url = '';
if (isset($this->request->get['filter_order_id'])) {
$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
}
if (isset($this->request->get['filter_customer'])) {
$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_order_status'])) {
$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
}
if (isset($this->request->get['filter_total'])) {
$url .= '&filter_total=' . $this->request->get['filter_total'];
}
if (isset($this->request->get['filter_date_added'])) {
$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
}
if (isset($this->request->get['filter_date_modified'])) {
$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
}
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
);
$data['shipping'] = $this->url->link('sale/order/shipping', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
$data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
$data['edit'] = $this->url->link('sale/order/edit', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
$data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');
$data['order_id'] = $this->request->get['order_id'];
$data['store_name'] = $order_info['store_name'];
$data['store_url'] = $order_info['store_url'];
if ($order_info['invoice_no']) {
$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
} else {
$data['invoice_no'] = '';
}
$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
$data['firstname'] = $order_info['firstname'];
$data['lastname'] = $order_info['lastname'];
if ($order_info['customer_id']) {
$data['customer'] = $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $order_info['customer_id'], 'SSL');
} else {
$data['customer'] = '';
}
$this->load->model('customer/customer_group');
$customer_group_info = $this->model_customer_customer_group->getCustomerGroup($order_info['customer_group_id']);
if ($customer_group_info) {
$data['customer_group'] = $customer_group_info['name'];
} else {
$data['customer_group'] = '';
}
$data['email'] = $order_info['email'];
$data['telephone'] = $order_info['telephone'];
$data['shipping_method'] = $order_info['shipping_method'];
$data['payment_method'] = $order_info['payment_method'];
// Payment Address
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
// Shipping Address
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['products'] = array();
$products = $this->model_sale_order->getOrderProducts($this->request->get['order_id']);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);
foreach ($options as $option) {
if ($option['type'] != 'file') {
$option_data[] = array(
'name' => $option['name'],
'value' => $option['value'],
'type' => $option['type']
);
} else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$option_data[] = array(
'name' => $option['name'],
'value' => $upload_info['name'],
'type' => $option['type'],
'href' => $this->url->link('tool/upload/download', 'token=' . $this->session->data['token'] . '&code=' . $upload_info['code'], 'SSL')
);
}
}
}
$data['products'][] = array(
'order_product_id' => $product['order_product_id'],
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
'href' => $this->url->link('catalog/product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $product['product_id'], 'SSL')
);
}
$data['vouchers'] = array();
$vouchers = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);
foreach ($vouchers as $voucher) {
$data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
'href' => $this->url->link('sale/voucher/edit', 'token=' . $this->session->data['token'] . '&voucher_id=' . $voucher['voucher_id'], 'SSL')
);
}
$data['totals'] = array();
$totals = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['comment'] = nl2br($order_info['comment']);
$this->load->model('customer/customer');
$data['reward'] = $order_info['reward'];
$data['reward_total'] = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($this->request->get['order_id']);
$data['affiliate_firstname'] = $order_info['affiliate_firstname'];
$data['affiliate_lastname'] = $order_info['affiliate_lastname'];
if ($order_info['affiliate_id']) {
$data['affiliate'] = $this->url->link('marketing/affiliate/edit', 'token=' . $this->session->data['token'] . '&affiliate_id=' . $order_info['affiliate_id'], 'SSL');
} else {
$data['affiliate'] = '';
}
$data['commission'] = $this->currency->format($order_info['commission'], $order_info['currency_code'], $order_info['currency_value']);
$this->load->model('marketing/affiliate');
$data['commission_total'] = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($this->request->get['order_id']);
$this->load->model('localisation/order_status');
$order_status_info = $this->model_localisation_order_status->getOrderStatus($order_info['order_status_id']);
if ($order_status_info) {
$data['order_status'] = $order_status_info['name'];
} else {
$data['order_status'] = '';
}
$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
$data['order_status_id'] = $order_info['order_status_id'];
$data['account_custom_field'] = $order_info['custom_field'];
// Uploaded files
$this->load->model('tool/upload');
// Custom Fields
$this->load->model('customer/custom_field');
$data['account_custom_fields'] = array();
$filter_data = array(
'sort' => 'cf.sort_order',
'order' => 'ASC',
);
$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);
foreach ($custom_fields as $custom_field) {
if ($custom_field['location'] == 'account' && isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['custom_field'][$custom_field['custom_field_id']]);
if ($custom_field_value_info) {
$data['account_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name']
);
}
}
if ($custom_field['type'] == 'checkbox' && is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
foreach ($order_info['custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);
if ($custom_field_value_info) {
$data['account_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name']
);
}
}
}
if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
$data['account_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $order_info['custom_field'][$custom_field['custom_field_id']]
);
}
if ($custom_field['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($order_info['custom_field'][$custom_field['custom_field_id']]);
if ($upload_info) {
$data['account_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $upload_info['name']
);
}
}
}
}
// Custom fields
$data['payment_custom_fields'] = array();
foreach ($custom_fields as $custom_field) {
if ($custom_field['location'] == 'address' && isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['payment_custom_field'][$custom_field['custom_field_id']]);
if ($custom_field_value_info) {
$data['payment_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
if ($custom_field['type'] == 'checkbox' && is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
foreach ($order_info['payment_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);
if ($custom_field_value_info) {
$data['payment_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
}
if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
$data['payment_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $order_info['payment_custom_field'][$custom_field['custom_field_id']],
'sort_order' => $custom_field['sort_order']
);
}
if ($custom_field['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($order_info['payment_custom_field'][$custom_field['custom_field_id']]);
if ($upload_info) {
$data['payment_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $upload_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
}
}
// Shipping
$data['shipping_custom_fields'] = array();
foreach ($custom_fields as $custom_field) {
if ($custom_field['location'] == 'address' && isset($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);
if ($custom_field_value_info) {
$data['shipping_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
if ($custom_field['type'] == 'checkbox' && is_array($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
foreach ($order_info['shipping_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);
if ($custom_field_value_info) {
$data['shipping_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $custom_field_value_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
}
if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
$data['shipping_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $order_info['shipping_custom_field'][$custom_field['custom_field_id']],
'sort_order' => $custom_field['sort_order']
);
}
if ($custom_field['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);
if ($upload_info) {
$data['shipping_custom_fields'][] = array(
'name' => $custom_field['name'],
'value' => $upload_info['name'],
'sort_order' => $custom_field['sort_order']
);
}
}
}
}
$data['ip'] = $order_info['ip'];
$data['forwarded_ip'] = $order_info['forwarded_ip'];
$data['user_agent'] = $order_info['user_agent'];
$data['accept_language'] = $order_info['accept_language'];
// Additional Tabs
$data['tabs'] = array();
$this->load->model('extension/extension');
$content = $this->load->controller('payment/' . $order_info['payment_code'] . '/order');
if ($content) {
$this->load->language('payment/' . $order_info['payment_code']);
$data['tabs'][] = array(
'code' => $order_info['payment_code'],
'title' => $this->language->get('heading_title'),
'content' => $content
);
}
$extensions = $this->model_extension_extension->getInstalled('fraud');
foreach ($extensions as $extension) {
if ($this->config->get($extension . '_status')) {
$this->load->language('fraud/' . $extension);
$content = $this->load->controller('fraud/' . $extension . '/order');
if ($content) {
$data['tabs'][] = array(
'code' => $extension,
'title' => $this->language->get('heading_title'),
'content' => $content
);
}
}
}
// API login
$this->load->model('user/api');
$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
if ($api_info) {
$data['api_id'] = $api_info['api_id'];
$data['api_key'] = $api_info['key'];
$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
} else {
$data['api_id'] = '';
$data['api_key'] = '';
$data['api_ip'] = '';
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('sale/order_info.tpl', $data));
} else {
$this->load->language('error/not_found');
$this->document->setTitle($this->language->get('heading_title'));
$data['heading_title'] = $this->language->get('heading_title');
$data['text_not_found'] = $this->language->get('text_not_found');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
);
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('error/not_found.tpl', $data));
}
}
public function createInvoiceNo() {
$this->load->language('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'sale/order')) {
$json['error'] = $this->language->get('error_permission');
} elseif (isset($this->request->get['order_id'])) {
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('sale/order');
$invoice_no = $this->model_sale_order->createInvoiceNo($order_id);
if ($invoice_no) {
$json['invoice_no'] = $invoice_no;
} else {
$json['error'] = $this->language->get('error_action');
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function addReward() {
$this->load->language('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'sale/order')) {
$json['error'] = $this->language->get('error_permission');
} else {
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('sale/order');
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info && $order_info['customer_id'] && ($order_info['reward'] > 0)) {
$this->load->model('customer/customer');
$reward_total = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($order_id);
if (!$reward_total) {
$this->model_customer_customer->addReward($order_info['customer_id'], $this->language->get('text_order_id') . ' #' . $order_id, $order_info['reward'], $order_id);
}
}
$json['success'] = $this->language->get('text_reward_added');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function removeReward() {
$this->load->language('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'sale/order')) {
$json['error'] = $this->language->get('error_permission');
} else {
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('sale/order');
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info) {
$this->load->model('customer/customer');
$this->model_customer_customer->deleteReward($order_id);
}
$json['success'] = $this->language->get('text_reward_removed');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function addCommission() {
$this->load->language('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'sale/order')) {
$json['error'] = $this->language->get('error_permission');
} else {
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('sale/order');
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info) {
$this->load->model('marketing/affiliate');
$affiliate_total = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($order_id);
if (!$affiliate_total) {
$this->model_marketing_affiliate->addTransaction($order_info['affiliate_id'], $this->language->get('text_order_id') . ' #' . $order_id, $order_info['commission'], $order_id);
}
}
$json['success'] = $this->language->get('text_commission_added');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function removeCommission() {
$this->load->language('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'sale/order')) {
$json['error'] = $this->language->get('error_permission');
} else {
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('sale/order');
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info) {
$this->load->model('marketing/affiliate');
$this->model_marketing_affiliate->deleteTransaction($order_id);
}
$json['success'] = $this->language->get('text_commission_removed');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function history() {
$this->load->language('sale/order');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_status'] = $this->language->get('column_status');
$data['column_notify'] = $this->language->get('column_notify');
$data['column_comment'] = $this->language->get('column_comment');
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['histories'] = array();
$this->load->model('sale/order');
$results = $this->model_sale_order->getOrderHistories($this->request->get['order_id'], ($page - 1) * 10, 10);
foreach ($results as $result) {
$data['histories'][] = array(
'notify' => $result['notify'] ? $this->language->get('text_yes') : $this->language->get('text_no'),
'status' => $result['status'],
'comment' => nl2br($result['comment']),
'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
);
}
$history_total = $this->model_sale_order->getTotalOrderHistories($this->request->get['order_id']);
$pagination = new Pagination();
$pagination->total = $history_total;
$pagination->page = $page;
$pagination->limit = 10;
$pagination->url = $this->url->link('sale/order/history', 'token=' . $this->session->data['token'] . '&order_id=' . $this->request->get['order_id'] . '&page={page}', 'SSL');
$data['pagination'] = $pagination->render();
$data['results'] = sprintf($this->language->get('text_pagination'), ($history_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($history_total - 10)) ? $history_total : ((($page - 1) * 10) + 10), $history_total, ceil($history_total / 10));
$this->response->setOutput($this->load->view('sale/order_history.tpl', $data));
}
public function invoice() {
$this->load->language('sale/order');
$data['title'] = $this->language->get('text_invoice');
if ($this->request->server['HTTPS']) {
$data['base'] = HTTPS_SERVER;
} else {
$data['base'] = HTTP_SERVER;
}
$data['direction'] = $this->language->get('direction');
$data['lang'] = $this->language->get('code');
$data['text_invoice'] = $this->language->get('text_invoice');
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_invoice_date'] = $this->language->get('text_invoice_date');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_telephone'] = $this->language->get('text_telephone');
$data['text_fax'] = $this->language->get('text_fax');
$data['text_email'] = $this->language->get('text_email');
$data['text_website'] = $this->language->get('text_website');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_product'] = $this->language->get('column_product');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$this->load->model('sale/order');
$this->load->model('setting/setting');
$data['orders'] = array();
$orders = array();
if (isset($this->request->post['selected'])) {
$orders = $this->request->post['selected'];
} elseif (isset($this->request->get['order_id'])) {
$orders[] = $this->request->get['order_id'];
}
foreach ($orders as $order_id) {
$order_info = $this->model_sale_order->getOrder($order_id);
if ($order_info) {
$store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);
if ($store_info) {
$store_address = $store_info['config_address'];
$store_email = $store_info['config_email'];
$store_telephone = $store_info['config_telephone'];
$store_fax = $store_info['config_fax'];
} else {
$store_address = $this->config->get('config_address');
$store_email = $this->config->get('config_email');
$store_telephone = $this->config->get('config_telephone');
$store_fax = $this->config->get('config_fax');
}
if ($order_info['invoice_no']) {
$invoice_no = $order_info['invoice_prefix'] . $order_info['invoice_no'];
} else {
$invoice_no = '';
}
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$payment_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$this->load->model('tool/upload');
$product_data = array();
$products = $this->model_sale_order->getOrderProducts($order_id);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);
foreach ($options as $option) {
if ($option['type'] != 'file') {
$value = $option['value'];
} else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
} else {
$value = '';
}
}
$option_data[] = array(
'name' => $option['name'],
'value' => $value
);
}
$product_data[] = array(
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
);
}
$voucher_data = array();
$vouchers = $this->model_sale_order->getOrderVouchers($order_id);
foreach ($vouchers as $voucher) {
$voucher_data[] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
);
}
$total_data = array();
$totals = $this->model_sale_order->getOrderTotals($order_id);
foreach ($totals as $total) {
$total_data[] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['orders'][] = array(
'order_id' => $order_id,
'invoice_no' => $invoice_no,
'date_added' => date($this->language->get('date_format_short'), strtotime($order_info['date_added'])),
'store_name' => $order_info['store_name'],
'store_url' => rtrim($order_info['store_url'], '/'),
'store_address' => nl2br($store_address),
'store_email' => $store_email,
'store_telephone' => $store_telephone,
'store_fax' => $store_fax,
'email' => $order_info['email'],
'telephone' => $order_info['telephone'],
'shipping_address' => $shipping_address,
'shipping_method' => $order_info['shipping_method'],
'payment_address' => $payment_address,
'payment_method' => $order_info['payment_method'],
'product' => $product_data,
'voucher' => $voucher_data,
'total' => $total_data,
'comment' => nl2br($order_info['comment'])
);
}
}
$this->response->setOutput($this->load->view('sale/order_invoice.tpl', $data));
}
public function shipping() {
$this->load->language('sale/order');
$data['title'] = $this->language->get('text_shipping');
if ($this->request->server['HTTPS']) {
$data['base'] = HTTPS_SERVER;
} else {
$data['base'] = HTTP_SERVER;
}
$data['direction'] = $this->language->get('direction');
$data['lang'] = $this->language->get('code');
$data['text_shipping'] = $this->language->get('text_shipping');
$data['text_picklist'] = $this->language->get('text_picklist');
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_invoice_date'] = $this->language->get('text_invoice_date');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_telephone'] = $this->language->get('text_telephone');
$data['text_fax'] = $this->language->get('text_fax');
$data['text_email'] = $this->language->get('text_email');
$data['text_website'] = $this->language->get('text_website');
$data['text_contact'] = $this->language->get('text_contact');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_sku'] = $this->language->get('text_sku');
$data['text_upc'] = $this->language->get('text_upc');
$data['text_ean'] = $this->language->get('text_ean');
$data['text_jan'] = $this->language->get('text_jan');
$data['text_isbn'] = $this->language->get('text_isbn');
$data['text_mpn'] = $this->language->get('text_mpn');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_location'] = $this->language->get('column_location');
$data['column_reference'] = $this->language->get('column_reference');
$data['column_product'] = $this->language->get('column_product');
$data['column_weight'] = $this->language->get('column_weight');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$this->load->model('sale/order');
$this->load->model('catalog/product');
$this->load->model('setting/setting');
$data['orders'] = array();
$orders = array();
if (isset($this->request->post['selected'])) {
$orders = $this->request->post['selected'];
} elseif (isset($this->request->get['order_id'])) {
$orders[] = $this->request->get['order_id'];
}
foreach ($orders as $order_id) {
$order_info = $this->model_sale_order->getOrder($order_id);
// Make sure there is a shipping method
if ($order_info && $order_info['shipping_code']) {
$store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);
if ($store_info) {
$store_address = $store_info['config_address'];
$store_email = $store_info['config_email'];
$store_telephone = $store_info['config_telephone'];
$store_fax = $store_info['config_fax'];
} else {
$store_address = $this->config->get('config_address');
$store_email = $this->config->get('config_email');
$store_telephone = $this->config->get('config_telephone');
$store_fax = $this->config->get('config_fax');
}
if ($order_info['invoice_no']) {
$invoice_no = $order_info['invoice_prefix'] . $order_info['invoice_no'];
} else {
$invoice_no = '';
}
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$this->load->model('tool/upload');
$product_data = array();
$products = $this->model_sale_order->getOrderProducts($order_id);
foreach ($products as $product) {
$option_weight = '';
$product_info = $this->model_catalog_product->getProduct($product['product_id']);
if ($product_info) {
$option_data = array();
$options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);
foreach ($options as $option) {
$option_value_info = $this->model_catalog_product->getProductOptionValue($order_id, $product['order_product_id']);
if ($option['type'] != 'file') {
$value = $option['value'];
} else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
} else {
$value = '';
}
}
$option_data[] = array(
'name' => $option['name'],
'value' => $value
);
$product_option_value_info = $this->model_catalog_product->getProductOptionValue($product['product_id'], $option['product_option_value_id']);
if ($product_option_value_info) {
if ($product_option_value_info['weight_prefix'] == '+') {
$option_weight += $product_option_value_info['weight'];
} elseif ($product_option_value_info['weight_prefix'] == '-') {
$option_weight -= $product_option_value_info['weight'];
}
}
}
$product_data[] = array(
'name' => $product_info['name'],
'model' => $product_info['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'location' => $product_info['location'],
'sku' => $product_info['sku'],
'upc' => $product_info['upc'],
'ean' => $product_info['ean'],
'jan' => $product_info['jan'],
'isbn' => $product_info['isbn'],
'mpn' => $product_info['mpn'],
'weight' => $this->weight->format(($product_info['weight'] + $option_weight) * $product['quantity'], $product_info['weight_class_id'], $this->language->get('decimal_point'), $this->language->get('thousand_point'))
);
}
}
$data['orders'][] = array(
'order_id' => $order_id,
'invoice_no' => $invoice_no,
'date_added' => date($this->language->get('date_format_short'), strtotime($order_info['date_added'])),
'store_name' => $order_info['store_name'],
'store_url' => rtrim($order_info['store_url'], '/'),
'store_address' => nl2br($store_address),
'store_email' => $store_email,
'store_telephone' => $store_telephone,
'store_fax' => $store_fax,
'email' => $order_info['email'],
'telephone' => $order_info['telephone'],
'shipping_address' => $shipping_address,
'shipping_method' => $order_info['shipping_method'],
'product' => $product_data,
'comment' => nl2br($order_info['comment'])
);
}
}
$this->response->setOutput($this->load->view('sale/order_shipping.tpl', $data));
}
}
| gpl-3.0 |
alex1993/Leetcode | src/solution300_399/solution337/Solution.java | 921 | package solution300_399.solution337;
/**
* Script Created by daidai on 2017/8/4.
*/
import structure.TreeNode;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
//返回长度为2的数组,第0个表示 include,第1个是 exclude
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int include = root.val + left[1] + right[1];
int exclude = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[]{include, exclude};
}
}
| gpl-3.0 |
josemrb/RequestFilter | src/RequestFilter/FilterFactory.cs | 1238 | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using RequestFilter.Configurations;
using RequestFilter.Extensions;
namespace RequestFilter
{
public class FilterFactory
{
private readonly RequestFilterSection _configurationSection;
public FilterFactory(RequestFilterSection requestFilterSection)
{
_configurationSection = requestFilterSection;
}
public IList<IFilter> BuildFiltersFromConfig()
{
List<IFilter> filters = new List<IFilter>();
foreach (Filter filterConfig in _configurationSection.Filters)
{
IFilter filter = BuildFilter(filterConfig.Type, filterConfig.Params.ToObjectArray());
if (filterConfig.Index != 0)
filters.Insert(filterConfig.Index, filter);
else
filters.Add(filter);
}
return filters;
}
public IFilter BuildFilter(Type type, params object[] options)
{
Contract.Requires(type != null);
Contract.Requires(options != null);
return (IFilter)Activator.CreateInstance(type, options);
}
}
}
| gpl-3.0 |
ShellBear/flushy | Ressources/modules/js/resizetext.js | 258 | window.onload = function() {
var size = 1.0
var up = true;
setInterval(function() {
document.body.style.fontSize = size + "em";
if (up)
size += 1;
else
size -= 1;
if (size == 10)
up = false;
if (size == 0)
up = true;
}, 100);
}
| gpl-3.0 |
jim-pansn/graph-tool | src/graph_tool/community/__init__.py | 13313 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
``graph_tool.community`` - Community structure
----------------------------------------------
This module contains algorithms for the computation of community structure on
graphs.
Stochastic blockmodel inference
+++++++++++++++++++++++++++++++
Non-hierarchical models
=======================
Summary
^^^^^^^
.. autosummary::
:nosignatures:
minimize_blockmodel_dl
BlockState
OverlapBlockState
CovariateBlockState
mcmc_sweep
MinimizeState
multilevel_minimize
collect_vertex_marginals
collect_edge_marginals
mf_entropy
bethe_entropy
model_entropy
get_max_B
get_akc
condensation_graph
get_block_edge_gradient
Hierarchical models
===================
Summary
^^^^^^^
.. autosummary::
:nosignatures:
minimize_nested_blockmodel_dl
NestedBlockState
NestedMinimizeState
init_nested_state
nested_mcmc_sweep
nested_tree_sweep
get_hierarchy_tree
Modularity-based community detection
++++++++++++++++++++++++++++++++++++
Summary
=======
.. autosummary::
:nosignatures:
community_structure
modularity
Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng
import random
import sys
__all__ = ["minimize_blockmodel_dl",
"BlockState",
"OverlapBlockState",
"CovariateBlockState",
"mcmc_sweep",
"MinimizeState",
"multilevel_minimize",
"collect_edge_marginals",
"collect_vertex_marginals",
"mf_entropy",
"bethe_entropy",
"model_entropy",
"get_max_B",
"get_akc",
"condensation_graph",
"minimize_nested_blockmodel_dl",
"NestedBlockState",
"NestedMinimizeState",
"init_nested_state",
"nested_mcmc_sweep",
"nested_tree_sweep",
"get_hierarchy_tree",
"get_block_edge_gradient",
"community_structure",
"modularity"]
from . blockmodel import minimize_blockmodel_dl, BlockState, mcmc_sweep, \
multilevel_minimize, model_entropy, get_max_B, get_akc, condensation_graph, \
collect_edge_marginals, collect_vertex_marginals, bethe_entropy, mf_entropy, \
MinimizeState
from . overlap_blockmodel import OverlapBlockState, get_block_edge_gradient
from . covariate_blockmodel import CovariateBlockState
from . nested_blockmodel import NestedBlockState, NestedMinimizeState, \
init_nested_state, nested_mcmc_sweep, nested_tree_sweep, \
minimize_nested_blockmodel_dl, get_hierarchy_tree
from . blockmodel import libcommunity as libgraph_tool_community
def community_structure(g, n_iter, n_spins, gamma=1.0, corr="erdos",
spins=None, weight=None, t_range=(100.0, 0.01),
verbose=False, history_file=None):
r"""Obtain the community structure for the given graph, using a Potts model
approach, which is a generalization of modularity maximization).
.. warning::
**The use of this function is discouraged.** Although community detection
based on modularity maximization is very common, it is very
problematic. It will find high-scoring partitions where there is none
[guimera-modularity-2004]_, and at the same time will not find actual
structure in large graphs [fortunato-resolution-2007]_. Furthermore, in
many empirical networks, the partitions found in this way are largely
meaningless [good-performance-2010]_.
One should use instead methods based on statistical inference
(i.e. :func:`~graph_tool.community.minimize_blockmodel_dl` and
:func:`~graph_tool.community.minimize_nested_blockmodel_dl`).
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
n_iter : int
Number of iterations.
n_spins : int
Number of maximum spins to be used.
gamma : float (optional, default: 1.0)
The :math:`\gamma` parameter of the hamiltonian.
corr : string (optional, default: "erdos")
Type of correlation to be assumed: Either "erdos", "uncorrelated" and
"correlated".
spins : :class:`~graph_tool.PropertyMap`
Vertex property maps to store the spin variables. If this is specified,
the values will not be initialized to a random value.
weight : :class:`~graph_tool.PropertyMap` (optional, default: None)
Edge property map with the optional edge weights.
t_range : tuple of floats (optional, default: (100.0, 0.01))
Temperature range.
verbose : bool (optional, default: False)
Display verbose information.
history_file : string (optional, default: None)
History file to keep information about the simulated annealing.
Returns
-------
spins : :class:`~graph_tool.PropertyMap`
Vertex property map with the spin values.
See Also
--------
community_structure: Obtain the community structure
modularity: Calculate the network modularity
condensation_graph: Network of communities, or blocks
Notes
-----
The method of community detection covered here is an implementation of what
was proposed in [reichard-statistical-2006]_. It
consists of a `simulated annealing`_ algorithm which tries to minimize the
following hamiltonian:
.. math::
\mathcal{H}(\{\sigma\}) = - \sum_{i \neq j} \left(A_{ij} -
\gamma p_{ij}\right) \delta(\sigma_i,\sigma_j)
where :math:`p_{ij}` is the probability of vertices i and j being connected,
which reduces the problem of community detection to finding the ground
states of a Potts spin-glass model. It can be shown that minimizing this
hamiltonan, with :math:`\gamma=1`, is equivalent to maximizing
Newman's modularity ([newman-modularity-2006]_). By increasing the parameter
:math:`\gamma`, it's possible also to find sub-communities.
It is possible to select three policies for choosing :math:`p_{ij}` and thus
choosing the null model: "erdos" selects a Erdos-Reyni random graph,
"uncorrelated" selects an arbitrary random graph with no vertex-vertex
correlations, and "correlated" selects a random graph with average
correlation taken from the graph itself. Optionally a weight property
can be given by the `weight` option.
The most important parameters for the algorithm are the initial and final
temperatures (`t_range`), and total number of iterations (`max_iter`). It
normally takes some trial and error to determine the best values for a
specific graph. To help with this, the `history` option can be used, which
saves to a chosen file the temperature and number of spins per iteration,
which can be used to determined whether or not the algorithm converged to
the optimal solution. Also, the `verbose` option prints the computation
status on the terminal.
.. note::
If the spin property already exists before the computation starts, it's
not re-sampled at the beginning. This means that it's possible to
continue a previous run, if you saved the graph, by properly setting
`t_range` value, and using the same `spin` property.
If enabled during compilation, this algorithm runs in parallel.
Examples
--------
This example uses the network :download:`community.xml <community.xml>`.
>>> from pylab import *
>>> from numpy.random import seed
>>> seed(42)
>>> g = gt.load_graph("community.xml")
>>> pos = g.vertex_properties["pos"]
>>> spins = gt.community_structure(g, 10000, 20, t_range=(5, 0.1))
>>> gt.graph_draw(g, pos=pos, vertex_fill_color=spins, output_size=(420, 420), output="comm1.pdf")
<...>
.. testcode::
:hide:
gt.graph_draw(g, pos=pos, vertex_fill_color=spins, output_size=(420, 420), output="comm1.png")
>>> spins = gt.community_structure(g, 10000, 40, t_range=(5, 0.1), gamma=2.5)
>>> gt.graph_draw(g, pos=pos, vertex_fill_color=spins, output_size=(420, 420), output="comm2.pdf")
<...>
.. testcode::
:hide:
gt.graph_draw(g, pos=pos, vertex_fill_color=spins, output_size=(420, 420), output="comm2.png")
.. figure:: comm1.*
:align: center
The community structure with :math:`\gamma=1`.
.. figure:: comm2.*
:align: center
The community structure with :math:`\gamma=2.5`.
References
----------
.. [guimera-modularity-2004] Roger Guimerà, Marta Sales-Pardo, and Luís
A. Nunes Amaral, "Modularity from fluctuations in random graphs and
complex networks", Phys. Rev. E 70, 025101(R) (2004),
:doi:`10.1103/PhysRevE.70.025101`
.. [fortunato-resolution-2007] Santo Fortunato and Marc Barthélemy,
"Resolution limit in community detection", Proc. Natl. Acad. Sci. USA
104(1): 36–41 (2007), :doi:`10.1073/pnas.0605965104`
.. [good-performance-2010] Benjamin H. Good, Yves-Alexandre de Montjoye, and
Aaron Clauset, "Performance of modularity maximization in practical
contexts", Phys. Rev. E 81, 046106 (2010),
:doi:`10.1103/PhysRevE.81.046106`
.. [reichard-statistical-2006] Joerg Reichardt and Stefan Bornholdt,
"Statistical Mechanics of Community Detection", Phys. Rev. E 74
016110 (2006), :doi:`10.1103/PhysRevE.74.016110`, :arxiv:`cond-mat/0603718`
.. [newman-modularity-2006] M. E. J. Newman, "Modularity and community
structure in networks", Proc. Natl. Acad. Sci. USA 103, 8577-8582 (2006),
:doi:`10.1073/pnas.0601602103`, :arxiv:`physics/0602124`
.. _simulated annealing: http://en.wikipedia.org/wiki/Simulated_annealing
"""
if spins is None:
spins = g.new_vertex_property("int32_t")
if history_file is None:
history_file = ""
ug = GraphView(g, directed=False)
libgraph_tool_community.community_structure(ug._Graph__graph, gamma, corr,
n_iter, t_range[1], t_range[0],
n_spins, _get_rng(),
verbose, history_file,
_prop("e", ug, weight),
_prop("v", ug, spins))
return spins
def modularity(g, prop, weight=None):
r"""
Calculate Newman's modularity.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
prop : :class:`~graph_tool.PropertyMap`
Vertex property map with the community partition.
weight : :class:`~graph_tool.PropertyMap` (optional, default: None)
Edge property map with the optional edge weights.
Returns
-------
modularity : float
Newman's modularity.
See Also
--------
community_structure: obtain the community structure
modularity: calculate the network modularity
condensation_graph: Network of communities, or blocks
Notes
-----
Given a specific graph partition specified by `prop`, Newman's modularity
[newman-modularity-2006]_ is defined by:
.. math::
Q = \frac{1}{2E} \sum_r e_{rr}- \frac{e_r^2}{2E}
where :math:`e_{rs}` is the number of edges which fall between
vertices in communities s and r, or twice that number if :math:`r = s`, and
:math:`e_r = \sum_s e_{rs}`.
If weights are provided, the matrix :math:`e_{rs}` corresponds to the sum
of edge weights instead of number of edges, and the value of :math:`E`
becomes the total sum of edge weights.
Examples
--------
>>> from pylab import *
>>> from numpy.random import seed
>>> seed(42)
>>> g = gt.load_graph("community.xml")
>>> b = gt.community_structure(g, 10000, 10)
>>> gt.modularity(g, b)
0.535314188562404...
References
----------
.. [newman-modularity-2006] M. E. J. Newman, "Modularity and community
structure in networks", Proc. Natl. Acad. Sci. USA 103, 8577-8582 (2006),
:doi:`10.1073/pnas.0601602103`, :arxiv:`physics/0602124`
"""
ug = GraphView(g, directed=False)
m = libgraph_tool_community.modularity(ug._Graph__graph,
_prop("e", ug, weight),
_prop("v", ug, prop))
return m
| gpl-3.0 |
lobomacz/safecom | src/main/java/com/ecom/safecom/dao/MovimientoCajaDao.java | 2009 | package com.ecom.safecom.dao;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ecom.safecom.entity.MovimientoCaja;
@Repository
public class MovimientoCajaDao {
@PersistenceContext
private EntityManager em;
@Transactional(readOnly = true)
public List<MovimientoCaja> listaTodo(Integer idcaja) {
Query query = em.createQuery("from MovimientoCaja mc where mc.caja.id_caja=:idcaja");
query.setParameter("idcaja", idcaja);
List<MovimientoCaja> resultado = query.getResultList();
return resultado;
}
@Transactional(readOnly = true)
public List<MovimientoCaja> listaPorFecha(Integer idcaja, Date finicio, Date ffinal) {
String consulta = "from MovimientoCaja mc where mc.caja.id_caja=:idcaja and mc.fecha_hora_movimiento between :finicio and :ffinal";
Query query = em.createQuery(consulta);
query.setParameter("idcaja", idcaja);
query.setParameter("finicio", finicio);
query.setParameter("ffinal", ffinal);
List<MovimientoCaja> resultado = query.getResultList();
return resultado;
}
@Transactional(readOnly = true)
public MovimientoCaja get(Integer _id) {
return em.find(MovimientoCaja.class, _id);
}
@Transactional(readOnly = true)
public MovimientoCaja reload(MovimientoCaja movimiento) {
return em
.find(MovimientoCaja.class, movimiento.getId_movimiento_caja());
}
@Transactional
public MovimientoCaja save(MovimientoCaja movcaja) {
em.persist(movcaja);
em.flush();
return get(movcaja.getId_movimiento_caja());
}
@Transactional
public MovimientoCaja update(MovimientoCaja movcaja) {
movcaja = em.merge(movcaja);
return movcaja;
}
@Transactional
public void delete(MovimientoCaja movcaja) {
MovimientoCaja mc = get(movcaja.getId_movimiento_caja());
if (mc != null) {
em.remove(mc);
}
}
}
| gpl-3.0 |
OriPekelman/aaar | spec/requests/activity_scores_spec.rb | 320 | require 'spec_helper'
describe "ActivityScores" do
describe "GET /activity_scores" do
it "works! (now write some real specs)" do
# Run the generator again with the --webrat flag if you want to use webrat methods/matchers
get activity_scores_path
response.status.should be(200)
end
end
end
| gpl-3.0 |
ljsimin/gimii | HeadTracking2LEDs/HeadTracking2LEDs/ScenaSoba.cs | 22473 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using DI = Microsoft.DirectX.DirectInput;
using DXAV = Microsoft.DirectX.AudioVideoPlayback;
using DSND = Microsoft.DirectX.DirectSound;
using System.Timers;
using System.Threading;
namespace HeadTracking2LEDs
{
public partial class ScenaSoba : Form
{
private Device device = null;
public const int ScreenWidth = 1280;
public const int ScreenHeight = 800;
private bool fullscreen = false;
private VertexBuffer vbTerrain = null;
private IndexBuffer ib = null;
private IndexBuffer ib2 = null;
private Microsoft.DirectX.Direct3D.Font infoFont;
private Mesh deoZida1Mesh = null;
private Mesh ball = null;
private Mesh podMesh = null;
private Mesh zidBezProzoraMesh = null;
private Mesh deoZida2Mesh = null;
private Texture texI = null;
private float angleTor = 0.0f;
private float angleTorStep = 0.002f;
private float pyrUpDown = 0.0f;
private float pyrUpDownStep = 0.005f;
private float angleGlob = 0.0f;
private float angleGlobStep = 0.02f;
private float moveStep = 0.25f;
private Camera myCamera = null;
private Microsoft.DirectX.DirectInput.Device keyb;
protected System.Timers.Timer myTimer;
private int TIMER_INTERVAL = 20;
private MatrixStack mStack = new MatrixStack();
private WiiController wii;
private bool showInfo = true;
public ScenaSoba()
{
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
}
public void InitializeTimer()
{
myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(TimerEventProcessor);
myTimer.Interval = TIMER_INTERVAL;
myTimer.Start();
}
public void InitializeWii()
{
wii = new WiiController();
}
public void InitializeKeyboard()
{
keyb = new DI.Device(DI.SystemGuid.Keyboard);
keyb.SetCooperativeLevel(this, DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
keyb.Acquire();
}
public void InitializeGraphicsAndCamera()
{
// Set presentation parameters
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.MultiSample = MultiSampleType.FourSamples;
presentParams.SwapEffect = SwapEffect.Discard;
// Start up full screen
Format current = Manager.Adapters[0].CurrentDisplayMode.Format;
if (Manager.CheckDeviceType(0, DeviceType.Hardware, current, current, false))
{
// Perfect, this is valid
presentParams.Windowed = true;
presentParams.BackBufferFormat = current;
presentParams.BackBufferCount = 1;
presentParams.BackBufferWidth = ScreenWidth;
presentParams.BackBufferHeight = ScreenHeight;
Cursor.Hide();
fullscreen = false;
}
else
{
presentParams.Windowed = true;
fullscreen = false;
}
// Depth Buffer
presentParams.EnableAutoDepthStencil = true;
presentParams.AutoDepthStencilFormat = DepthFormat.D16;
// Create device
device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
deoZida1Mesh = Mesh.Box(device, 12, 15, 0.1f);
podMesh = Mesh.Box(device, 30, 0.1f, 30);
zidBezProzoraMesh = Mesh.Box(device, 0.1f, 15, 30);
deoZida2Mesh = Mesh.Box(device, 6, 5, 0.1f);
ball = Mesh.Sphere(device, 1, 36, 36);
vbTerrain = new VertexBuffer(typeof(CustomVertex.PositionNormalColored), 1600, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalColored.Format, Pool.Default);
vbTerrain.Created += new EventHandler(this.OnVertexBufferCreate);
OnVertexBufferCreate(vbTerrain, null);
texI = new Texture(device, new Bitmap("i.jpg"), 0, Pool.Managed);
infoFont = new Microsoft.DirectX.Direct3D.Font(device, new System.Drawing.Font("Arial", 12.0f, FontStyle.Regular));
mStack = new MatrixStack();
myCamera = new Camera(new Vector3(0.0f, 5.0f, -15.0f), new Vector3(0.0f, 5.0f, 40.0f), new Vector3(0.0f, 1.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(0.0f, 0.0f, 1.0f));
}
private void OnVertexBufferCreate(object sender, EventArgs e)
{
VertexBuffer buffer = (VertexBuffer)sender;
if (buffer == vbTerrain)
{
CustomVertex.PositionNormalColored[] vertsTerrain = new CustomVertex.PositionNormalColored[1600];
for (int i = 0; i < 40; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 20, 0.0f, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 20, 0.0f, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 20, 20.0f, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 20, 20.0f, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
for (int i = 40; i < 140; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3((-20.0f), 0.0f, (float)i - 60), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, 0.0f, (float)i - 60), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3((-20.0f), 20.0f, (float)i - 60), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, 20.0f, (float)i - 60), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
for (int i = 140; i < 161; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, (float)i - 140, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, (float)i - 140, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3(-20.0f, (float)i - 140, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3(-20.0f, (float)i - 140, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
for (int i = 161; i < 180; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3((-20.0f), (float)i - 160, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, (float)i - 160, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3((-20.0f), (float)i - 160, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, (float)i - 160, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
for (int i = 180; i < 221; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 200, 0.0f, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 200, 20.0f, 80.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 200, 0.0f, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3((float)i - 200, 20.0f, -20.0f), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
for (int i = 221; i < 321; i++)
{
int index = i;
vertsTerrain[index * 4] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, 0.0f, (float)i - 240), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 1] = new CustomVertex.PositionNormalColored(new Vector3(20.0f, 20.0f, (float)i - 240), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 2] = new CustomVertex.PositionNormalColored(new Vector3(-20.0f, 0.0f, (float)i - 240), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
vertsTerrain[index * 4 + 3] = new CustomVertex.PositionNormalColored(new Vector3(-20.0f, 20.0f, (float)i - 240), new Vector3(0.0f, 1.0f, -0.4f), Color.DarkGreen.ToArgb());
}
buffer.SetData(vertsTerrain, 0, LockFlags.None);
}
}
private void SetupCamera()
{
device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3, this.Width / this.Height, 1.0f, 10000.0f);
//device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, -15.0f), new Vector3(0,0,0), new Vector3(0, 1, 0));
device.Transform.View = myCamera.LookLeftHanded();
// Setting back face culling
device.RenderState.CullMode = Cull.None;
// Setting lights
device.RenderState.Lighting = true;
//device.RenderState.Ambient = Color.Bisque;
device.Lights[0].Ambient = Color.FromArgb(20,20,20);
device.Lights[0].Type = LightType.Directional;
device.Lights[0].Diffuse = Color.White;
device.Lights[0].Position = new Vector3(150.0f, 50.0f, 150.0f);
device.Lights[0].Direction = new Vector3(0.0f, -0.5f, -1.0f);
device.Lights[0].Enabled = true;
Color lightDiffColor = Color.White;
if (wii != null)
if (wii.Connected)
lightDiffColor = Color.Red;
device.Lights[1].Type = LightType.Directional;
device.Lights[1].Diffuse = lightDiffColor;
//device.Lights[1].Direction = new Vector3(0.0f, 1.0f, 0.0f);
device.Lights[1].Direction = new Vector3(0.0f, 1.0f, 0.0f);
device.Lights[1].Enabled = false;
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
Color backColor = Color.Black;
if (wii != null)
if (wii.Connected)
backColor = Color.DimGray;
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, backColor, 1.0f, 0);
SetupCamera();
device.BeginScene();
//mStack.LoadMatrix(device.Transform.View);
mStack.Push();
{
mStack.MultiplyMatrixLocal(
Matrix.Identity
);
device.Transform.World = mStack.Top;
device.VertexFormat = CustomVertex.PositionNormalColored.Format;
device.SetStreamSource(0, vbTerrain, 0);
device.DrawPrimitives(PrimitiveType.LineList, 0, 800);
}
mStack.Pop();
//zidovi
mStack.Push();
{
Material myMaterial = new Material();
myMaterial.Ambient = Color.FromArgb(20, Color.White);
myMaterial.Diffuse = Color.FromArgb(20, Color.White);
myMaterial.Specular = Color.FromArgb(20, Color.White);
myMaterial.Emissive = Color.FromArgb(50, 50, 50);
device.Material = myMaterial;
device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
mStack.Push();
{
mStack.MultiplyMatrixLocal(
Matrix.Translation(-15.0f, 7.5f, 0.0f)
);
device.Transform.World = mStack.Top;
zidBezProzoraMesh.DrawSubset(0);
mStack.MultiplyMatrixLocal(
Matrix.Translation(30.0f, 0.0f, 0.0f)
);
device.Transform.World = mStack.Top;
zidBezProzoraMesh.DrawSubset(0);
mStack.MultiplyMatrixLocal(
Matrix.RotationAxis(new Vector3(0, 1, 0), -(float)Math.PI / 2) *
Matrix.Translation(-15.0f, 0.0f, -15.0f)
);
device.Transform.World = mStack.Top;
zidBezProzoraMesh.DrawSubset(0);
}
mStack.Pop();
mStack.Push();
{
mStack.MultiplyMatrixLocal(
// Matrix.RotationAxis(new Vector3(1, 0, 0), -(float)Math.PI / 2) *
// Matrix.Scaling(0.5f, 1.0f, 1.0f) *
Matrix.Translation(0.0f, 0.0f, 0.0f)
);
device.Transform.World = mStack.Top;
podMesh.DrawSubset(0);
mStack.MultiplyMatrixLocal(
// Matrix.RotationAxis(new Vector3(1, 0, 0), -(float)Math.PI / 2) *
// Matrix.Scaling(0.5f, 1.0f, 1.0f) *
Matrix.Translation(0.0f, 15.0f, 0.0f)
);
device.Transform.World = mStack.Top;
podMesh.DrawSubset(0);
}
mStack.Pop();
mStack.Push();
{
myMaterial.Emissive = Color.FromArgb(30, 30, 30);
device.Material = myMaterial;
mStack.MultiplyMatrixLocal(
Matrix.Translation(-9.0f, 7.5f, 15.0f)
);
device.Transform.World = mStack.Top;
deoZida1Mesh.DrawSubset(0);
mStack.MultiplyMatrixLocal(
Matrix.Translation(18.0f, 0.0f, 0.0f)
);
device.Transform.World = mStack.Top;
deoZida1Mesh.DrawSubset(0);
}
mStack.Pop();
mStack.Push();
{
mStack.MultiplyMatrixLocal(
Matrix.Translation(0, 2.5f, 15.0f)
);
device.Transform.World = mStack.Top;
deoZida2Mesh.DrawSubset(0);
mStack.MultiplyMatrixLocal(
Matrix.Translation(0, 10, 0.0f)
);
device.Transform.World = mStack.Top;
deoZida2Mesh.DrawSubset(0);
}
mStack.Pop();
}
mStack.Pop();
if (showInfo)
{
infoFont.DrawText(null, "Press Insert to Connect/Disconnect, Escape to Exit", new Rectangle(25, 25, 0, 0),
DrawTextFormat.NoClip, Color.PaleGreen);
infoFont.DrawText(null, "Press I to turn info On/Off", new Rectangle(25, 45, 0, 0),
DrawTextFormat.NoClip, Color.PaleGreen);
string ctrl = "Wii controller not connected";
if (wii != null)
if (wii.Connected)
ctrl = "Press R to calibrate"
+ "\nX1: " + wii.X1 + " Y1: " + wii.Y1 + " X2: " + wii.X2 + " Y2: " + wii.Y2 +
" \nHeadX: " + wii.HeadX + " HeadY: " + wii.HeadY + " HeadDist: " + wii.HeadDist;
infoFont.DrawText(null, ctrl, new Rectangle(25, 65, 0, 0),
DrawTextFormat.NoClip, Color.PaleGreen);
}
device.EndScene();
device.Present();
this.Invalidate();
}
protected override void OnKeyUp(KeyEventArgs e)
{
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
wii.ConnectAction();
if (wii.Connected)
wii.setRumbling(100);
}
if (e.KeyCode == Keys.R)
{
wii.CalibrateAngle();
}
if (e.KeyCode == Keys.I)
{
showInfo = !showInfo;
}
if (e.KeyCode == Keys.Escape)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(CloseTheForm));
}
else
{
CloseTheForm();
}
}
}
protected void readKeyboard()
{
DI.KeyboardState keys = keyb.GetCurrentKeyboardState();
if (keys[DI.Key.F1])
{
myCamera.SetPosition(new Vector3(0.0f, 20.0f, -15.0f));
}
if (keys[DI.Key.F2])
{
myCamera.SetPosition(new Vector3(-2.0f, 2.0f, -15.0f));
}
if (keys[DI.Key.F3])
{
myCamera.SetPosition(new Vector3(30.0f, -20.0f, -15.0f));
}
if (keys[DI.Key.A])
{
myCamera.MoveStrafeLeftRight(moveStep);
}
if (keys[DI.Key.D])
{
myCamera.MoveStrafeLeftRight(-moveStep);
}
if (keys[DI.Key.W])
{
myCamera.MoveForwardBackward(moveStep);
}
if (keys[DI.Key.S])
{
myCamera.MoveForwardBackward(-moveStep);
}
if (keys[DI.Key.C])
{
myCamera.MoveUpDown(-moveStep);
}
if (keys[DI.Key.Space])
{
myCamera.MoveUpDown(moveStep);
}
if (keys[DI.Key.Up])
{
myCamera.Pitch(0.02f);
}
if (keys[DI.Key.Down])
{
myCamera.Pitch(-0.02f);
}
if (keys[DI.Key.Left])
{
if (keys[DI.Key.LeftAlt])
myCamera.Yaw(0.02f);
else
myCamera.MoveViewRotateLeftRight(0.02f);
}
if (keys[DI.Key.Right])
{
if (keys[DI.Key.LeftAlt])
myCamera.Yaw(-0.02f);
else
myCamera.MoveViewRotateLeftRight(-0.02f);
}
}
protected void readWii()
{
myCamera.SetPosition(new Vector3(-5 * wii.HeadX, 5 * wii.HeadY, -5 * wii.HeadDist));
}
protected void setAnimationParameters()
{
if (pyrUpDown > 1 || pyrUpDown < -1)
pyrUpDownStep *= -1;
pyrUpDown += pyrUpDownStep;
if (angleTor > 0.3 || angleTor < -0.3)
angleTorStep *= -1;
angleTor += angleTorStep;
if (angleGlob >= 2 * Math.PI)
angleGlob = 0.0f;
angleGlob += angleGlobStep;
}
public void CloseTheForm()
{
if (wii.Connected)
wii.ConnectAction();
Cursor.Show();
Close();
}
protected void TimerEventProcessor(object source, ElapsedEventArgs e)
{
readKeyboard();
if (wii.Connected)
readWii();
setAnimationParameters();
//setAudio();
}
static void Main()
{
{
ScenaSoba f1 = new ScenaSoba();
f1.InitializeGraphicsAndCamera();
//f1.InitializeAudio();
f1.InitializeKeyboard();
f1.InitializeWii();
f1.InitializeTimer();
f1.Show();
Application.Run(f1);
}
}
}
}
| gpl-3.0 |
pyladiesmedellin/lessons | lesson_1/5.py | 215 | # -*- coding: utf-8 -*-
# Esto es un comentario de una sola línea
mi_variable = 15
"""
Y este es un comentario
de varias líneas
"""
mi_variable = 15
mi_variable = 15 # Este comentario es de una línea también
| gpl-3.0 |
GuillaumeDD/scala99problems | src/main/scala/multiwayTree/P73/sol01.scala | 1829 | /*******************************************************************************
* Copyright (c) 2014 Guillaume DUBUISSON DUPLESSIS <guillaume.dubuisson_duplessis@insa-rouen.fr>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Guillaume DUBUISSON DUPLESSIS <guillaume.dubuisson_duplessis@insa-rouen.fr> - initial API and implementation
******************************************************************************/
package multiwayTree.P73
import multiwayTree.MTree
import org.scalatest.Args
import scala.util.parsing.combinator.JavaTokenParsers
class sol01 extends P73 {
def lipsy(t: MTree[Char]): String =
if (t.children.isEmpty) {
t.value.toString
} else {
s"(${t.value} ${t.children.map(lipsy(_)).mkString(" ")})"
}
// Usage of Scala combinator
object TreeParser extends JavaTokenParsers {
// Define the expected value of a node (here a Char)
def value: Parser[Char] = """[a-zA-Z]""".r ^^ { _.head }
def simpleTree: Parser[MTree[Char]] = value ^^ { MTree(_) }
// Define the string representation of a non-leaf node
def tree: Parser[MTree[Char]] =
simpleTree | ("(" ~> value ~ rep(" " ~> simpleTree | tree) <~ ")") ^^ {
case value ~ children =>
if (children.isEmpty) {
MTree(value)
} else {
MTree(value, children)
}
}
def apply(input: String): MTree[Char] = parseAll(tree, input) match {
case Success(result, _) => result
case failure: NoSuccess => scala.sys.error(failure.msg)
}
}
def lipsyStringToMTree(t: String): MTree[Char] =
TreeParser(t)
}
| gpl-3.0 |
Zapuss/ZapekFapeCore | src/server/game/Entities/Item/Item.cpp | 40122 | /*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "Item.h"
#include "ObjectMgr.h"
#include "WorldPacket.h"
#include "DatabaseEnv.h"
#include "ItemEnchantmentMgr.h"
#include "SpellMgr.h"
#include "SpellInfo.h"
#include "ScriptMgr.h"
#include "ConditionMgr.h"
void AddItemsSetItem(Player* player, Item* item)
{
ItemTemplate const* proto = item->GetTemplate();
uint32 setid = proto->ItemSet;
ItemSetEntry const* set = sItemSetStore.LookupEntry(setid);
if (!set)
{
sLog->outErrorDb("Item set %u for item (id %u) not found, mods not applied.", setid, proto->ItemId);
return;
}
if (set->required_skill_id && player->GetSkillValue(set->required_skill_id) < set->required_skill_value)
return;
ItemSetEffect* eff = NULL;
for (size_t x = 0; x < player->ItemSetEff.size(); ++x)
{
if (player->ItemSetEff[x] && player->ItemSetEff[x]->setid == setid)
{
eff = player->ItemSetEff[x];
break;
}
}
if (!eff)
{
eff = new ItemSetEffect();
eff->setid = setid;
size_t x = 0;
for (; x < player->ItemSetEff.size(); ++x)
if (!player->ItemSetEff[x])
break;
if (x < player->ItemSetEff.size())
player->ItemSetEff[x]=eff;
else
player->ItemSetEff.push_back(eff);
}
++eff->item_count;
for (uint32 x = 0; x < MAX_ITEM_SET_SPELLS; ++x)
{
if (!set->spells [x])
continue;
//not enough for spell
if (set->items_to_triggerspell[x] > eff->item_count)
continue;
uint32 z = 0;
for (; z < MAX_ITEM_SET_SPELLS; ++z)
if (eff->spells[z] && eff->spells[z]->Id == set->spells[x])
break;
if (z < MAX_ITEM_SET_SPELLS)
continue;
//new spell
for (uint32 y = 0; y < MAX_ITEM_SET_SPELLS; ++y)
{
if (!eff->spells[y]) // free slot
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(set->spells[x]);
if (!spellInfo)
{
sLog->outError("WORLD: unknown spell id %u in items set %u effects", set->spells[x], setid);
break;
}
// spell casted only if fit form requirement, in other case will casted at form change
player->ApplyEquipSpell(spellInfo, NULL, true);
eff->spells[y] = spellInfo;
break;
}
}
}
}
void RemoveItemsSetItem(Player*player, ItemTemplate const* proto)
{
uint32 setid = proto->ItemSet;
ItemSetEntry const* set = sItemSetStore.LookupEntry(setid);
if (!set)
{
sLog->outErrorDb("Item set #%u for item #%u not found, mods not removed.", setid, proto->ItemId);
return;
}
ItemSetEffect* eff = NULL;
size_t setindex = 0;
for (; setindex < player->ItemSetEff.size(); setindex++)
{
if (player->ItemSetEff[setindex] && player->ItemSetEff[setindex]->setid == setid)
{
eff = player->ItemSetEff[setindex];
break;
}
}
// can be in case now enough skill requirement for set appling but set has been appliend when skill requirement not enough
if (!eff)
return;
--eff->item_count;
for (uint32 x = 0; x < MAX_ITEM_SET_SPELLS; x++)
{
if (!set->spells[x])
continue;
// enough for spell
if (set->items_to_triggerspell[x] <= eff->item_count)
continue;
for (uint32 z = 0; z < MAX_ITEM_SET_SPELLS; z++)
{
if (eff->spells[z] && eff->spells[z]->Id == set->spells[x])
{
// spell can be not active if not fit form requirement
player->ApplyEquipSpell(eff->spells[z], NULL, false);
eff->spells[z]=NULL;
break;
}
}
}
if (!eff->item_count) //all items of a set were removed
{
ASSERT(eff == player->ItemSetEff[setindex]);
delete eff;
player->ItemSetEff[setindex] = NULL;
}
}
bool ItemCanGoIntoBag(ItemTemplate const* proto, ItemTemplate const* pBagProto)
{
if (!proto || !pBagProto)
return false;
switch (pBagProto->Class)
{
case ITEM_CLASS_CONTAINER:
switch (pBagProto->SubClass)
{
case ITEM_SUBCLASS_CONTAINER:
return true;
case ITEM_SUBCLASS_SOUL_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_SOUL_SHARDS))
return false;
return true;
case ITEM_SUBCLASS_HERB_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_HERBS))
return false;
return true;
case ITEM_SUBCLASS_ENCHANTING_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_ENCHANTING_SUPP))
return false;
return true;
case ITEM_SUBCLASS_MINING_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_MINING_SUPP))
return false;
return true;
case ITEM_SUBCLASS_ENGINEERING_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_ENGINEERING_SUPP))
return false;
return true;
case ITEM_SUBCLASS_GEM_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_GEMS))
return false;
return true;
case ITEM_SUBCLASS_LEATHERWORKING_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_LEATHERWORKING_SUPP))
return false;
return true;
case ITEM_SUBCLASS_INSCRIPTION_CONTAINER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_INSCRIPTION_SUPP))
return false;
return true;
default:
return false;
}
case ITEM_CLASS_QUIVER:
switch (pBagProto->SubClass)
{
case ITEM_SUBCLASS_QUIVER:
if (!(proto->BagFamily & BAG_FAMILY_MASK_ARROWS))
return false;
return true;
case ITEM_SUBCLASS_AMMO_POUCH:
if (!(proto->BagFamily & BAG_FAMILY_MASK_BULLETS))
return false;
return true;
default:
return false;
}
}
return false;
}
Item::Item()
{
_objectType |= TYPEMASK_ITEM;
_objectTypeId = TYPEID_ITEM;
m_updateFlag = 0;
_valuesCount = ITEM_END;
m_slot = 0;
uState = ITEM_NEW;
uQueuePos = -1;
m_container = NULL;
_lootGenerated = false;
mb_in_trade = false;
m_lastPlayedTimeUpdate = time(NULL);
m_refundRecipient = 0;
m_paidMoney = 0;
m_paidExtendedCost = 0;
}
bool Item::Create(uint32 guidlow, uint32 itemid, Player const* owner)
{
Object::_Create(guidlow, 0, HIGHGUID_ITEM);
SetEntry(itemid);
SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
SetUInt64Value(ITEM_FIELD_OWNER, owner ? owner->GetGUID() : 0);
SetUInt64Value(ITEM_FIELD_CONTAINED, owner ? owner->GetGUID() : 0);
ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(itemid);
if (!itemProto)
return false;
SetUInt32Value(ITEM_FIELD_STACK_COUNT, 1);
SetUInt32Value(ITEM_FIELD_MAXDURABILITY, itemProto->MaxDurability);
SetUInt32Value(ITEM_FIELD_DURABILITY, itemProto->MaxDurability);
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
SetSpellCharges(i, itemProto->Spells[i].SpellCharges);
SetUInt32Value(ITEM_FIELD_DURATION, abs(itemProto->Duration));
SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, 0);
return true;
}
// Returns true if Item is a bag AND it is not empty.
// Returns false if Item is not a bag OR it is an empty bag.
bool Item::IsNotEmptyBag() const
{
if (Bag const* bag = ToBag())
return !bag->IsEmpty();
return false;
}
void Item::UpdateDuration(Player* owner, uint32 diff)
{
if (!GetUInt32Value(ITEM_FIELD_DURATION))
return;
sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item::UpdateDuration Item (Entry: %u Duration %u Diff %u)", GetEntry(), GetUInt32Value(ITEM_FIELD_DURATION), diff);
if (GetUInt32Value(ITEM_FIELD_DURATION) <= diff)
{
sScriptMgr->OnItemExpire(owner, GetTemplate());
owner->DestroyItem(GetBagSlot(), GetSlot(), true);
return;
}
SetUInt32Value(ITEM_FIELD_DURATION, GetUInt32Value(ITEM_FIELD_DURATION) - diff);
SetState(ITEM_CHANGED, owner); // save new time in database
}
void Item::SaveToDB(SQLTransaction& trans)
{
bool isInTransaction = !(trans.null());
if (!isInTransaction)
trans = CharacterDatabase.BeginTransaction();
uint32 guid = GetGUIDLow();
switch (uState)
{
case ITEM_NEW:
case ITEM_CHANGED:
{
uint8 index = 0;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_ADD_ITEM_INSTANCE : CHAR_UPDATE_ITEM_INSTANCE);
stmt->setUInt32( index, GetEntry());
stmt->setUInt32(++index, GUID_LOPART(GetOwnerGUID()));
stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_CREATOR)));
stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_GIFTCREATOR)));
stmt->setUInt32(++index, GetCount());
stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURATION));
std::ostringstream ssSpells;
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
ssSpells << GetSpellCharges(i) << ' ';
stmt->setString(++index, ssSpells.str());
stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_FLAGS));
std::ostringstream ssEnchants;
for (uint8 i = 0; i < MAX_ENCHANTMENT_SLOT; ++i)
{
ssEnchants << GetEnchantmentId(EnchantmentSlot(i)) << ' ';
ssEnchants << GetEnchantmentDuration(EnchantmentSlot(i)) << ' ';
ssEnchants << GetEnchantmentCharges(EnchantmentSlot(i)) << ' ';
}
stmt->setString(++index, ssEnchants.str());
stmt->setInt32 (++index, GetItemRandomPropertyId());
stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURABILITY));
stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME));
stmt->setString(++index, m_text);
stmt->setUInt32(++index, guid);
trans->Append(stmt);
if ((uState == ITEM_CHANGED) && HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_GIFT_OWNER);
stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID()));
stmt->setUInt32(1, guid);
trans->Append(stmt);
}
break;
}
case ITEM_REMOVED:
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, guid);
trans->Append(stmt);
if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT);
stmt->setUInt32(0, guid);
trans->Append(stmt);
}
if (!isInTransaction)
CharacterDatabase.CommitTransaction(trans);
delete this;
return;
}
case ITEM_UNCHANGED:
break;
}
SetState(ITEM_UNCHANGED);
if (!isInTransaction)
CharacterDatabase.CommitTransaction(trans);
}
bool Item::LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry)
{
// 0 1 2 3 4 5 6 7 8 9 10
//result = CharacterDatabase.PQuery("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text FROM item_instance WHERE guid = '%u'", guid);
// create item before any checks for store correct guid
// and allow use "FSetState(ITEM_REMOVED); SaveToDB();" for deleting item from DB
Object::_Create(guid, 0, HIGHGUID_ITEM);
// Set entry, MUST be before proto check
SetEntry(entry);
SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
ItemTemplate const* proto = GetTemplate();
if (!proto)
return false;
// set owner (not if item is only loaded for gbank/auction/mail
if (owner_guid != 0)
SetOwnerGUID(owner_guid);
bool need_save = false; // need explicit save data at load fixes
SetUInt64Value(ITEM_FIELD_CREATOR, MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER));
SetUInt64Value(ITEM_FIELD_GIFTCREATOR, MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_PLAYER));
SetCount(fields[2].GetUInt32());
uint32 duration = fields[3].GetUInt32();
SetUInt32Value(ITEM_FIELD_DURATION, duration);
// update duration if need, and remove if not need
if ((proto->Duration == 0) != (duration == 0))
{
SetUInt32Value(ITEM_FIELD_DURATION, abs(proto->Duration));
need_save = true;
}
Tokens tokens(fields[4].GetString(), ' ', MAX_ITEM_PROTO_SPELLS);
if (tokens.size() == MAX_ITEM_PROTO_SPELLS)
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
SetSpellCharges(i, atoi(tokens[i]));
SetUInt32Value(ITEM_FIELD_FLAGS, fields[5].GetUInt32());
// Remove bind flag for items vs NO_BIND set
if (IsSoulBound() && proto->Bonding == NO_BIND)
{
ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_SOULBOUND, false);
need_save = true;
}
std::string enchants = fields[6].GetString();
_LoadIntoDataField(enchants.c_str(), ITEM_FIELD_ENCHANTMENT_1_1, MAX_ENCHANTMENT_SLOT * MAX_ENCHANTMENT_OFFSET);
SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, fields[7].GetInt16());
// recalculate suffix factor
if (GetItemRandomPropertyId() < 0)
UpdateItemSuffixFactor();
uint32 durability = fields[8].GetUInt16();
SetUInt32Value(ITEM_FIELD_DURABILITY, durability);
// update max durability (and durability) if need
SetUInt32Value(ITEM_FIELD_MAXDURABILITY, proto->MaxDurability);
if (durability > proto->MaxDurability)
{
SetUInt32Value(ITEM_FIELD_DURABILITY, proto->MaxDurability);
need_save = true;
}
SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, fields[9].GetUInt32());
SetText(fields[10].GetString());
if (need_save) // normal item changed state set not work at loading
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ITEM_INSTANCE_ON_LOAD);
stmt->setUInt32(0, GetUInt32Value(ITEM_FIELD_DURATION));
stmt->setUInt32(1, GetUInt32Value(ITEM_FIELD_FLAGS));
stmt->setUInt32(2, GetUInt32Value(ITEM_FIELD_DURABILITY));
stmt->setUInt32(3, guid);
CharacterDatabase.Execute(stmt);
}
return true;
}
/*static*/
void Item::DeleteFromDB(SQLTransaction& trans, uint32 itemGuid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, itemGuid);
trans->Append(stmt);
}
void Item::DeleteFromDB(SQLTransaction& trans)
{
DeleteFromDB(trans, GetGUIDLow());
}
/*static*/
void Item::DeleteFromInventoryDB(SQLTransaction& trans, uint32 itemGuid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVENTORY_ITEM);
stmt->setUInt32(0, itemGuid);
trans->Append(stmt);
}
void Item::DeleteFromInventoryDB(SQLTransaction& trans)
{
DeleteFromInventoryDB(trans, GetGUIDLow());
}
ItemTemplate const* Item::GetTemplate() const
{
return sObjectMgr->GetItemTemplate(GetEntry());
}
Player* Item::GetOwner()const
{
return ObjectAccessor::FindPlayer(GetOwnerGUID());
}
uint32 Item::GetSkill()
{
const static uint32 item_weapon_skills[MAX_ITEM_SUBCLASS_WEAPON] =
{
SKILL_AXES, SKILL_2H_AXES, SKILL_BOWS, SKILL_GUNS, SKILL_MACES,
SKILL_2H_MACES, SKILL_POLEARMS, SKILL_SWORDS, SKILL_2H_SWORDS, 0,
SKILL_STAVES, 0, 0, SKILL_FIST_WEAPONS, 0,
SKILL_DAGGERS, SKILL_THROWN, SKILL_ASSASSINATION, SKILL_CROSSBOWS, SKILL_WANDS,
SKILL_FISHING
};
const static uint32 item_armor_skills[MAX_ITEM_SUBCLASS_ARMOR] =
{
0, SKILL_CLOTH, SKILL_LEATHER, SKILL_MAIL, SKILL_PLATE_MAIL, 0, SKILL_SHIELD, 0, 0, 0, 0
};
ItemTemplate const* proto = GetTemplate();
switch (proto->Class)
{
case ITEM_CLASS_WEAPON:
if (proto->SubClass >= MAX_ITEM_SUBCLASS_WEAPON)
return 0;
else
return item_weapon_skills[proto->SubClass];
case ITEM_CLASS_ARMOR:
if (proto->SubClass >= MAX_ITEM_SUBCLASS_ARMOR)
return 0;
else
return item_armor_skills[proto->SubClass];
default:
return 0;
}
}
uint32 Item::GetSpell()
{
ItemTemplate const* proto = GetTemplate();
switch (proto->Class)
{
case ITEM_CLASS_WEAPON:
switch (proto->SubClass)
{
case ITEM_SUBCLASS_WEAPON_AXE: return 196;
case ITEM_SUBCLASS_WEAPON_AXE2: return 197;
case ITEM_SUBCLASS_WEAPON_BOW: return 264;
case ITEM_SUBCLASS_WEAPON_GUN: return 266;
case ITEM_SUBCLASS_WEAPON_MACE: return 198;
case ITEM_SUBCLASS_WEAPON_MACE2: return 199;
case ITEM_SUBCLASS_WEAPON_POLEARM: return 200;
case ITEM_SUBCLASS_WEAPON_SWORD: return 201;
case ITEM_SUBCLASS_WEAPON_SWORD2: return 202;
case ITEM_SUBCLASS_WEAPON_STAFF: return 227;
case ITEM_SUBCLASS_WEAPON_DAGGER: return 1180;
case ITEM_SUBCLASS_WEAPON_THROWN: return 2567;
case ITEM_SUBCLASS_WEAPON_CROSSBOW:return 5011;
case ITEM_SUBCLASS_WEAPON_WAND: return 5009;
default: return 0;
}
case ITEM_CLASS_ARMOR:
switch (proto->SubClass)
{
case ITEM_SUBCLASS_ARMOR_CLOTH: return 9078;
case ITEM_SUBCLASS_ARMOR_LEATHER: return 9077;
case ITEM_SUBCLASS_ARMOR_MAIL: return 8737;
case ITEM_SUBCLASS_ARMOR_PLATE: return 750;
case ITEM_SUBCLASS_ARMOR_SHIELD: return 9116;
default: return 0;
}
}
return 0;
}
int32 Item::GenerateItemRandomPropertyId(uint32 item_id)
{
ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id);
if (!itemProto)
return 0;
// item must have one from this field values not null if it can have random enchantments
if ((!itemProto->RandomProperty) && (!itemProto->RandomSuffix))
return 0;
// item can have not null only one from field values
if ((itemProto->RandomProperty) && (itemProto->RandomSuffix))
{
sLog->outErrorDb("Item template %u have RandomProperty == %u and RandomSuffix == %u, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix);
return 0;
}
// RandomProperty case
if (itemProto->RandomProperty)
{
uint32 randomPropId = GetItemEnchantMod(itemProto->RandomProperty);
ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId);
if (!random_id)
{
sLog->outErrorDb("Enchantment id #%u used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId);
return 0;
}
return random_id->ID;
}
// RandomSuffix case
else
{
uint32 randomPropId = GetItemEnchantMod(itemProto->RandomSuffix);
ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId);
if (!random_id)
{
sLog->outErrorDb("Enchantment id #%u used but it doesn't have records in sItemRandomSuffixStore.", randomPropId);
return 0;
}
return -int32(random_id->ID);
}
}
void Item::SetItemRandomProperties(int32 randomPropId)
{
if (!randomPropId)
return;
if (randomPropId > 0)
{
ItemRandomPropertiesEntry const* item_rand = sItemRandomPropertiesStore.LookupEntry(randomPropId);
if (item_rand)
{
if (GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID) != int32(item_rand->ID))
{
SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, item_rand->ID);
SetState(ITEM_CHANGED, GetOwner());
}
for (uint32 i = PROP_ENCHANTMENT_SLOT_2; i < PROP_ENCHANTMENT_SLOT_2 + 3; ++i)
SetEnchantment(EnchantmentSlot(i), item_rand->enchant_id[i - PROP_ENCHANTMENT_SLOT_2], 0, 0);
}
}
else
{
ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(-randomPropId);
if (item_rand)
{
if (GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID) != -int32(item_rand->ID) ||
!GetItemSuffixFactor())
{
SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, -int32(item_rand->ID));
UpdateItemSuffixFactor();
SetState(ITEM_CHANGED, GetOwner());
}
for (uint32 i = PROP_ENCHANTMENT_SLOT_0; i < PROP_ENCHANTMENT_SLOT_0 + 3; ++i)
SetEnchantment(EnchantmentSlot(i), item_rand->enchant_id[i - PROP_ENCHANTMENT_SLOT_0], 0, 0);
}
}
}
void Item::UpdateItemSuffixFactor()
{
uint32 suffixFactor = GenerateEnchSuffixFactor(GetEntry());
if (GetItemSuffixFactor() == suffixFactor)
return;
SetUInt32Value(ITEM_FIELD_PROPERTY_SEED, suffixFactor);
}
void Item::SetState(ItemUpdateState state, Player* forplayer)
{
if (uState == ITEM_NEW && state == ITEM_REMOVED)
{
// pretend the item never existed
RemoveFromUpdateQueueOf(forplayer);
forplayer->DeleteRefundReference(GetGUIDLow());
delete this;
return;
}
if (state != ITEM_UNCHANGED)
{
// new items must stay in new state until saved
if (uState != ITEM_NEW)
uState = state;
AddToUpdateQueueOf(forplayer);
}
else
{
// unset in queue
// the item must be removed from the queue manually
uQueuePos = -1;
uState = ITEM_UNCHANGED;
}
}
void Item::AddToUpdateQueueOf(Player* player)
{
if (IsInUpdateQueue())
return;
ASSERT(player != NULL);
if (player->GetGUID() != GetOwnerGUID())
{
sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item::AddToUpdateQueueOf - Owner's guid (%u) and player's guid (%u) don't match!", GUID_LOPART(GetOwnerGUID()), player->GetGUIDLow());
return;
}
if (player->_itemUpdateQueueBlocked)
return;
player->m_itemUpdateQueue.push_back(this);
uQueuePos = player->m_itemUpdateQueue.size()-1;
}
void Item::RemoveFromUpdateQueueOf(Player* player)
{
if (!IsInUpdateQueue())
return;
ASSERT(player != NULL)
if (player->GetGUID() != GetOwnerGUID())
{
sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item::RemoveFromUpdateQueueOf - Owner's guid (%u) and player's guid (%u) don't match!", GUID_LOPART(GetOwnerGUID()), player->GetGUIDLow());
return;
}
if (player->_itemUpdateQueueBlocked)
return;
player->m_itemUpdateQueue[uQueuePos] = NULL;
uQueuePos = -1;
}
uint8 Item::GetBagSlot() const
{
return m_container ? m_container->GetSlot() : uint8(INVENTORY_SLOT_BAG_0);
}
bool Item::IsEquipped() const
{
return !IsInBag() && m_slot < EQUIPMENT_SLOT_END;
}
bool Item::CanBeTraded(bool mail, bool trade) const
{
if (_lootGenerated)
return false;
if ((!mail || !IsBoundAccountWide()) && (IsSoulBound() && (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE) || !trade)))
return false;
if (IsBag() && (Player::IsBagPos(GetPos()) || !((Bag const*)this)->IsEmpty()))
return false;
if (Player* owner = GetOwner())
{
if (owner->CanUnequipItem(GetPos(), false) != EQUIP_ERR_OK)
return false;
if (owner->GetLootGUID() == GetGUID())
return false;
}
if (IsBoundByEnchant())
return false;
return true;
}
bool Item::HasEnchantRequiredSkill(const Player* player) const
{
// Check all enchants for required skill
for (uint32 enchant_slot = PERM_ENCHANTMENT_SLOT; enchant_slot < MAX_ENCHANTMENT_SLOT; ++enchant_slot)
if (uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)))
if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id))
if (enchantEntry->requiredSkill && player->GetSkillValue(enchantEntry->requiredSkill) < enchantEntry->requiredSkillValue)
return false;
return true;
}
uint32 Item::GetEnchantRequiredLevel() const
{
uint32 level = 0;
// Check all enchants for required level
for (uint32 enchant_slot = PERM_ENCHANTMENT_SLOT; enchant_slot < MAX_ENCHANTMENT_SLOT; ++enchant_slot)
if (uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)))
if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id))
if (enchantEntry->requiredLevel > level)
level = enchantEntry->requiredLevel;
return level;
}
bool Item::IsBoundByEnchant() const
{
// Check all enchants for soulbound
for (uint32 enchant_slot = PERM_ENCHANTMENT_SLOT; enchant_slot < MAX_ENCHANTMENT_SLOT; ++enchant_slot)
if (uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)))
if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id))
if (enchantEntry->slot & ENCHANTMENT_CAN_SOULBOUND)
return true;
return false;
}
InventoryResult Item::CanBeMergedPartlyWith(ItemTemplate const* proto) const
{
// not allow merge looting currently items
if (_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
// check item type
if (GetEntry() != proto->ItemId)
return EQUIP_ERR_ITEM_CANT_STACK;
// check free space (full stacks can't be target of merge
if (GetCount() >= proto->GetMaxStackSize())
return EQUIP_ERR_ITEM_CANT_STACK;
return EQUIP_ERR_OK;
}
bool Item::IsFitToSpellRequirements(SpellInfo const* spellInfo) const
{
ItemTemplate const* proto = GetTemplate();
if (spellInfo->EquippedItemClass != -1) // -1 == any item class
{
// Special case - accept vellum for armor/weapon requirements
if ((spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR && proto->IsArmorVellum()))
if (spellInfo->IsAbilityOfSkillType(SKILL_ENCHANTING)) // only for enchanting spells
return true;
if (spellInfo->EquippedItemClass != int32(proto->Class))
return false; // wrong item class
if (spellInfo->EquippedItemSubClassMask != 0) // 0 == any subclass
{
if ((spellInfo->EquippedItemSubClassMask & (1 << proto->SubClass)) == 0)
return false; // subclass not present in mask
}
}
if (spellInfo->EquippedItemInventoryTypeMask != 0) // 0 == any inventory type
{
// Special case - accept weapon type for main and offhand requirements
if (proto->InventoryType == INVTYPE_WEAPON &&
(spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONMAINHAND) ||
spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONOFFHAND)))
return true;
else if ((spellInfo->EquippedItemInventoryTypeMask & (1 << proto->InventoryType)) == 0)
return false; // inventory type not present in mask
}
return true;
}
void Item::SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges)
{
// Better lost small time at check in comparison lost time at item save to DB.
if ((GetEnchantmentId(slot) == id) && (GetEnchantmentDuration(slot) == duration) && (GetEnchantmentCharges(slot) == charges))
return;
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET, id);
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration);
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges);
SetState(ITEM_CHANGED, GetOwner());
}
void Item::SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner)
{
if (GetEnchantmentDuration(slot) == duration)
return;
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration);
SetState(ITEM_CHANGED, owner);
// Cannot use GetOwner() here, has to be passed as an argument to avoid freeze due to hashtable locking
}
void Item::SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges)
{
if (GetEnchantmentCharges(slot) == charges)
return;
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges);
SetState(ITEM_CHANGED, GetOwner());
}
void Item::ClearEnchantment(EnchantmentSlot slot)
{
if (!GetEnchantmentId(slot))
return;
for (uint8 x = 0; x < MAX_ITEM_ENCHANTMENT_EFFECTS; ++x)
SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + x, 0);
SetState(ITEM_CHANGED, GetOwner());
}
bool Item::GemsFitSockets() const
{
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot)
{
uint8 SocketColor = GetTemplate()->Socket[enchant_slot-SOCK_ENCHANTMENT_SLOT].Color;
if (!SocketColor) // no socket slot
continue;
uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id) // no gems on this socket
return false;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry) // invalid gem id on this socket
return false;
uint8 GemColor = 0;
uint32 gemid = enchantEntry->GemID;
if (gemid)
{
ItemTemplate const* gemProto = sObjectMgr->GetItemTemplate(gemid);
if (gemProto)
{
GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
if (gemProperty)
GemColor = gemProperty->color;
}
}
if (!(GemColor & SocketColor)) // bad gem color on this socket
return false;
}
return true;
}
uint8 Item::GetGemCountWithID(uint32 GemID) const
{
uint8 count = 0;
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot)
{
uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
if (GemID == enchantEntry->GemID)
++count;
}
return count;
}
uint8 Item::GetGemCountWithLimitCategory(uint32 limitCategory) const
{
uint8 count = 0;
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot)
{
uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
ItemTemplate const* gemProto = sObjectMgr->GetItemTemplate(enchantEntry->GemID);
if (!gemProto)
continue;
if (gemProto->ItemLimitCategory == limitCategory)
++count;
}
return count;
}
bool Item::IsLimitedToAnotherMapOrZone(uint32 cur_mapId, uint32 cur_zoneId) const
{
ItemTemplate const* proto = GetTemplate();
return proto && ((proto->Map && proto->Map != cur_mapId) || (proto->Area && proto->Area != cur_zoneId));
}
// Though the client has the information in the item's data field,
// we have to send SMSG_ITEM_TIME_UPDATE to display the remaining
// time.
void Item::SendTimeUpdate(Player* owner)
{
uint32 duration = GetUInt32Value(ITEM_FIELD_DURATION);
if (!duration)
return;
WorldPacket data(SMSG_ITEM_TIME_UPDATE, (8+4));
data << uint64(GetGUID());
data << uint32(duration);
owner->GetSession()->SendPacket(&data);
}
Item* Item::CreateItem(uint32 item, uint32 count, Player const* player)
{
if (count < 1)
return NULL; //don't create item at zero count
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item);
if (proto)
{
if (count > proto->GetMaxStackSize())
count = proto->GetMaxStackSize();
ASSERT(count !=0 && "proto->Stackable == 0 but checked at loading already");
Item* pItem = NewItemOrBag(proto);
if (pItem->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_ITEM), item, player))
{
pItem->SetCount(count);
return pItem;
}
else
delete pItem;
}
else
ASSERT(false);
return NULL;
}
Item* Item::CloneItem(uint32 count, Player const* player) const
{
Item* newItem = CreateItem(GetEntry(), count, player);
if (!newItem)
return NULL;
newItem->SetUInt32Value(ITEM_FIELD_CREATOR, GetUInt32Value(ITEM_FIELD_CREATOR));
newItem->SetUInt32Value(ITEM_FIELD_GIFTCREATOR, GetUInt32Value(ITEM_FIELD_GIFTCREATOR));
newItem->SetUInt32Value(ITEM_FIELD_FLAGS, GetUInt32Value(ITEM_FIELD_FLAGS));
newItem->SetUInt32Value(ITEM_FIELD_DURATION, GetUInt32Value(ITEM_FIELD_DURATION));
// player CAN be NULL in which case we must not update random properties because that accesses player's item update queue
if (player)
newItem->SetItemRandomProperties(GetItemRandomPropertyId());
return newItem;
}
bool Item::IsBindedNotWith(Player const* player) const
{
// not binded item
if (!IsSoulBound())
return false;
// own item
if (GetOwnerGUID() == player->GetGUID())
return false;
if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE))
if (allowedGUIDs.find(player->GetGUIDLow()) != allowedGUIDs.end())
return false;
// BOA item case
if (IsBoundAccountWide())
return false;
return true;
}
void Item::BuildUpdate(UpdateDataMapType& data_map)
{
if (Player* owner = GetOwner())
BuildFieldsUpdate(owner, data_map);
ClearUpdateMask(false);
}
void Item::SaveRefundDataToDB()
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
trans->PAppend("DELETE FROM item_refund_instance WHERE item_guid = '%u'", GetGUIDLow());
trans->PAppend("INSERT INTO item_refund_instance (`item_guid`, `player_guid`, `paidMoney`, `paidExtendedCost`)"
" VALUES('%u', '%u', '%u', '%u')", GetGUIDLow(), GetRefundRecipient(), GetPaidMoney(), GetPaidExtendedCost());
CharacterDatabase.CommitTransaction(trans);
}
void Item::DeleteRefundDataFromDB(SQLTransaction* trans)
{
if (trans && !trans->null())
(*trans)->PAppend("DELETE FROM item_refund_instance WHERE item_guid = '%u'", GetGUIDLow());
}
void Item::SetNotRefundable(Player* owner, bool changestate /*=true*/, SQLTransaction* trans /*=NULL*/)
{
if (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
return;
RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
// Following is not applicable in the trading procedure
if (changestate)
SetState(ITEM_CHANGED, owner);
SetRefundRecipient(0);
SetPaidMoney(0);
SetPaidExtendedCost(0);
DeleteRefundDataFromDB(trans);
owner->DeleteRefundReference(GetGUIDLow());
}
void Item::UpdatePlayedTime(Player* owner)
{
/* Here we update our played time
We simply add a number to the current played time,
based on the time elapsed since the last update hereof.
*/
// Get current played time
uint32 current_playtime = GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME);
// Calculate time elapsed since last played time update
time_t curtime = time(NULL);
uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate);
uint32 new_playtime = current_playtime + elapsed;
// Check if the refund timer has expired yet
if (new_playtime <= 2*HOUR)
{
// No? Proceed.
// Update the data field
SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, new_playtime);
// Flag as changed to get saved to DB
SetState(ITEM_CHANGED, owner);
// Speaks for itself
m_lastPlayedTimeUpdate = curtime;
return;
}
// Yes
SetNotRefundable(owner);
}
uint32 Item::GetPlayedTime()
{
time_t curtime = time(NULL);
uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate);
return GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + elapsed;
}
bool Item::IsRefundExpired()
{
return (GetPlayedTime() > 2*HOUR);
}
void Item::SetSoulboundTradeable(AllowedLooterSet& allowedLooters)
{
SetFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE);
allowedGUIDs = allowedLooters;
}
void Item::ClearSoulboundTradeable(Player* currentOwner)
{
RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE);
if (allowedGUIDs.empty())
return;
allowedGUIDs.clear();
SetState(ITEM_CHANGED, currentOwner);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_BOP_TRADE);
stmt->setUInt32(0, GetGUIDLow());
CharacterDatabase.Execute(stmt);
}
bool Item::CheckSoulboundTradeExpire()
{
// called from owner's update - GetOwner() MUST be valid
if (GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + 2*HOUR < GetOwner()->GetTotalPlayedTime())
{
ClearSoulboundTradeable(GetOwner());
return true; // remove from tradeable list
}
return false;
}
| gpl-3.0 |
electricpandafishstudios/Spoon | game/modules/tome-1.4.1/data/birth/classes/rogue.lua | 10564 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2016 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newBirthDescriptor{
type = "class",
name = "Rogue",
desc = {
"Rogues are masters of tricks; they can strike from the shadows, and lure monsters into deadly traps.",
},
descriptor_choices =
{
subclass =
{
__ALL__ = "disallow",
Rogue = "allow",
Shadowblade = "allow",
Marauder = "allow",
Skirmisher = "allow",
},
},
copy = {
max_life = 100,
},
}
newBirthDescriptor{
type = "subclass",
name = "Rogue",
desc = {
"Rogues are masters of tricks. A Rogue can get behind you unnoticed and stab you in the back for tremendous damage.",
"Rogues usually prefer to dual-wield daggers. They can also become trapping experts, detecting and disarming traps as well as setting them.",
"Their most important stats are: Dexterity and Cunning",
"#GOLD#Stat modifiers:",
"#LIGHT_BLUE# * +1 Strength, +3 Dexterity, +0 Constitution",
"#LIGHT_BLUE# * +0 Magic, +0 Willpower, +5 Cunning",
"#GOLD#Life per level:#LIGHT_BLUE# +0",
},
power_source = {technique=true},
stats = { dex=3, str=1, cun=5, },
talents_types = {
["technique/dualweapon-attack"]={true, 0.3},
["technique/dualweapon-training"]={true, 0.3},
["technique/combat-techniques-active"]={false, 0.3},
["technique/combat-techniques-passive"]={false, 0.3},
["technique/combat-training"]={true, 0.3},
["technique/field-control"]={false, 0},
["technique/acrobatics"]={true, 0.3},
["cunning/stealth"]={true, 0.3},
["cunning/trapping"]={true, 0.3},
["cunning/dirty"]={true, 0.3},
["cunning/lethality"]={true, 0.3},
["cunning/survival"]={true, 0.3},
["cunning/scoundrel"]={true, 0.3},
},
unlockable_talents_types = {
["cunning/poisons"]={false, 0.3, "rogue_poisons"},
},
talents = {
[ActorTalents.T_SHOOT] = 1,
[ActorTalents.T_STEALTH] = 1,
[ActorTalents.T_TRAP_MASTERY] = 1,
[ActorTalents.T_LETHALITY] = 1,
[ActorTalents.T_DUAL_STRIKE] = 1,
[ActorTalents.T_KNIFE_MASTERY] = 1,
[ActorTalents.T_WEAPON_COMBAT] = 1,
},
copy = {
equipment = resolvers.equipbirth{ id=true,
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="armor", subtype="light", name="rough leather armour", autoreq=true, ego_chance=-1000}
},
resolvers.inventorybirth{ id=true, inven="QS_MAINHAND",
{type="weapon", subtype="sling", name="rough leather sling", autoreq=true, ego_chance=-1000},
},
resolvers.inventorybirth{ id=true, inven="QS_QUIVER",
{type="ammo", subtype="shot", name="pouch of iron shots", autoreq=true, ego_chance=-1000},
},
},
}
newBirthDescriptor{
type = "subclass",
name = "Shadowblade",
desc = {
"Shadowblades are Rogues that are touched by the gift of magic, able to kill with their daggers under a veil of stealth while casting spells to enhance their performance and survival.",
"Their use of magic is innate and not really studied; as such they do not naturally regenerate mana and must use external means of recharging.",
"They use the schools of Phantasm, Temporal, Divination and Conveyance magic to enhance their arts.",
"Their most important stats are: Dexterity, Cunning and Magic",
"#GOLD#Stat modifiers:",
"#LIGHT_BLUE# * +0 Strength, +3 Dexterity, +0 Constitution",
"#LIGHT_BLUE# * +3 Magic, +0 Willpower, +3 Cunning",
"#GOLD#Life per level:#LIGHT_BLUE# +0",
},
power_source = {technique=true, arcane=true},
stats = { dex=3, mag=3, cun=3, },
talents_types = {
["spell/phantasm"]={true, 0},
["spell/temporal"]={false, 0},
["spell/divination"]={false, 0},
["spell/conveyance"]={true, 0},
["technique/dualweapon-attack"]={true, 0.2},
["technique/dualweapon-training"]={true, 0.2},
["technique/combat-techniques-active"]={true, 0.3},
["technique/combat-techniques-passive"]={false, 0.3},
["technique/combat-training"]={true, 0.2},
["cunning/stealth"]={false, 0.3},
["cunning/survival"]={true, 0.1},
["cunning/lethality"]={true, 0.3},
["cunning/dirty"]={true, 0.3},
["cunning/shadow-magic"]={true, 0.3},
["cunning/ambush"]={false, 0.3},
},
talents = {
[ActorTalents.T_DUAL_STRIKE] = 1,
[ActorTalents.T_SHADOW_COMBAT] = 1,
[ActorTalents.T_PHASE_DOOR] = 1,
[ActorTalents.T_LETHALITY] = 1,
[ActorTalents.T_KNIFE_MASTERY] = 1,
[ActorTalents.T_WEAPON_COMBAT] = 1,
},
copy = {
resolvers.inscription("RUNE:_MANASURGE", {cooldown=25, dur=10, mana=620}),
equipment = resolvers.equipbirth{ id=true,
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="armor", subtype="light", name="rough leather armour", autoreq=true, ego_chance=-1000}
},
},
}
newBirthDescriptor{
type = "subclass",
name = "Marauder",
locked = function() return profile.mod.allow_build.rogue_marauder end,
locked_desc = "I will not hide and I will not sneak - come dance with my blades and we'll see who's weak. Snapping bone and cracking skull, it's the sounds of battle that make life full!",
desc = {
"The wilds of Maj'Eyal are not a safe place. Untamed beasts and wandering dragons may seem a great threat, but the true perils walk on two legs. Thieves and brigands, assassins and opportunistic adventurers, even mad wizards and magic-hating zealots all carry danger to those who venture beyond the safety of city walls.",
"Amidst this chaos wanders one class of rogue that has learned to take by force rather than subterfuge. With refined techniques, agile feats and brawn-backed blades the Marauder seeks out his targets and removes them by the most direct methods. He uses dual weapons backed by advanced combat training to become highly effective in battle, and he is unafraid to use the dirtiest tactics when the odds are against him.",
"Their most important stats are: Strength, Dexterity and Cunning",
"#GOLD#Stat modifiers:",
"#LIGHT_BLUE# * +4 Strength, +4 Dexterity, +0 Constitution",
"#LIGHT_BLUE# * +0 Magic, +0 Willpower, +1 Cunning",
"#GOLD#Life per level:#LIGHT_BLUE# +0",
},
stats = { dex=4, str=4, cun=1, },
talents_types = {
["technique/dualweapon-attack"]={true, 0.2},
["technique/dualweapon-training"]={true, 0.2},
["technique/combat-techniques-active"]={true, 0.3},
["technique/combat-techniques-passive"]={true, 0.0},
["technique/combat-training"]={true, 0.3},
["technique/field-control"]={true, 0.3},
["technique/battle-tactics"]={false, 0.2},
["technique/mobility"]={true, 0.3},
["technique/thuggery"]={true, 0.3},
["technique/conditioning"]={true, 0.3},
["technique/bloodthirst"]={false, 0.1},
["cunning/dirty"]={true, 0.3},
["cunning/tactical"]={false, 0.2},
["cunning/survival"]={true, 0.3},
},
unlockable_talents_types = {
["cunning/poisons"]={false, -0.1, "rogue_poisons"},
},
talents = {
[ActorTalents.T_DIRTY_FIGHTING] = 1,
[ActorTalents.T_SKULLCRACKER] = 1,
[ActorTalents.T_HACK_N_BACK] = 1,
[ActorTalents.T_DUAL_STRIKE] = 1,
[ActorTalents.T_ARMOUR_TRAINING] = 1,
},
copy = {
equipment = resolvers.equipbirth{ id=true,
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="weapon", subtype="dagger", name="iron dagger", autoreq=true, ego_chance=-1000},
{type="armor", subtype="light", name="rough leather armour", autoreq=true, ego_chance=-1000},
{type="armor", subtype="head", name="iron helm", autoreq=true, ego_chance=-1000},
},
},
}
newBirthDescriptor{
type = "subclass",
name = "Skirmisher",
locked = function() return profile.mod.allow_build.rogue_skirmisher end,
locked_desc = "Fleet of foot and strong of throw, overwhelming every foe, from afar we counter, strike and thud, in the chaos'd skirmish spilling blood.",
desc = {
"While able to take maximum advantage of their sling by using deft movements to avoid and confuse enemies that try to get close, the Skirmisher truly excels when fighting other ranged users.",
"They have mastered the use of their shield as well as their sling and are nearly impossible to defeat in a standoff.",
"Their most important stats are: Dexterity and Cunning",
"#GOLD#Stat modifiers:",
"#LIGHT_BLUE# * +0 Strength, +4 Dexterity, +0 Constitution",
"#LIGHT_BLUE# * +0 Magic, +1 Willpower, +4 Cunning",
"#GOLD#Life per level:#LIGHT_BLUE# +0",
},
not_on_random_boss = true,
power_source = {technique=true},
stats = {dex = 4, cun = 4, wil = 1},
talents_types = {
-- class
["technique/skirmisher-slings"]={true, 0.3},
["technique/buckler-training"]={true, 0.3},
["cunning/called-shots"]={true, 0.3},
["technique/tireless-combatant"]={true, 0.3},
["cunning/trapping"]={false, 0.1},
-- generic
["technique/acrobatics"]={true, 0.3},
["cunning/survival"]={true, 0.3},
["technique/combat-training"]={true, 0.3},
["technique/field-control"]={false, 0.1},
},
unlockable_talents_types = {
["cunning/poisons"]={false, 0.2, "rogue_poisons"},
},
talents = {
[ActorTalents.T_SKIRMISHER_VAULT] = 1,
[ActorTalents.T_SHOOT] = 1,
[ActorTalents.T_SKIRMISHER_KNEECAPPER] = 1,
[ActorTalents.T_SKIRMISHER_SLING_SUPREMACY] = 1,
[ActorTalents.T_SKIRMISHER_BUCKLER_EXPERTISE] = 1,
[ActorTalents.T_WEAPON_COMBAT] = 1,
},
copy = {
resolvers.equipbirth{
id=true,
{type="armor", subtype="light", name="rough leather armour", autoreq=true,ego_chance=-1000},
{type="weapon", subtype="sling", name="rough leather sling", autoreq=true, ego_chance=-1000},
{type="armor", subtype="shield", name="iron shield", autoreq=false, ego_chance=-1000, ego_chance=-1000},
{type="ammo", subtype="shot", name="pouch of iron shots", autoreq=true, ego_chance=-1000},
},
resolvers.generic(function(e)
e.auto_shoot_talent = e.T_SHOOT
end),
},
copy_add = {
life_rating = 0,
},
}
| gpl-3.0 |
sgtfrankieboy/Reddit-Enhancement-Suite | lib/core/utils.js | 62687 | $.fn.safeHtml = function(string) {
if (!string) return '';
else return $(this).html(RESUtils.sanitizeHTML(string));
};
if (typeof Array.prototype.find !== 'function') {
Array.prototype.find = function(predicate) {
if (this === undefined || this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
if (typeof Array.prototype.findIndex !== 'function') {
Array.prototype.findIndex = function(predicate) {
if (this === undefined || this === null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}
// define common RESUtils - reddit related functions and data that may need to be accessed...
var RESUtils = RESUtils || {};
// set up arrays for html tag classes and body tag classes to be added as early
// as possible and all at once to avoid excess screen repaints
(function(exports) {
var classes = [];
function initClasses() {
if (!classes.length) {
classes = [ 'res', 'res-v430' ];
var versionComponents = RESMetadata.version.split('.');
for (var i = 0, length = versionComponents.length; i < length; i++) {
classes.push('res-v' + (versionComponents.slice(0, i + 1).join('-')));
}
}
}
var add = function() {
initClasses();
classes = Array.prototype.slice.call(arguments).reduce(function(a, b) {
return a.concat(b);
}, classes);
if (classes.length) {
if (document.html) {
document.html.classList.add.apply(document.html.classList, classes);
}
if (document.body) {
document.body.classList.add.apply(document.body.classList, classes);
}
}
};
var remove = function(classes) {
classes = Array.prototype.slice.call(arguments)
.reduce(function(a, b) {
return a.concat(b);
}, []);
if (classes.length) {
if (document.html) {
document.html.classList.remove.apply(document.html.classList, classes);
}
if (document.body) {
document.body.classList.remove.apply(document.body.classList, classes);
}
}
};
exports.add = add;
exports.remove = remove;
})(RESUtils.bodyClasses = RESUtils.bodyClasses || {});
// A cache variable to store CSS that will be applied at the end of execution...
RESUtils.randomHash = function(len) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var numChars = len || 5;
var randomString = '';
for (var i = 0; i < numChars; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomString += chars.substring(rnum, rnum + 1);
}
return randomString;
};
RESUtils.hashCode = function(str) {
var hash = 0,
i, len, char;
if (str.length === 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
RESUtils.addCSS = function(css) {
var style = RESUtils.addStyle(css);
return {
remove: function() {
style.textContent = '';
if (style.parentNode) {
style.parentNode.removeChild(style);
}
}
};
};
RESUtils.insertParam = function(href, key, value) {
var pre = '&';
if (href.indexOf('?') === -1) pre = '?';
return href + pre + key + '=' + value;
};
// checks if script should run on current URL using exclude / include.
RESUtils.isMatchURL = function(moduleID) {
// stop if not on reddit
if (!RESUtils.isReddit()) {
return false;
}
var module = modules[moduleID];
if (!module) {
console.warn('isMatchURL could not find module', moduleID);
return false;
}
var exclude = module.exclude,
include = module.include;
return RESUtils.matchesPageLocation(include, exclude);
};
RESUtils.matchesPageLocation = function(includes, excludes) {
includes = typeof includes === 'undefined' ? [] : [].concat(includes);
excludes = typeof excludes === 'undefined' ? [] : [].concat(excludes);
var excludesPageType = excludes.length && (RESUtils.isPageType.apply(RESUtils, excludes) || RESUtils.matchesPageRegex.apply(RESUtils, excludes));
if (!excludesPageType) {
var includesPageType = !includes.length || RESUtils.isPageType.apply(RESUtils, includes) || RESUtils.matchesPageRegex.apply(RESUtils, includes);
return includesPageType;
}
};
RESUtils.getUrlParams = function(url) {
var result = {},
re = /([^&=]+)=([^&]*)/g,
m, queryString;
if (url) {
var fullUrlRe = /\?((?:[^&=]+=[^&]*?&?)+)(?:#[^&]*)?$/;
var groups = fullUrlRe.exec(url);
if (groups) {
queryString = groups[1];
} else {
return {};
}
} else {
queryString = location.search.substr(1);
}
while ((m = re.exec(queryString))) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
};
RESUtils.click = function(obj, button) {
var evt = document.createEvent('MouseEvents');
button = button || 0;
evt.initMouseEvent('click', true, true, window.wrappedJSObject, 0, 1, 1, 1, 1, false, false, false, false, button, null);
obj.dispatchEvent(evt);
};
RESUtils.mousedown = function(obj, button) {
var evt = document.createEvent('MouseEvents');
button = button || 0;
evt.initMouseEvent('mousedown', true, true, window.wrappedJSObject, 0, 1, 1, 1, 1, false, false, false, false, button, null);
obj.dispatchEvent(evt);
};
RESUtils.loggedInUser = function(tryingEarly) {
if (typeof this.loggedInUserCached === 'undefined') {
var userLink = document.querySelector('#header-bottom-right > span.user > a');
if ((userLink !== null) && (!userLink.classList.contains('login-required'))) {
this.loggedInUserCached = userLink.textContent;
// HERE BE DRAGONS
// this.verifyHash(this.loggedInUserCached);
this.loggedInUserHashCached = document.querySelector('[name=uh]').value;
} else {
if (tryingEarly) {
// trying early means we're trying before DOM load may be complete, so if we fail here
// we don't want to null this, we want to allow another try.
// currently the only place this is really used is username hider, which tries (if possible)
// to hide the username as early/fast as possible.
delete this.loggedInUserCached;
delete this.loggedInUserHashCached;
} else {
this.loggedInUserCached = null;
}
}
}
return this.loggedInUserCached;
};
RESUtils.isModeratorAnywhere = function() {
// I was given special permission to do this.
return !!document.getElementById('modmail');
};
RESUtils.loggedInUserHash = function() {
this.loggedInUser();
return this.loggedInUserHashCached;
};
RESUtils.problemHashes = [991658920,3385400];
RESUtils.getUserInfo = function(callback, username, live) {
// Default to currently logged-in user, for backwards compatibility
username = (typeof username !== 'undefined' ? username : RESUtils.loggedInUser());
if (username === null) return false;
// Default to getting live data (i.e. from reddit's server)
live = (typeof live === 'boolean' ? live : true);
RESUtils.cache.fetch({
endpoint: 'user/' + encodeURIComponent(username) + '/about.json',
expires: live ? 0 : 300000,
callback: callback
});
};
RESUtils.regexes = {
all: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\//i,
comments: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/[\-\w\.\/]*\/comments/i,
nosubComments: /https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/comments\/[\-\w\.\/]*/i,
friendsComments: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/r\/friends\/comments/i,
inbox: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/(?:r\/[\-\w\.\/]+?\/)?message\//i,
profile: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/user\/([\-\w\.#=]*)\/?(?:comments)?\/?(?:\?(?:[a-z]+=[a-zA-Z0-9_%]*&?)*)?$/i,
submit: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/(?:[\-\w\.\/]*\/)?submit\/?(?:\?.*)?$/i,
prefs: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/prefs/i,
wiki: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/(?:r\/[\-\w\.]+\/)?wiki/i,
stylesheet: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/(?:r\/[\-\w\.]+\/)?about\/stylesheet/i,
search: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/(?:[\-\w\.\/]*\/)?search/i,
toolbar: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/tb\//i,
commentPermalink: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/[\-\w\.\/]*comments\/[a-z0-9]+\/[^\/]+\/[a-z0-9]+$/i,
subreddit: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/r\/([\w\.\+]+)/i,
subredditPostListing: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/r\/([\w\.\+]+)(?:\/(new|rising|controversial|top))?\/?(?:\?.*)?$/i,
multireddit: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/((?:me|user\/[\-\w\.#=]*)\/(?:m|f)\/([\w\.\+]+))/i,
domain: /^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/domain\/([\w\.\+]+)/i
};
RESUtils.verifyHash = function(hash) {
if ($.inArray(RESUtils.hashCode(hash), RESUtils.problemHashes) !== -1) {
throw 'Error';
}
};
RESUtils.isReddit = function() {
var currURL = location.href;
return RESUtils.regexes.all.test(currURL) && !RESUtils.regexes.toolbar.test(currURL);
};
RESUtils.pageType = function() {
if (this.pageTypeSaved !== undefined) {
return this.pageTypeSaved;
}
var currURL = location.href.split('#')[0];
var pageType = '';
if (RESUtils.regexes.wiki.test(currURL)) {
pageType = 'wiki';
} else if (RESUtils.regexes.search.test(currURL)) {
pageType = 'search';
} else if (RESUtils.regexes.profile.test(currURL)) {
pageType = 'profile';
} else if (RESUtils.regexes.comments.test(currURL)) {
pageType = 'comments';
} else if (RESUtils.regexes.inbox.test(currURL)) {
pageType = 'inbox';
} else if (RESUtils.regexes.submit.test(currURL)) {
pageType = 'submit';
} else if (RESUtils.regexes.prefs.test(currURL)) {
pageType = 'prefs';
} else if (RESUtils.regexes.stylesheet.test(currURL)) {
pageType = 'stylesheet';
} else {
pageType = 'linklist';
}
this.pageTypeSaved = pageType;
return pageType;
};
RESUtils.isPageType = function(/*type1, type2, type3, ...*/) {
var thisPage = RESUtils.pageType();
return Array.prototype.slice.call(arguments).some(function(type) {
return (type === 'all') || (type === thisPage);
});
};
RESUtils.matchesPageRegex = function(/*regex1, regex2, regex3, ...*/) {
var href = document.location.href;
return Array.prototype.slice.call(arguments).some(function(regex) {
return regex.test && regex.test(href);
});
};
RESUtils.isCommentPermalinkPage = function() {
if (typeof this.isCommentPermalinkSaved === 'undefined') {
var currURL = location.href.split('#')[0];
if (RESUtils.regexes.commentPermalink.test(currURL)) {
this.isCommentPermalinkSaved = true;
} else {
this.isCommentPermalinkSaved = false;
}
}
return this.isCommentPermalinkSaved;
};
RESUtils.currentSubreddit = function(check) {
if (typeof this.curSub === 'undefined') {
var match = location.href.match(RESUtils.regexes.subreddit);
if (match !== null) {
this.curSub = match[1];
if (check) return (match[1].toLowerCase() === check.toLowerCase());
return match[1];
} else {
if (check) return false;
return null;
}
} else {
if (check) return (this.curSub.toLowerCase() === check.toLowerCase());
return this.curSub;
}
};
RESUtils.thingsContainer = function(body) {
var container;
body = body || document.body;
container = body.querySelectorAll(RESUtils.thing.prototype.containerSelector);
// stupid sponsored links create a second div with ID of sitetable (bad reddit! you should never have 2 IDs with the same name! naughty, naughty reddit!)
if (container.length === 2) {
// console.log('skipped first sitetable, stupid reddit.');
container = container[1];
} else {
container = container[0];
}
return container;
};
RESUtils.things = function(container) {
container = container || RESUtils.thingsContainer();
return $(container).find(RESUtils.thing.prototype.thingSelector);
};
RESUtils.thing = function(element) {
if (!(this instanceof RESUtils.thing)) {
return new RESUtils.thing(element);
}
var $thing = $(element).closest(this.thingSelector);
var thing = $thing[0];
var entry = thing && thing.querySelector(this.entrySelector) || thing;
$.extend(this, {
'$thing': $thing,
thing: thing,
element: thing,
entry: entry,
find: $thing.find.bind($thing),
querySelector: thing ? thing.querySelector.bind(thing) : function() { },
querySelectorAll: thing ? thing.querySelectorAll.bind(thing) : function() { }
});
return this;
};
RESUtils.thing.prototype = {
thingSelector: '.thing, .search-result-link',
entrySelector: '.entry, .search-result-link > :not(.thumbnail)',
containerSelector: '.sitetable, .search-result-listing',
is: function(otherThing) {
if (otherThing && otherThing.element === this.element) {
return true;
}
},
getTitle: function() {
return this.entry.querySelector('a.title, a.search-title');
},
getPostLink: function() {
return this.entry.querySelector('a.title, a.search-link');
},
getCommentsLink: function() {
return this.entry.querySelector('a.comments, a.search-comments');
},
getCommentPermalink: function() {
return this.entry.querySelector('a.bylink');
},
getSubredditLink: function() {
return this.entry.querySelector('a.subreddit, a.search-subreddit-link');
},
getUpvoteButton: function() {
return this._getVoteButton('div.up, div.upmod');
},
getDownvoteButton: function() {
return this._getVoteButton('div.down, div.downmod');
},
_getVoteButton: function(selector) {
var button;
if (this.entry.previousSibling.tagName === 'A') {
button = this.entry.previousSibling.previousSibling.querySelector(selector);
} else {
button = this.entry.previousSibling.querySelector(selector);
}
return button;
},
getExpandoButton: function() {
return this.entry.querySelector('.expando-button, .search-expando-button');
},
getExpandoButtons: function() {
return this.entry.querySelectorAll('.expando-button, .search-expando-button');
}
};
RESUtils.subredditForElement = function(element) {
var $thing = $(element).closest('.thing');
if (!$thing.length) return;
var $subredditElement = $thing.find('.subreddit');
if (!$subredditElement.length) {
$subredditElement = $thing.find('.tagline a').filter(function() {
return RESUtils.regexes.subreddit.test(this.href);
});
}
if (!$subredditElement.length) {
$subredditElement = $('.sitetable .link .subreddit');
}
if ($subredditElement.length) {
var subredditName = $subredditElement[0].href.match(RESUtils.regexes.subreddit)[1];
return subredditName;
}
};
RESUtils.currentMultireddit = function(check) {
if (typeof this.curMulti === 'undefined') {
var match = location.href.match(RESUtils.regexes.multireddit);
if (match !== null) {
this.curMulti = match[1];
if (check) return (match[1].toLowerCase() === check.toLowerCase());
return match[1];
} else {
if (check) return false;
return null;
}
} else {
if (check) return (this.curMulti.toLowerCase() === check.toLowerCase());
return this.curMulti;
}
};
RESUtils.currentDomain = function(check) {
if (typeof this.curDom === 'undefined') {
var match = location.href.match(RESUtils.regexes.domain);
if (match !== null) {
this.curDom = match[1];
if (check) return (match[1].toLowerCase() === check.toLowerCase());
return match[1];
} else {
if (check) return false;
return null;
}
} else {
if (check) return (this.curDom.toLowerCase() === check.toLowerCase());
return this.curDom;
}
};
RESUtils.currentUserProfile = function() {
if (typeof this.curUserProfile === 'undefined') {
var match = location.href.match(RESUtils.regexes.profile);
if (match !== null) {
this.curUserProfile = match[1];
return match[1];
} else {
return null;
}
} else {
return this.curUserProfile;
}
};
RESUtils.subredditForPost = function (thingEle) {
var postSubreddit = '';
var thisSubRedditEle = $(thingEle).find('A.subreddit')[0];
if ((typeof thisSubRedditEle !== 'undefined') && (thisSubRedditEle !== null)) {
postSubreddit = RESUtils.regexes.subreddit.exec(thisSubRedditEle.href)[1] || '';
}
return postSubreddit;
};
RESUtils.getHeaderMenuList = function() {
var mainMenuUL;
if ((/search\?\/?q\=/.test(location.href)) ||
(/\/about\/(?:reports|spam|unmoderated)/.test(location.href)) ||
(location.href.indexOf('/modqueue') !== -1) ||
(location.href.toLowerCase().indexOf('/dashboard') !== -1)) {
var hbl = document.getElementById('header-bottom-left');
if (hbl) {
mainMenuUL = document.createElement('ul');
mainMenuUL.setAttribute('class', 'tabmenu viewimages');
mainMenuUL.setAttribute('style', 'display: inline-block');
hbl.appendChild(mainMenuUL);
}
} else {
mainMenuUL = document.body.querySelector('#header-bottom-left ul.tabmenu');
}
return mainMenuUL;
};
RESUtils.getXYpos = function(obj) {
var topValue = 0,
leftValue = 0;
while (obj) {
leftValue += obj.offsetLeft;
topValue += obj.offsetTop;
obj = obj.offsetParent;
}
return {
'x': leftValue,
'y': topValue
};
};
RESUtils.elementInViewport = function(obj) {
if (!obj) {
return false;
}
var element = RESUtils.getDimensions(obj);
var viewport = RESUtils.getViewportDimensions();
var contained = (
viewport.top <= element.top &&
viewport.left <= element.left &&
element.bottom <= viewport.bottom &&
element.right <= viewport.right
);
return contained;
};
RESUtils.getDimensions = function(obj) {
var headerOffset = this.getHeaderOffset();
var top = obj.offsetTop - headerOffset;
var left = obj.offsetLeft;
var width = obj.offsetWidth;
var height = obj.offsetHeight;
while (obj.offsetParent) {
obj = obj.offsetParent;
top += obj.offsetTop;
left += obj.offsetLeft;
}
var bottom = top + height;
var right = left + width;
return {
yOffset: headerOffset,
x: top,
y: left,
top: top,
left: left,
bottom: bottom,
right: right,
width: width,
height: height
};
};
RESUtils.getViewportDimensions = function() {
var headerOffset = this.getHeaderOffset();
var dimensions = {
yOffset: headerOffset,
x: window.pageXOffset,
y: window.pageYOffset + headerOffset,
width: window.innerWidth,
height: window.innerHeight - headerOffset
};
dimensions.top = dimensions.y;
dimensions.left = dimensions.x;
dimensions.bottom = dimensions.top + dimensions.height;
dimensions.right = dimensions.left + dimensions.width;
return dimensions;
};
// Returns percentage of the element that is within the viewport along the y-axis
// Note that it doesn't matter where the element is on the x-axis, it can be totally invisible to the user
// and this function might still return 1!
RESUtils.getPercentageVisibleYAxis = function(obj) {
var rect = obj.getBoundingClientRect();
var top = Math.max(0, rect.bottom - rect.height);
var bottom = Math.min(document.documentElement.clientHeight, rect.bottom);
if (rect.height === 0) {
return 0;
}
return Math.max(0, (bottom - top) / rect.height);
};
// Returns percentage of the element that is within the viewport along the x-axis
// Note that it doesn't matter where the element is on the y-axis, it can be totally invisible to the user
// and this function might still return 1!
RESUtils.getPercentageVisibleXAxis = function(obj) {
var rect = obj.getBoundingClientRect();
var left = Math.max(0, rect.left);
var right = Math.min(document.documentElement.clientWidth, rect.right);
if (rect.width === 0) {
return 0;
}
return Math.max(0, (right - left) / rect.width);
};
// Returns percentage of the element that is within the viewport
RESUtils.getPercentageVisible = function(obj) {
return RESUtils.getPercentageVisibleXAxis(obj) * RESUtils.getPercentageVisibleYAxis(obj);
};
RESUtils.watchMouseMove = function() {
document.body.addEventListener('mousemove', RESUtils.setMouseXY, false);
};
RESUtils.setMouseXY = function(e) {
e = e || window.event;
var cursor = {
x: 0,
y: 0
};
if (e.pageX || e.pageY) {
cursor.x = e.pageX;
cursor.y = e.pageY;
} else {
cursor.x = e.clientX +
(document.documentElement.scrollLeft ||
document.body.scrollLeft) -
document.documentElement.clientLeft;
cursor.y = e.clientY +
(document.documentElement.scrollTop ||
document.body.scrollTop) -
document.documentElement.clientTop;
}
RESUtils.mouseX = cursor.x;
RESUtils.mouseY = cursor.y;
};
RESUtils.elementUnderMouse = function(obj) {
var $obj = $(obj),
top = $obj.offset().top,
left = $obj.offset().left,
width = $obj.outerWidth(),
height = $obj.outerHeight(),
right = left + width,
bottom = top + height;
if ((RESUtils.mouseX >= left) && (RESUtils.mouseX <= right) && (RESUtils.mouseY >= top) && (RESUtils.mouseY <= bottom)) {
return true;
} else {
return false;
}
};
RESUtils.doElementsCollide = function(ele1, ele2, margin) {
margin = margin || 0;
ele1 = $(ele1);
ele2 = $(ele2);
var dims1 = ele1.offset();
dims1.right = dims1.left + ele1.width();
dims1.bottom = dims1.top + ele1.height();
dims1.left -= margin;
dims1.top -= margin;
dims1.right += margin;
dims1.bottom += margin;
var dims2 = ele2.offset();
dims2.right = dims2.left + ele2.width();
dims2.bottom = dims2.top + ele2.height();
if (
(
(dims1.left < dims2.left && dims2.left < dims1.right) ||
(dims1.left < dims2.right && dims2.right < dims1.right) ||
(dims2.left < dims1.left && dims1.left < dims2.right) ||
(dims2.left < dims1.right && dims1.right < dims2.right)
) &&
(
(dims1.top < dims2.top && dims2.top < dims1.bottom) ||
(dims1.top < dims2.bottom && dims2.bottom < dims1.bottom) ||
(dims2.top < dims1.top && dims1.top < dims2.bottom) ||
(dims2.top < dims1.bottom && dims1.bottom < dims2.bottom))
) {
// In layman's terms:
// If one of the box's left/right borders is between the other box's left/right
// and same with top/bottom,
// then they collide.
// This could probably be logicked into a more compact form.
return true;
}
return false;
};
RESUtils.scrollToElement = function(element, options) {
options = $.extend(true, {
topOffset: 5,
makeVisible: undefined
}, options);
var target = (options.makeVisible || element).getBoundingClientRect(); // top, right, bottom, left are relative to viewport
var viewport = RESUtils.getViewportDimensions();
target = $.extend({}, target);
target.top -= viewport.yOffset;
target.bottom -= viewport.yOffset;
var top = viewport.y + target.top - options.topOffset; // for DRY
if (options.scrollStyle === 'none') {
return;
}
else if (options.scrollStyle === 'top') {
// Always scroll element to top of page
RESUtils.scrollTo(0, top);
}
else if (0 <= target.top && target.bottom <= viewport.height) {
// Element is already completely inside viewport
// (remember, top and bottom are relative to viewport)
return;
}
else if (target.top < viewport.yOffset) {
// Element starts above viewport
// So, align top of element to top of viewport
RESUtils.scrollTo(0, top);
}
else if (viewport.height < target.bottom &&
target.height < viewport.height) {
// Visible part of element starts or extends below viewport
if (options.scrollStyle === 'page') {
RESUtils.scrollTo(0, viewport.y + target.top - options.topOffset);
} else {
// So, align bottom of target to bottom of viewport
RESUtils.scrollTo(0, viewport.y + target.bottom - viewport.height);
}
return;
}
else {
// Visible part of element below the viewport but it'll fill the viewport, or fallback
// So, align top of element to top of viewport
RESUtils.scrollTo(0, top);
}
};
RESUtils.scrollTo = function(x, y) {
var headerOffset = this.getHeaderOffset();
window.scrollTo(x, y - headerOffset);
};
RESUtils.getHeaderOffset = function() {
if (typeof this.headerOffset === 'undefined') {
var header;
var headerOffset = 0;
if (modules['betteReddit'].isEnabled()) {
switch (modules['betteReddit'].options.pinHeader.value) {
case 'sub':
case 'subanduser':
header = document.getElementById('sr-header-area');
break;
case 'header':
header = document.getElementById('header');
break;
// case 'none':
default:
break;
}
}
if (header) {
headerOffset = header.offsetHeight + 6;
}
this.headerOffset = headerOffset;
}
return this.headerOffset;
};
RESUtils.addStyle = function(css) {
var style = document.createElement('style');
style.textContent = css;
RESUtils.init.await.headReady().done(function() {
document.head.appendChild(style);
});
return style;
};
RESUtils.stripHTML = function(str) {
var regExp = /<\/?[^>]+>/gi;
str = str.replace(regExp, '');
return str;
};
RESUtils.sanitizeHTML = function(htmlStr) {
return window.Pasteurizer.safeParseHTML(htmlStr).wrapAll('<div></div>').parent().html();
};
RESUtils.firstValid = function() {
return Array.prototype.slice.call(arguments).find(function(argument) {
return argument !== undefined && argument !== null &&
(typeof argument !== 'number' || !isNaN(argument));
});
};
RESUtils.fadeElementTo = function(el, speedInSeconds, finalOpacity, callback) {
var initialOpacity;
start();
function start() {
if (el._resIsFading) {
return;
} else if (finalOpacity === 0 && el.style.display === 'none') {
// already faded out, don't need to fade out again.
done();
return;
} else {
setup();
go();
}
}
function setup() {
el._resIsFading = true;
if (el.style.display === 'none' || el.style.display === '') {
initialOpacity = 0;
el.style.display = 'block';
} else {
initialOpacity = parseFloat(el.style.opacity) || 1;
}
if (typeof finalOpacity === 'undefined') {
finalOpacity = 1;
}
}
function go() {
$(el).fadeTo(speedInSeconds * 1000, finalOpacity, done);
}
function done() {
el.style.opacity = finalOpacity;
if (finalOpacity <= 0) {
el.style.display = 'none';
}
delete el._resIsFading;
if (callback && callback.call) {
callback();
}
}
return true;
};
RESUtils.fadeElementOut = function(el, speed, callback) {
RESUtils.fadeElementTo(el, speed, 0, callback);
};
RESUtils.fadeElementIn = function(el, speed, finalOpacity, callback) {
RESUtils.fadeElementTo(el, speed, finalOpacity, callback);
};
RESUtils.setCursorPosition = function(form, pos) {
var elem = $(form)[0];
if (!elem) return;
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
return form;
};
RESUtils.createMultiLock = function() {
var locks = {};
var count = 0;
return {
lock: function(lockname, value) {
if (typeof lockname === 'undefined') return;
if (locks[lockname]) return;
locks[lockname] = value || true;
count++;
return true;
},
unlock: function(lockname) {
if (typeof lockname === 'undefined') return;
if (!locks[lockname]) return;
locks[lockname] = false;
count--;
return true;
},
locked: function(lockname) {
if (typeof lockname !== 'undefined') {
// Is this lock set?
return locks[lockname];
} else {
// Is any lock set?
return count > 0;
}
}
};
};
RESUtils.indexOptionTable = function(moduleID, optionKey, keyFieldIndex) {
var source = modules[moduleID].options[optionKey].value;
var keyIsList =
modules[moduleID].options[optionKey].fields[keyFieldIndex].type === 'list' ?
',' :
false;
return RESUtils.indexArrayByProperty(source, keyFieldIndex, keyIsList);
};
RESUtils.indexArrayByProperty = function(source, keyIndex, keyValueSeparator) {
var index;
if (!source || !source.length) {
index = {
items: [],
keys: []
};
} else {
index = createIndex();
}
Object.defineProperty(getItem, 'keys', {
value: index.keys,
writeable: false
});
Object.defineProperty(getItem, 'all', {
value: getAllItems,
writeable: false
});
return getItem;
function createIndex() {
var itemsByKey = {};
var allKeys = [];
for (var i = 0, length = source.length; i < length; i++) {
var item = source[i];
var key = item && item[keyIndex];
if (!key) continue;
var keys;
if (keyValueSeparator) {
keys = key.split(keyValueSeparator);
} else {
keys = [ key && key ];
}
for (var ki = 0, klength = keys.length; ki < klength; ki++) {
key = keys[ki].toLowerCase();
itemsByKey[key] = itemsByKey[key] || [];
itemsByKey[key].push(item);
}
allKeys = allKeys.concat(keys);
}
allKeys = allKeys.filter(function(value, index, array) {
var unique = array.indexOf(value, index + 1) === -1;
return unique;
});
return {
items: itemsByKey,
keys: allKeys
};
}
function getItem(key) {
key = key && key.toLowerCase();
var item = index.items[key];
return item;
}
function getAllItems() {
return index.keys.map(getItem);
}
};
RESUtils.inList = function(needle, haystack, separator, isCaseSensitive) {
if (!needle || !haystack) return false;
separator = separator || ',';
if (haystack.indexOf(separator) !== -1) {
var haystacks = haystack.split(separator);
if (RESUtils.inArray(needle, haystacks, isCaseSensitive)) {
return true;
}
} else {
if (isCaseSensitive) {
return (needle === haystack);
} else {
return (needle.toLowerCase() === haystack.toLowerCase());
}
}
};
RESUtils.inArray = function(needle, haystacks, isCaseSensitive) {
if (!isCaseSensitive) needle = needle.toLowerCase();
for (var i = 0, length = haystacks.length; i < length; i++) {
if (isCaseSensitive) {
if (needle === haystacks[i]) {
return true;
}
} else {
if (needle === haystacks[i].toLowerCase()) {
return true;
}
}
}
};
RESUtils.deferred = RESUtils.deferred || {};
RESUtils.deferred.map = function(array, callback) {
var deferreds,
mapped = [];
deferreds = [].concat(array).map(function(item, index, array) {
var def = callback(item, index, array)
.done(function(mappedItem) {
mapped[index] = mappedItem;
});
return def;
});
return RESUtils.deferred.all(deferreds)
.then(function() { return mapped; })
.promise();
};
RESUtils.deferred.all = function(deferreds) {
var deferred = $.Deferred(),
doneCount = 0,
failCount = 0;
deferreds = [].concat(deferreds);
deferreds.forEach(function(def) {
def
.done(done)
.fail(fail)
.always(always);
});
function done() {
doneCount++;
}
function fail() {
failCount++;
}
function always() {
if ((doneCount + failCount) < deferreds.length) {
return;
}
if (failCount > 0 && doneCount === 0) {
deferred.reject(doneCount, failCount);
} else {
deferred.resolve(doneCount, failCount);
}
}
return deferred.promise();
};
RESUtils.rpc = function(moduleID, method, args) {
if (args && args[args.length - 1] === 'rpc') {
console.warn('rpc warning: loop.', moduleID, method, args);
return 'rpc loop suspected';
}
var module = modules[moduleID];
if (!module || typeof module[method] !== 'function') {
console.warn('rpc error: could not find method.', moduleID, method, args);
return 'could not find method';
}
var sanitized = args ?
[].concat(JSON.parse(JSON.stringify(args))) :
[];
sanitized = sanitized.concat('rpc');
return module[method].apply(method, sanitized);
};
RESUtils.proEnabled = function() {
return ((typeof modules['RESPro'] !== 'undefined') && (modules['RESPro'].isEnabled()));
};
RESUtils.niceKeyCode = function(charCode) {
var keyComboString = '';
var testCode, niceString;
if (typeof charCode === 'string') {
var tempArray = charCode.split(',');
if (tempArray.length) {
if (tempArray[1] === 'true') keyComboString += 'alt-';
if (tempArray[2] === 'true') keyComboString += 'ctrl-';
if (tempArray[3] === 'true') keyComboString += 'shift-';
if (tempArray[4] === 'true') keyComboString += 'command-';
}
testCode = parseInt(charCode, 10);
} else if (typeof charCode === 'object') {
testCode = parseInt(charCode[0], 10);
if (charCode[1]) keyComboString += 'alt-';
if (charCode[2]) keyComboString += 'ctrl-';
if (charCode[3]) keyComboString += 'shift-';
if (charCode[4]) keyComboString += 'command-';
}
switch (testCode) {
case -1:
niceString = 'none'; // none
break;
case 8:
niceString = 'backspace'; // backspace
break;
case 9:
niceString = 'tab'; // tab
break;
case 13:
niceString = 'enter'; // enter
break;
case 16:
niceString = 'shift'; // shift
break;
case 17:
niceString = 'ctrl'; // ctrl
break;
case 18:
niceString = 'alt'; // alt
break;
case 19:
niceString = 'pause/break'; // pause/break
break;
case 20:
niceString = 'caps lock'; // caps lock
break;
case 27:
niceString = 'escape'; // escape
break;
case 33:
niceString = 'page up'; // page up, to avoid displaying alternate character and confusing people
break;
case 34:
niceString = 'page down'; // page down
break;
case 35:
niceString = 'end'; // end
break;
case 36:
niceString = 'home'; // home
break;
case 37:
niceString = 'left arrow'; // left arrow
break;
case 38:
niceString = 'up arrow'; // up arrow
break;
case 39:
niceString = 'right arrow'; // right arrow
break;
case 40:
niceString = 'down arrow'; // down arrow
break;
case 45:
niceString = 'insert'; // insert
break;
case 46:
niceString = 'delete'; // delete
break;
case 91:
niceString = 'left window'; // left window
break;
case 92:
niceString = 'right window'; // right window
break;
case 93:
niceString = 'select key'; // select key
break;
case 96:
niceString = 'numpad 0'; // numpad 0
break;
case 97:
niceString = 'numpad 1'; // numpad 1
break;
case 98:
niceString = 'numpad 2'; // numpad 2
break;
case 99:
niceString = 'numpad 3'; // numpad 3
break;
case 100:
niceString = 'numpad 4'; // numpad 4
break;
case 101:
niceString = 'numpad 5'; // numpad 5
break;
case 102:
niceString = 'numpad 6'; // numpad 6
break;
case 103:
niceString = 'numpad 7'; // numpad 7
break;
case 104:
niceString = 'numpad 8'; // numpad 8
break;
case 105:
niceString = 'numpad 9'; // numpad 9
break;
case 106:
niceString = 'multiply'; // multiply
break;
case 107:
niceString = 'add'; // add
break;
case 109:
niceString = 'subtract'; // subtract
break;
case 110:
niceString = 'decimal point'; // decimal point
break;
case 111:
niceString = 'divide'; // divide
break;
case 112:
niceString = 'F1'; // F1
break;
case 113:
niceString = 'F2'; // F2
break;
case 114:
niceString = 'F3'; // F3
break;
case 115:
niceString = 'F4'; // F4
break;
case 116:
niceString = 'F5'; // F5
break;
case 117:
niceString = 'F6'; // F6
break;
case 118:
niceString = 'F7'; // F7
break;
case 119:
niceString = 'F8'; // F8
break;
case 120:
niceString = 'F9'; // F9
break;
case 121:
niceString = 'F10'; // F10
break;
case 122:
niceString = 'F11'; // F11
break;
case 123:
niceString = 'F12'; // F12
break;
case 144:
niceString = 'num lock'; // num lock
break;
case 145:
niceString = 'scroll lock'; // scroll lock
break;
case 186:
niceString = ';'; // semi-colon
break;
case 187:
niceString = '='; // equal-sign
break;
case 188:
niceString = ','; // comma
break;
case 189:
niceString = '-'; // dash
break;
case 190:
niceString = '.'; // period
break;
case 191:
niceString = '/'; // forward slash
break;
case 192:
niceString = '`'; // grave accent
break;
case 219:
niceString = '['; // open bracket
break;
case 220:
niceString = '\\'; // back slash
break;
case 221:
niceString = ']'; // close bracket
break;
case 222:
niceString = '\''; // single quote
break;
default:
niceString = String.fromCharCode(testCode);
break;
}
return keyComboString + niceString;
};
RESUtils.niceDate = function(d, usformat) {
d = d || new Date();
var year = d.getFullYear();
var month = (d.getMonth() + 1);
month = (month < 10) ? '0' + month : month;
var day = d.getDate();
day = (day < 10) ? '0' + day : day;
var fullString = year + '-' + month + '-' + day;
if (usformat) {
fullString = month + '-' + day + '-' + year;
}
return fullString;
};
RESUtils.niceDateTime = function(d, usformat) {
d = d || new Date();
var dateString = RESUtils.niceDate(d, usformat);
var hours = d.getHours();
hours = (hours < 10) ? '0' + hours : hours;
var minutes = d.getMinutes();
minutes = (minutes < 10) ? '0' + minutes : minutes;
var seconds = d.getSeconds();
seconds = (seconds < 10) ? '0' + seconds : seconds;
var fullString = dateString + ' ' + hours + ':' + minutes + ':' + seconds;
return fullString;
};
RESUtils.niceDateDiff = function(origdate, newdate) {
// Enter the month, day, and year below you want to use as
// the starting point for the date calculation
if (!newdate) {
newdate = new Date();
}
var amonth = origdate.getUTCMonth() + 1;
var aday = origdate.getUTCDate();
var ayear = origdate.getUTCFullYear();
var tmonth = newdate.getUTCMonth() + 1;
var tday = newdate.getUTCDate();
var tyear = newdate.getUTCFullYear();
var y = 1;
var mm = 1;
var d = 1;
var a2 = 0;
var a1 = 0;
var f = 28;
if (((tyear % 4 === 0) && (tyear % 100 !== 0)) || (tyear % 400 === 0)) {
f = 29;
}
var m = [31, f, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dyear = tyear - ayear;
var dmonth = tmonth - amonth;
if (dmonth < 0 && dyear > 0) {
dmonth = dmonth + 12;
dyear--;
}
var dday = tday - aday;
if (dday < 0) {
if (dmonth > 0) {
var ma = tmonth - 1;
// Retrive total number of days in month before tmonth
// Can think of diff as (dmonth-1) months, and
// (daysIn(tmonth-1) + tday - aday) days
dday = dday + m[ma - 1];
// Months are 0 indexed in array m but 1 indexed for
// amonth and tmonth. This compensates for that
dmonth--;
if (dmonth < 0) {
dyear--;
dmonth = dmonth + 12;
}
} else {
dday = 0;
}
}
var returnString = '';
if (dyear === 0) {
y = 0;
}
if (dmonth === 0) {
mm = 0;
}
if (dday === 0) {
d = 0;
}
if ((y === 1) && (mm === 1)) {
a1 = 1;
}
if ((y === 1) && (d === 1)) {
a1 = 1;
}
if ((mm === 1) && (d === 1)) {
a2 = 1;
}
if (y === 1) {
if (dyear === 1) {
returnString += dyear + ' year';
} else {
returnString += dyear + ' years';
}
}
if ((a1 === 1) && (a2 === 0)) {
returnString += ' and ';
}
if ((a1 === 1) && (a2 === 1)) {
returnString += ', ';
}
if (mm === 1) {
if (dmonth === 1) {
returnString += dmonth + ' month';
} else {
returnString += dmonth + ' months';
}
}
if (a2 === 1) {
returnString += ' and ';
}
if (d === 1) {
if (dday === 1) {
returnString += dday + ' day';
} else {
returnString += dday + ' days';
}
}
if (returnString === '') {
returnString = '0 days';
}
return returnString;
};
RESUtils.isEmpty = function(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
return false;
}
return true;
};
RESUtils.openLinkInNewTab = function(url, focus) {
var thisJSON = {
requestType: 'openLinkInNewTab',
linkURL: url,
button: focus
};
RESUtils.runtime.sendMessage(thisJSON);
};
RESUtils.createElement = function(elementType, id, classname, textContent) {
var obj = document.createElement(elementType);
if (id) {
obj.setAttribute('id', id);
}
if ((typeof classname !== 'undefined') && classname && (classname !== '')) {
obj.setAttribute('class', classname);
}
if (textContent) {
if (classname && classname.split(' ').indexOf('noCtrlF') !== -1) {
obj.setAttribute('data-text', textContent);
} else {
obj.textContent = textContent;
}
}
return obj;
};
RESUtils.createElementWithID = RESUtils.createElement; // legacy alias
RESUtils.createElement.toggleButton = function(moduleID, fieldID, enabled, onText, offText, isTable) {
var checked, thisToggle,
toggleOn, toggleOff, field;
enabled = enabled || false;
checked = (enabled) ? 'CHECKED' : '';
onText = onText || 'on';
offText = offText || 'off';
thisToggle = document.createElement('div');
thisToggle.setAttribute('class', 'toggleButton');
thisToggle.setAttribute('id', fieldID + 'Container');
toggleOn = RESUtils.createElement('span', null, 'toggleOn noCtrlF', onText);
toggleOff = RESUtils.createElement('span', null, 'toggleOff noCtrlF', offText);
field = RESUtils.createElement('input', fieldID);
field.name = fieldID;
field.type = 'checkbox';
if (enabled) {
field.checked = true;
}
if (isTable) {
field.setAttribute('tableOption', 'true');
}
thisToggle.appendChild(toggleOn);
thisToggle.appendChild(toggleOff);
thisToggle.appendChild(field);
thisToggle.addEventListener('click', function(e) {
var thisCheckbox = this.querySelector('input[type=checkbox]'),
enabled = thisCheckbox.checked;
thisCheckbox.checked = !enabled;
if (enabled) {
this.classList.remove('enabled');
} else {
this.classList.add('enabled');
}
if (moduleID) {
modules['settingsConsole'].onOptionChange(moduleID, fieldID, enabled, !enabled);
}
}, false);
if (enabled) thisToggle.classList.add('enabled');
return thisToggle;
};
RESUtils.createElement.commaDelimitedNumber = function(nStr) {
nStr = typeof nStr === 'string' ? nStr.replace(/[^\w]/, '') : nStr;
var locale = document.querySelector('html').getAttribute('lang') || 'en';
return Number(nStr).toLocaleString(locale);
};
RESUtils.createElement.table = function(items, call, context) {
if (!items || !call) return;
// Sanitize single item into items array
if (!(items.length && typeof items !== 'string')) items = [items];
var description = [];
description.push('<table>');
for (var i = 0; i < items.length; i++) {
var item = call(items[i], i, items, context);
if (typeof item === 'string') {
description.push(item);
} else if (item.length) {
description = description.concat(item);
}
}
description.push('</table>');
description = description.join('\n');
return description;
};
RESUtils.xhrCache = function(operation) {
var thisJSON = {
requestType: 'XHRCache',
operation: operation
};
RESUtils.runtime.sendMessage(thisJSON);
};
RESUtils.initObservers = function() {
var siteTable, observer;
if (RESUtils.pageType() !== 'comments') {
// initialize sitetable observer...
siteTable = RESUtils.thingsContainer();
if (BrowserDetect.MutationObserver && siteTable) {
observer = new BrowserDetect.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if ($(mutation.addedNodes[0]).is(RESUtils.thing.prototype.containerSelector)) {
// when a new sitetable is loaded, we need to add new observers for selftexts within that sitetable...
$(mutation.addedNodes[0]).find('.entry div.expando').each(function() {
RESUtils.addSelfTextObserver(this);
});
RESUtils.watchers.siteTable.forEach(function(callback) {
if (callback) callback(mutation.addedNodes[0]);
});
}
});
});
observer.observe(siteTable, {
attributes: false,
childList: true,
characterData: false
});
} else {
// Opera doesn't support MutationObserver - so we need this for Opera support.
if (siteTable) {
siteTable.addEventListener('DOMNodeInserted', function(event) {
if ($(event.target).is(RESUtils.thing.prototype.containerSelector)) {
RESUtils.watchers.siteTable.forEach(function(callback) {
if (callback) callback(event.target);
});
}
}, true);
}
}
} else {
// initialize sitetable observer...
siteTable = document.querySelector('.commentarea > .sitetable');
if (!siteTable) {
siteTable = document.querySelector('.sitetable');
}
if (BrowserDetect.MutationObserver && siteTable) {
observer = new BrowserDetect.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// handle comment listing pages (not within a post)
var $container = $(mutation.addedNodes[0]);
if ($container.is('[id^="siteTable"]')) {
// when a new sitetable is loaded, we need to add new observers for selftexts within that sitetable...
$container.find('.entry div.expando').each(function() {
RESUtils.addSelfTextObserver(this);
});
RESUtils.watchers.siteTable.forEach(function(callback) {
if (callback) callback(mutation.addedNodes[0]);
});
}
if (mutation.addedNodes.length > 0 && mutation.addedNodes[0].classList.contains('thing')) {
var thing = mutation.addedNodes[0];
var newCommentEntry = thing.querySelector('.entry');
if (!$(newCommentEntry).data('alreadyDetected')) {
$(newCommentEntry).data('alreadyDetected', true);
$(thing).find('.child').each(function() {
RESUtils.addNewCommentFormObserver(this);
});
RESUtils.watchers.newComments.forEach(function(callback) {
if (callback) callback(newCommentEntry);
});
}
}
});
});
observer.observe(siteTable, {
attributes: false,
childList: true,
characterData: false
});
} else {
// Opera doesn't support MutationObserver - so we need this for Opera support.
if (siteTable) {
siteTable.addEventListener('DOMNodeInserted', RESUtils.mutationEventCommentHandler, false);
}
}
}
$('.entry div.expando').each(function() {
RESUtils.addSelfTextObserver(this);
});
// initialize new comments observers on demand, by first wiring up click listeners to "load more comments" buttons.
// on click, we'll add a mutation observer...
$('.morecomments a').on('click', RESUtils.addNewCommentObserverToTarget);
// initialize new comments forms observers on demand, by first wiring up click listeners to reply buttons.
// on click, we'll add a mutation observer...
// $('body').on('click', 'ul.flat-list li a[onclick*=reply]', RESUtils.addNewCommentFormObserver);
$('.thing .child').each(function() {
RESUtils.addNewCommentFormObserver(this);
});
};
// Opera doesn't support MutationObserver - so we need this for Opera support.
RESUtils.mutationEventCommentHandler = function(event) {
if ((event.target.tagName === 'DIV') && (event.target.classList.contains('thing'))) {
// we've found a matching element - stop propagation.
event.stopPropagation();
// because nested DOMNodeInserted events are an absolute CLUSTER to manage,
// only send individual comments through to the callback.
// Otherwise, we end up calling functions on a parent, then its child (which
// already got scanned when we passed in the parent), etc.
var thisComment = event.target.querySelector('.entry');
if (!$(thisComment).data('alreadyDetected')) {
$(thisComment).data('alreadyDetected', true);
// wire up listeners for new "more comments" links...
$(event.target).find('.morecomments a').click(RESUtils.addNewCommentObserverToTarget);
RESUtils.watchers.newComments.forEach(function(callback) {
RESUtils.addNewCommentFormObserver(event.target);
if (callback) callback(thisComment);
});
}
}
};
RESUtils.addNewCommentObserverToTarget = function(e) {
var ele = $(e.currentTarget).closest('.sitetable')[0];
// mark this as having an observer so we don't add multiples...
if (!$(ele).hasClass('hasObserver')) {
$(ele).addClass('hasObserver');
RESUtils.addNewCommentObserver(ele);
}
};
RESUtils.addNewCommentObserver = function(ele) {
var mutationNodeToObserve = ele;
if (BrowserDetect.MutationObserver) {
var observer = new BrowserDetect.MutationObserver(function(mutations) {
// we need to get ONLY the nodes that are new...
// get the nodeList from each mutation, find comments within it,
// then call our callback on it.
for (var i = 0, len = mutations.length; i < len; i++) {
var thisMutation = mutations[i];
var nodeList = thisMutation.addedNodes;
// look at the added nodes, and find comment containers.
for (var j = 0, jLen = nodeList.length; j < jLen; j++) {
if (nodeList[j].classList.contains('thing')) {
$(nodeList[j]).find('.child').each(function() {
RESUtils.addNewCommentFormObserver(this);
});
// check for "load new comments" links within this group as well...
$(nodeList[j]).find('.morecomments a').click(RESUtils.addNewCommentObserverToTarget);
var subComments = nodeList[j].querySelectorAll('.entry');
// look at the comment containers and find actual comments...
for (var k = 0, kLen = subComments.length; k < kLen; k++) {
var thisComment = subComments[k];
if (!$(thisComment).data('alreadyDetected')) {
$(thisComment).data('alreadyDetected', true);
RESUtils.watchers.newComments.forEach(function(callback) {
if (callback) callback(thisComment);
});
}
}
}
}
}
// RESUtils.watchers.newComments.forEach(function(callback) {
// // add form observers to these new comments we've found...
// $(mutations[0].target).find('.thing .child').each(function() {
// RESUtils.addNewCommentFormObserver(this);
// });
// // check for "load new comments" links within this group as well...
// $(mutations[0].target).find('.morecomments a').click(RESUtils.addNewCommentObserverToTarget);
// callback(mutations[0].target);
// });
// disconnect this observer once all callbacks have been run.
// unless we have the nestedlisting class, in which case don't disconnect because that's a
// bottom level load more comments where even more can be loaded after, so they all drop into this
// same .sitetable div.
if (!$(ele).hasClass('nestedlisting')) {
observer.disconnect();
}
});
observer.observe(mutationNodeToObserve, {
attributes: false,
childList: true,
characterData: false
});
} else {
mutationNodeToObserve.addEventListener('DOMNodeInserted', RESUtils.mutationEventCommentHandler, false);
}
};
RESUtils.addNewCommentFormObserver = function(ele) {
var commentsFormParent = ele;
if (BrowserDetect.MutationObserver) {
// var mutationNodeToObserve = moreCommentsParent.parentNode.parentNode.parentNode.parentNode;
var observer = new BrowserDetect.MutationObserver(function(mutations) {
var form = $(mutations[0].target).children('form');
if ((form) && (form.length === 1)) {
RESUtils.watchers.newCommentsForms.forEach(function(callback) {
callback(form[0]);
});
} else {
var newOwnComment = $(mutations[0].target).find(' > div.sitetable > .thing:first-child'); // assumes new comment will be prepended to sitetable's children
if ((newOwnComment) && (newOwnComment.length === 1)) {
// new comment detected from the current user...
RESUtils.watchers.newComments.forEach(function(callback) {
callback(newOwnComment[0]);
});
}
}
});
observer.observe(commentsFormParent, {
attributes: false,
childList: true,
characterData: false
});
} else {
// Opera doesn't support MutationObserver - so we need this for Opera support.
commentsFormParent.addEventListener('DOMNodeInserted', function(event) {
// TODO: proper tag filtering here, it's currently all wrong.
if (event.target.tagName === 'FORM') {
RESUtils.watchers.newCommentsForms.forEach(function(callback) {
if (callback) callback(event.target);
});
} else {
var newOwnComment = $(event.target).find(' > div.sitetable > .thing:first-child'); // assumes new comment will be prepended to sitetable's children
if ((newOwnComment) && (newOwnComment.length === 1)) {
// new comment detected from the current user...
RESUtils.watchers.newComments.forEach(function(callback) {
callback(newOwnComment[0]);
});
}
}
}, true);
}
};
RESUtils.addSelfTextObserver = function(ele) {
var selfTextParent = ele;
if (BrowserDetect.MutationObserver) {
// var mutationNodeToObserve = moreCommentsParent.parentNode.parentNode.parentNode.parentNode;
var observer = new BrowserDetect.MutationObserver(function(mutations) {
var form = $(mutations[0].target).find('form');
if ((form) && (form.length > 0)) {
RESUtils.watchers.selfText.forEach(function(callback) {
callback(form[0]);
});
}
});
observer.observe(selfTextParent, {
attributes: false,
childList: true,
characterData: false
});
} else {
// Opera doesn't support MutationObserver - so we need this for Opera support.
selfTextParent.addEventListener('DOMNodeInserted', function(event) {
// TODO: proper tag filtering here, it's currently all wrong.
if (event.target.tagName === 'FORM') {
RESUtils.watchers.selfText.forEach(function(callback) {
if (callback) callback(event.target);
});
}
}, true);
}
};
RESUtils.watchForElement = function(type, callback) {
switch (type) {
case 'siteTable':
RESUtils.watchers.siteTable.push(callback);
break;
case 'newComments':
RESUtils.watchers.newComments.push(callback);
break;
case 'selfText':
RESUtils.watchers.selfText.push(callback);
break;
case 'newCommentsForms':
RESUtils.watchers.newCommentsForms.push(callback);
break;
}
};
RESUtils.watchers = {
siteTable: [],
newComments: [],
selfText: [],
newCommentsForms: []
};
// A link is a comment code if all these conditions are true:
// * It has no content (i.e. content.length === 0)
// * Its href is of the form "/code" or "#code"
//
// In case it's not clear, here is a list of some common comment
// codes on a specific subreddit:
// http://www.reddit.com/r/metarage/comments/p3eqe/full_updated_list_of_comment_faces_wcodes/
// also for CSS hacks to do special formatting, like /r/CSSlibrary
RESUtils.COMMENT_CODE_REGEX = /^[\/#].+$/;
RESUtils.isCommentCode = function(link) {
// don't add annotations for hidden links - these are used as CSS
// hacks on subreddits to do special formatting, etc.
// Note that link.href will return the full href (which includes the
// reddit.com domain). We don't want that.
var href = link.getAttribute('href');
var emptyText = link.textContent.length === 0;
var isCommentCode = RESUtils.COMMENT_CODE_REGEX.test(href);
return emptyText && isCommentCode;
};
RESUtils.isEmptyLink = function(link) {
/* jshint -W107 */
// Note that link.href will return the full href (which includes the
// reddit.com domain). We don't want that.
var href = link.getAttribute('href');
return typeof href !== 'string' || href.substring(0, 11) === 'javascript:';
};
/*
Starts a unique named timeout.
If there is a running timeout with the same name cancel the old one in favor of the new.
Call with no time/call parameter (null/undefined/missing) to and existing one with the given name.
Used to derfer an action until a series of events has stopped.
e.g. wait until a user a stopped typing to update a comment preview.
(name based on similar function in underscore.js)
*/
RESUtils.debounceTimeouts = {};
RESUtils.debounce = function(name, time, call, data) {
if (name === null) return;
if (RESUtils.debounceTimeouts[name] !== undefined) {
window.clearTimeout(RESUtils.debounceTimeouts[name]);
delete RESUtils.debounceTimeouts[name];
}
if (typeof time === 'number' && typeof call === 'function') {
RESUtils.debounceTimeouts[name] = window.setTimeout(function() {
delete RESUtils.debounceTimeouts[name];
call(data);
}, time);
}
};
RESUtils.toolTipTimers = {};
/*
Iterate through an array in chunks, executing a callback on each element.
Each chunk is handled asynchronously from the others with a delay betwen each batch.
If the provided callback returns false iteration will be halted.
*/
RESUtils.forEachChunked = function(array, chunkSize, delay, call) {
if (typeof array === 'undefined' || array === null) return;
if (typeof chunkSize === 'undefined' || chunkSize === null || chunkSize < 1) return;
if (typeof delay === 'undefined' || delay === null || delay < 0) return;
if (typeof call === 'undefined' || call === null) return;
var counter = 0,
length = array.length;
function doChunk() {
for (var end = Math.min(length, counter + chunkSize); counter < end; counter++) {
var ret = call(array[counter], counter, array);
if (ret === false) return;
}
if (counter < length) {
window.setTimeout(doChunk, delay);
}
}
window.setTimeout(doChunk, delay);
};
RESUtils.getComputedStyle = function(elem, property) {
if (elem.constructor === String) {
elem = document.querySelector(elem);
} else if (!(elem instanceof Node)) {
return undefined;
}
var strValue;
if (document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(elem, '').getPropertyValue(property);
} else if (elem.currentStyle) {
property = property.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
strValue = elem.currentStyle[property];
}
return strValue;
};
// utility function for checking events against keyCode arrays
RESUtils.checkKeysForEvent = function(event, keyArray) {
//[keycode, alt, ctrl, shift, meta]
// if we've passed in a number, fix that and make it an array with alt, shift and ctrl set to false.
if (typeof keyArray === 'number') {
keyArray = [keyArray, false, false, false, false];
} else if (keyArray.length === 4) {
keyArray.push(false);
}
var eventHash = RESUtils.hashKeyEvent(event);
var arrayHash = RESUtils.hashKeyArray(keyArray);
var matches = (eventHash === arrayHash);
return matches;
};
RESUtils.hashKeyEvent = function(event) {
var keyArray = [ event.keyCode, event.altKey, event.ctrlKey, event.shiftKey, event.metaKey ];
// this hack is because Firefox differs from other browsers with keycodes for - and =
if (BrowserDetect.isFirefox()) {
if (keyArray[0] === 173) {
keyArray[0] = 189;
}
if (keyArray[0] === 61) {
keyArray[0] = 187;
}
}
return RESUtils.hashKeyArray(keyArray);
};
RESUtils.hashKeyArray = function(keyArray) {
var length = 5;
var hash = keyArray[0] * Math.pow(2, length);
for (var i = 1; i < length; i++) {
if (keyArray[i]) {
hash = hash + Math.pow(2, i);
}
}
return hash;
};
// Retrieves either a live or cached copy of some data from reddit's api, i.e.
// RESUtils.cache.fetch({
// key: 'RESmodules.module.subs.username', // optional, necessary to distinguish between users if the endpoint doesn't
// endpoint: 'subreddits/mine/moderator.json?limit=100',
// expires: 0, // optional: default 30000 (5 minutes)
// handleData: function(response, expiredData) { return response.data.children; }, // optional: default `return response;`
// callback: function(data) { RESUtils.someFunction(data); }
// });
(function() {
RESUtils.cache = RESUtils.cache || {};
function makeCacheKey(obj) {
var key;
if (typeof obj.key === 'string') {
key = obj.key;
} else if (typeof obj.endpoint === 'string') {
key = 'RESUtils.cache.' + obj.endpoint.replace(/[^\w\-]/g, '-');
} else {
console.error('makeCacheKey: no key or endpoint specified.');
}
return key;
}
var fetching = {};
RESUtils.cache.fetch = function (obj) {
var deferred;
if (typeof obj.callback !== 'function') {
console.error('RESUtils.cache.fetch: no callback given');
return;
}
if (typeof obj.endpoint !== 'string') {
console.error('RESUtils.cache.fetch: no endpoint given');
return;
}
obj.key = makeCacheKey(obj);
obj.expires = (typeof obj.expires === 'number') ? obj.expires : 300000;
obj.handleData = (typeof obj.handleData === 'function') ? obj.handleData : function(data) { return data; };
var cache = safeJSON.parse(RESStorage.getItem(obj.key), obj.key, true) || {},
lastCheck = (cache !== null) ? parseInt(cache.lastCheck, 10) || 0 : 0,
now = Date.now();
if ((now - lastCheck) > obj.expires || lastCheck > now) {
if (fetching[obj.key]) {
deferred = fetching[obj.key];
} else {
deferred = fetching[obj.key] = $.Deferred();
RESUtils.runtime.ajax({
method: 'GET',
url: location.protocol + '//' + location.hostname + '/' + obj.endpoint,
data: 'app=res',
onload: function (response) {
var data;
try {
data = JSON.parse(response.responseText);
} catch (e) {
console.error('RESUtils.cache.fetch: Error parsing response from ' + this.url);
console.log(response.responseText);
delete fetching[obj.key];
return false;
}
var handled = obj.handleData(data, cache && cache.data);
cache.data = (typeof handled !== 'undefined') ? handled : data;
cache.lastCheck = now;
RESStorage.setItem(obj.key, JSON.stringify(cache));
deferred.resolve(cache.data);
}
});
}
} else {
deferred = $.Deferred().resolve(cache.data);
}
if (obj.callback) {
deferred.done(obj.callback);
}
return deferred.promise();
};
RESUtils.cache.expire = function (obj) {
var key = makeCacheKey(obj);
if (key) {
var existingCache = RESStorage.getItem(key) || {},
cache = {
data: existingCache.data,
lastCheck: 0
};
RESStorage.setItem(key, JSON.stringify(cache));
}
};
})();
RESUtils.insertAfter = function(referenceNode, newNode) {
if ((typeof referenceNode === 'undefined') || (referenceNode === null)) {
console.error('Could not insert node after undefined node from', arguments.callee.caller, newNode);
} else if ((typeof referenceNode.parentNode !== 'undefined') && (typeof referenceNode.nextSibling !== 'undefined')) {
if (referenceNode.parentNode === null) {
console.error('Could not insert node after parentless node from', arguments.callee.caller, newNode);
} else {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
}
};
RESUtils.cssPrefix = function(css) {
return '-webkit-' + css + ';' + '-o-' + css + ';' + '-moz-' + css + ';' +
'-ms-' + css + ';' + css + ';';
};
RESUtils.baseStyleProtection = 'margin: 0 !important; background-color: inherit !important; color: inherit !important; position: relative !important; left: 0 !important; top: 0 !important; max-height: none!important; max-width: none!important; height: auto !important; width: auto !important; visibility: visible !important; overflow: auto !important; text-indent: 0 !important; font-size: 12px !important; float: none !important; opacity: 1 !important;' + RESUtils.cssPrefix('transform: none !important;') + RESUtils.cssPrefix('filter: none !important;');
| gpl-3.0 |
ryandoherty/RaceCapture_App | autosportlabs/comms/comms.py | 5447 | import traceback
import threading
import multiprocessing
from Queue import Empty
from time import sleep
from kivy.logger import Logger
from autosportlabs.comms.commscommon import PortNotOpenException
STAY_ALIVE_TIMEOUT = 4
COMMAND_CLOSE = 'CLOSE'
COMMAND_KEEP_ALIVE = 'PING'
def connection_process_message_reader(rx_queue, connection, should_run):
Logger.debug('Comms: connection process message reader started')
while should_run.is_set():
try:
msg = connection.read_line()
if msg:
rx_queue.put(msg)
except:
Logger.error('Comms: Exception in connection_process_message_reader')
Logger.debug(traceback.format_exc())
should_run.clear()
sleep(0.5)
Logger.debug('Comms: connection process message reader exited')
def connection_process_message_writer(tx_queue, connection, should_run):
Logger.debug('Comms: connection process message writer started')
while should_run.is_set():
try:
message = tx_queue.get(True, 1.0)
if message:
connection.write(message)
except Empty:
pass
except Exception as e:
Logger.error('Comms: Exception in connection_process_message_writer ' + str(e))
Logger.debug(traceback.format_exc())
should_run.clear()
sleep(0.5)
Logger.debug('Comms: connection process message writer exited')
def connection_message_process(connection, device, rx_queue, tx_queue, command_queue):
Logger.debug('Comms: connection process starting')
try:
connection.open(device)
connection.flushInput()
connection.flushOutput()
reader_writer_should_run = threading.Event()
reader_writer_should_run.set()
reader_thread = threading.Thread(target=connection_process_message_reader, args=(rx_queue, connection, reader_writer_should_run))
reader_thread.start()
writer_thread = threading.Thread(target=connection_process_message_writer, args=(tx_queue, connection, reader_writer_should_run))
writer_thread.start()
while reader_writer_should_run.is_set():
try:
command = command_queue.get(True, STAY_ALIVE_TIMEOUT)
if command == COMMAND_CLOSE:
Logger.debug('Comms: connection process: got close command')
reader_writer_should_run.clear()
except Empty:
Logger.info('Comms: keep alive timeout')
reader_writer_should_run.clear()
Logger.debug('Comms: connection worker exiting')
reader_thread.join()
writer_thread.join()
try:
connection.close()
except:
Logger.error('Comms: Exception closing connection worker connection')
except Exception as e:
Logger.error('Comms: Exception setting up connection process: ' + str(type(e)) + str(e))
Logger.debug(traceback.format_exc())
Logger.debug('Comms: connection worker exited')
class Comms():
CONNECT_TIMEOUT = 1.0
DEFAULT_TIMEOUT = 1.0
QUEUE_FULL_TIMEOUT = 1.0
_timeout = DEFAULT_TIMEOUT
device = None
_connection = None
_connection_process = None
_rx_queue = None
_tx_queue = None
_command_queue = None
def __init__(self, device, connection):
self.device = device
self._connection = connection
self.supports_streaming = False
def start_connection_process(self):
rx_queue = multiprocessing.Queue()
tx_queue = multiprocessing.Queue(5)
command_queue = multiprocessing.Queue()
connection_process = multiprocessing.Process(target=connection_message_process, args=(self._connection, self.device, rx_queue, tx_queue, command_queue))
connection_process.start()
self._rx_queue = rx_queue
self._tx_queue = tx_queue
self._command_queue = command_queue
self._connection_process = connection_process
def get_available_devices(self):
return self._connection.get_available_devices()
def isOpen(self):
return self._connection_process != None and self._connection_process.is_alive()
def open(self):
connection = self._connection
Logger.info('Comms: Opening connection ' + str(self.device))
self.start_connection_process()
def keep_alive(self):
try:
self._command_queue.put_nowait(COMMAND_KEEP_ALIVE)
except:
pass
def close(self):
Logger.debug('Comms: comms.close()')
if self.isOpen():
try:
Logger.debug('Comms: closing connection process')
self._command_queue.put_nowait(COMMAND_CLOSE)
self._connection_process.join(self._timeout * 2)
Logger.debug('Comms: connection process joined')
except:
Logger.error('Comms: Timeout joining connection process')
def read_message(self):
if not self.isOpen():
raise PortNotOpenException('Port Closed')
try:
return self._rx_queue.get(True, self._timeout)
except: # returns Empty object if timeout is hit
return None
def write_message(self, message):
if not self.isOpen(): raise PortNotOpenException('Port Closed')
self._tx_queue.put(message, True, Comms.QUEUE_FULL_TIMEOUT)
| gpl-3.0 |
bregma/ginn | ginn/xmlwishsource.cpp | 11782 | /**
* @file ginn/xmlwishsource.cpp
* @brief Definitions of the Ginn BAMF Wish Source class.
*/
/*
* Copyright 2013 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ginn/xmlwishsource.h"
#include <algorithm>
#include <cstring>
#include "ginn/actionbuilder.h"
#include "ginn/keymap.h"
#include "ginn/wishbuilder.h"
#include "ginn/wish.h"
#include "ginn/wishsourceconfig.h"
#include <iostream>
#include <iterator>
#include <libxml/xmlreader.h>
#include <memory>
#include <string>
/**
* Partial specializations of std::default_delete to trick std::unique_ptr into
* working with uninitialized pointers as singular vales.
*
* Sheesh, the things we do for love.
*/
namespace std
{
template<>
class default_delete<xmlRelaxNGParserCtxt>
{
public:
void operator()(xmlRelaxNGParserCtxt* p)
{ xmlRelaxNGFreeParserCtxt(p); }
};
template<>
class default_delete<xmlRelaxNG>
{
public:
void operator()(xmlRelaxNG* p)
{ xmlRelaxNGFree(p); }
};
template<>
class default_delete<xmlRelaxNGValidCtxt>
{
public:
void operator()(xmlRelaxNGValidCtxt* p)
{ xmlRelaxNGFreeValidCtxt(p); }
};
template<>
class default_delete<xmlDoc>
{
public:
void operator()(xmlDoc* p)
{ xmlFreeDoc(p); }
};
} // namespace std
namespace Ginn
{
using ParserCtxtPtr = std::unique_ptr<xmlRelaxNGParserCtxt>;
using SchemaPtr = std::unique_ptr<xmlRelaxNG>;
using ValidatorPtr = std::unique_ptr<xmlRelaxNGValidCtxt>;
using XmlDocPtr = std::unique_ptr<xmlDoc>;
/**
* Transforms an action XML entity into an Action.
*/
struct XmlActionBuilder
: public ActionBuilder
{
XmlActionBuilder(xmlNodePtr const& node, Keymap* keymap);
Action::EventList const&
events() const;
private:
Action::EventList events_;
};
XmlActionBuilder::
XmlActionBuilder(xmlNodePtr const& node, Keymap* keymap)
{
Action::EventList tail;
char const* mod1 = (char const*)xmlGetProp(node, (xmlChar const*)"modifier1");
if (mod1)
{
events_.push_back({Action::EventType::key_press, keymap->to_keycode(mod1)});
tail.push_back({Action::EventType::key_release, keymap->to_keycode(mod1)});
}
char const* mod2 = (char const*)xmlGetProp(node, (xmlChar const*)"modifier2");
if (mod2)
{
events_.push_back({Action::EventType::key_press, keymap->to_keycode(mod2)});
tail.push_back({Action::EventType::key_release, keymap->to_keycode(mod2)});
}
if (0 == strcmp((char const*)node->name, "button"))
{
for (xmlNodePtr child = node->children; child; child = child->next)
{
if (child->type == XML_TEXT_NODE)
{
// @todo use something better to convert content to keycode
std::string keysym(reinterpret_cast<char const*>(child->content));
events_.push_back({Action::EventType::button_press,
static_cast<Keymap::Keycode>(std::stoi(keysym))});
tail.push_back({Action::EventType::button_release,
static_cast<Keymap::Keycode>(std::stoi(keysym))});
}
}
}
else if (0 == strcmp((char const*)node->name, "key"))
{
for (xmlNodePtr child = node->children; child; child = child->next)
{
if (child->type == XML_TEXT_NODE)
{
std::string keysym(reinterpret_cast<char const*>(child->content));
events_.push_back({Action::EventType::key_press,
keymap->to_keycode(keysym)});
tail.push_back({Action::EventType::key_release,
keymap->to_keycode(keysym)});
}
}
}
std::copy(tail.rbegin(), tail.rend(), std::back_inserter(events_));
}
Action::EventList const& XmlActionBuilder::
events() const
{
return events_;
}
/**
* Transforms a wish XML node into a Wish object.
*/
struct XmlWishBuilder
: public WishBuilder
{
XmlWishBuilder(xmlNodePtr const& node, Keymap* keymap);
~XmlWishBuilder()
{ }
std::string
name() const
{ return gesture_ + std::to_string(touches_) + property_; }
std::string
gesture() const
{ return gesture_; }
int
touches() const
{ return touches_; }
std::string
when() const
{ return when_; }
std::string
property() const
{ return property_; }
float
min() const
{ return min_; }
float
max() const
{ return max_; }
Action
action() const
{ return action_; }
private:
std::string gesture_;
int touches_;
std::string when_;
std::string property_;
float min_;
float max_;
Action action_;
};
/**
* Unpacks the WIsh DOM into separate values that can be used to build a Wish.
* @param[in] app_name The name of the application (or <global>).
* @param[in] node The wish XML DOM.
*/
XmlWishBuilder::
XmlWishBuilder(xmlNodePtr const& node, Keymap* keymap)
: gesture_((char const*)xmlGetProp(node, (xmlChar const*)"gesture"))
, touches_(std::stoi((char const*)xmlGetProp(node, (xmlChar const*)"fingers")))
, min_(0.0f)
, max_(0.0f)
{
for (xmlNodePtr child = node->children; child; child = child->next)
{
if (child->type == XML_ELEMENT_NODE
&& 0 == strcmp((char const*)child->name, "action"))
{
when_ = (char const*)xmlGetProp(child, (xmlChar const*)"when");
for (xmlNodePtr anode = child->children; anode; anode = anode->next)
{
if (anode->type == XML_ELEMENT_NODE)
{
if (0 == strcmp((char const*)anode->name, "trigger"))
{
property_ = (char const*)xmlGetProp(anode, (xmlChar const*)"prop");
char const* smin = (char const*)xmlGetProp(anode, (xmlChar const*)"min");
if (smin)
{
min_ = std::stof(smin);
}
char const* smax = (char const*)xmlGetProp(anode, (xmlChar const*)"max");
if (smax)
{
max_ = std::stof(smax);
}
}
else if (0 == strcmp((char const*)anode->name, "button")
|| 0 == strcmp((char const*)anode->name, "key"))
{
action_ = Action(XmlActionBuilder(anode, keymap));
}
}
}
}
}
}
/**
* Internal implementation of the XML wish source.
*/
struct XmlWishSource::Impl
{
Impl(WishSourceConfig const* config);
~Impl()
{ }
void
wish_table_merge(Wish::Table& lhs, Wish::Table const& rhs);
WishSourceConfig const* config_;
ParserCtxtPtr ctxt_;
SchemaPtr schema_;
ValidatorPtr vctxt_;
};
/** @todo: add proper error handling to schema load/parse */
XmlWishSource::Impl::
Impl(WishSourceConfig const* config)
: config_(config)
{
std::string const& schema_file_name = config_->wish_schema_file_name();
if (schema_file_name != WishSourceConfig::WISH_NO_VALIDATE)
{
ctxt_ = ParserCtxtPtr(xmlRelaxNGNewParserCtxt(schema_file_name.c_str()));
schema_ = SchemaPtr(xmlRelaxNGParse(ctxt_.get()));
vctxt_ = ValidatorPtr(xmlRelaxNGNewValidCtxt(schema_.get()));
}
}
/**
* Merges rhs into lhs, with rhs replacing lhs where keys are dupolicated.
* @param[inout] lhs The destination Wish::Table
* @param[in] rhs The source Wish::Table
*/
void XmlWishSource::Impl::
wish_table_merge(Wish::Table& lhs, Wish::Table const& rhs)
{
for (auto const& p: rhs)
{
if (config_->is_verbose_mode())
{
std::cout << " adding wishes for app '" << p.first << "'\n";
for (auto const& wish: p.second)
std::cout << " " << *wish.second << "\n";
}
lhs[p.first] = p.second;
}
}
XmlWishSource::
XmlWishSource(WishSourceConfig const* config)
: impl_(new Impl(config))
{
if (impl_->config_->is_verbose_mode())
std::cout << __FUNCTION__ << " created\n";
}
XmlWishSource::
~XmlWishSource()
{
}
/**
* Processes a collection of wishes targeted to a specific application
* (including the global <global> application).
* @param[in] node An XML node to process.
* @param[out] wishes The current collection of processed wishes.
*/
static Wish::List
process_application_node(xmlNodePtr node, Keymap* keymap)
{
Wish::List wish_list;
while (node)
{
if (node->type == XML_ELEMENT_NODE
&& 0 == strcmp((char const*)node->name, "wish"))
{
auto wish = std::make_shared<Wish>(XmlWishBuilder(node, keymap));
wish_list[wish->name()] = wish;
}
node = node->next;
}
return wish_list;
}
/**
* Processes the top-level <ginn> node of the wish XML.
* @param[in] node An XML node to process.
* @param[in] keymap The mapping between key symbol names and keycodes.
* @param[out] wishes The current collection of processed wishes.
*/
static void
process_ginn_node(xmlNodePtr node, Keymap* keymap, Wish::Table& wish_table)
{
while (node)
{
if (node->type == XML_ELEMENT_NODE)
{
if (0 == strcmp((char const*)node->name, "global"))
{
wish_table["<global>"] = process_application_node(node->children,
keymap);
}
else if (0 == strcmp((char const*)node->name, "applications"))
{
for (xmlNodePtr app_node = node->children;
app_node;
app_node = app_node->next)
{
if (app_node->type == XML_ELEMENT_NODE
&& 0 == strcmp((char const*)app_node->name, "application"))
{
char const* name = (char const*)xmlGetProp(app_node, (xmlChar const*)"name");
wish_table[name] = process_application_node(app_node->children,
keymap);
}
}
}
}
node = node->next;
}
}
static Wish::Table
load_wishes(ValidatorPtr const& vctxt,
WishSource::RawSource const& raw_source,
Keymap* keymap)
{
Wish::Table wish_table;
XmlDocPtr xml_doc { xmlParseMemory(raw_source.source.data(),
raw_source.source.size()) };
if (!xml_doc)
{
std::cerr << "error reading " << raw_source.name << "\n";
}
else
{
if (vctxt)
{
int result = xmlRelaxNGValidateDoc(vctxt.get(), xml_doc.get());
if (result) {
std::cerr << "validation returned " << result << "\n";
return wish_table;
}
}
xmlNodePtr root = xmlDocGetRootElement(xml_doc.get());
if (root == NULL)
{
std::cerr << raw_source.name << ": empty document\n";
}
else if (0 != std::strcmp((char const*)root->name, "ginn"))
{
std::cerr << raw_source.name << ": unexpected document root '"
<< root->name << "'\n";
}
else
{
process_ginn_node(root->children, keymap, wish_table);
}
}
return wish_table;
}
/**
* Reads a wishes file and processes it into a Wish::List.
*
* If configured, the wish file may be validated first.
*/
Wish::Table XmlWishSource::
get_wishes(WishSource::RawSourceList const& raw_wishes, Keymap* keymap)
{
Wish::Table wish_table;
for (auto const& raw_source: raw_wishes)
{
if (impl_->config_->is_verbose_mode())
std::cout << __FUNCTION__ << "(): "
<< " loading '" << raw_source.name << "'\n";
impl_->wish_table_merge(wish_table,
load_wishes(impl_->vctxt_, raw_source, keymap));
}
return wish_table;
}
} // namespace Ginn
| gpl-3.0 |
c0bra2/TrainingScheduler | TrainingScheduler/TrainingScheduler/Form1.cs | 34810 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TrainingScheduler
{
public partial class Form1 : Form
{
private List<Schedule> customerSchedule = new List<Schedule>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
/*// make it readonly
//trainerComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
testerComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
vehicalComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
timeComboBox.DropDownStyle = ComboBoxStyle.DropDownList;*/
// trainercombo options
trainerComboBox.Items.Add("Chris Humphrey");
trainerComboBox.Items.Add("Patrick Humphrey");
trainerComboBox.Items.Add("Ed Humphrey");
trainerComboBox.Items.Add("Dave Skutt");
trainerComboBox.Items.Add("Eddie Humphrey");
trainerComboBox.Text = "Chris Humphrey";
// testercombo options
testerComboBox.Items.Add("Chris Humphrey");
testerComboBox.Items.Add("Patrick Humphrey");
testerComboBox.Items.Add("Ed Humphrey");
testerComboBox.Items.Add("Dave Skutt");
testerComboBox.Items.Add("Eddie Humphrey");
testerComboBox.Text = "Patrick Humphrey";
// vehicalcombo options
vehicalComboBox.Items.Add("Semi Rental");
vehicalComboBox.Items.Add("Truck Rental");
vehicalComboBox.Items.Add("Customer Truck: Fifth Wheel");
vehicalComboBox.Items.Add("Customer Truck: Pintle Hitch");
vehicalComboBox.Items.Add("Customer Truck");
vehicalComboBox.Items.Add("School Bus");
vehicalComboBox.Items.Add("Transit/Coach");
vehicalComboBox.Items.Add("Car Rental");
vehicalComboBox.Items.Add("Customer's Car");
vehicalComboBox.Text = "Semi Rental";
// cdlcombo options
cdlComboBox.Items.Add("A");
cdlComboBox.Items.Add("B");
cdlComboBox.Items.Add("BP");
cdlComboBox.Items.Add("BPS");
cdlComboBox.Items.Add("C");
cdlComboBox.Text = "A";
// brakecombo options
brakeComboBox.Items.Add("Hydraulic");
brakeComboBox.Items.Add("Partial Air");
brakeComboBox.Items.Add("Full Air");
brakeComboBox.Text = "Full Air";
// transcombo options
transComboBox.Items.Add("Manual");
transComboBox.Items.Add("Automatic");
transComboBox.Text = "Manual";
// timescombo options
timeComboBox.Items.Add("8:00AM");
timeComboBox.Items.Add("9:00AM");
timeComboBox.Items.Add("10:00AM");
timeComboBox.Items.Add("11:00AM");
timeComboBox.Items.Add("12:00PM");
timeComboBox.Items.Add("1:00PM");
timeComboBox.Items.Add("12:00PM");
timeComboBox.Items.Add("2:00PM");
timeComboBox.Items.Add("3:00PM");
timeComboBox.Items.Add("4:00PM");
timeComboBox.Items.Add("5:00PM");
timeComboBox.Items.Add("6:00PM");
timeComboBox.Items.Add("7:00PM");
timeComboBox.Text = "9:00AM";
// tenativecombo options
tenativeComboBox.Items.Add("Yes");
tenativeComboBox.Items.Add("No");
tenativeComboBox.Text = "No";
// lengthcombo options
lengthComboBox.Items.Add("1hrs");
lengthComboBox.Items.Add("2hrs");
lengthComboBox.Items.Add("3hrs");
lengthComboBox.Items.Add("4hrs");
lengthComboBox.Items.Add("5hrs");
lengthComboBox.Items.Add("6hrs");
lengthComboBox.Items.Add("7hrs");
lengthComboBox.Items.Add("8hrs");
lengthComboBox.Text = "4hrs";
// lengthcombo options
idComboBox.Items.Add("1");
idComboBox.Text = "1";
//UI Behavior Update. Bias towards car tests
cdlComboBox.Visible = false;
label10.Visible = false;
transComboBox.Visible = false;
label12.Visible = false;
brakeComboBox.Visible = false;
label11.Visible = false;
lengthComboBox.Text = "1hrs";
vehicalComboBox.Text = "Customer's Car";
}
/*ADD Training TO SCHEDULE BUTTON*/
private void button2_Click(object sender, EventArgs e)
{
//create driver object
Driver dObj = new Driver();
dObj.first_name = firstTextBox.Text;
dObj.last_name = lastTextBox.Text;
dObj.trainer = trainerComboBox.Text;
dObj.tester = testerComboBox.Text;
dObj.vehical = vehicalComboBox.Text;
dObj.trans = transComboBox.Text;
dObj.brakes = brakeComboBox.Text;
dObj.cdl = cdlComboBox.Text;
dObj.setRate(dObj.vehical, false);
//create schedule obj
Schedule sObj = new Schedule();
sObj.customer = dObj;
sObj.date = dateTimePicker1.Value.ToShortDateString();
sObj.time = timeComboBox.Text;
sObj.id = idComboBox.Text;
sObj.tentative = tenativeComboBox.Text;
sObj.setHours(lengthComboBox.Text);
sObj.type = "train";
idComboBox.Items.Add((Int32.Parse(idComboBox.Text) + 1).ToString());
idComboBox.Text = (Int32.Parse(idComboBox.Text) + 1).ToString();
//add to list
try
{
customerSchedule.Add(sObj);
}
catch
{
//do nothing
}
//print training in box and testing
printTrainingToBox(customerSchedule);
printTestingToBox(customerSchedule);
}
//test button clicked
private void button5_Click(object sender, EventArgs e)
{
//create driver object
Driver dObj = new Driver();
dObj.first_name = firstTextBox.Text;
dObj.last_name = lastTextBox.Text;
dObj.trainer = trainerComboBox.Text;
dObj.tester = testerComboBox.Text;
dObj.vehical = vehicalComboBox.Text;
dObj.trans = transComboBox.Text;
dObj.brakes = brakeComboBox.Text;
dObj.cdl = cdlComboBox.Text;
dObj.setRate(dObj.vehical, false);
//create schedule obj
Schedule sObj = new Schedule();
sObj.customer = dObj;
sObj.date = dateTimePicker1.Value.ToShortDateString();
sObj.time = timeComboBox.Text;
sObj.id = idComboBox.Text;
sObj.tentative = tenativeComboBox.Text;
if (dObj.vehical != "Car Rental" && dObj.vehical != "Customer's Car"){
sObj.setHours("3hrs");
}
else {
sObj.setHours("1hrs");
}
sObj.type = "test";
idComboBox.Items.Add((Int32.Parse(idComboBox.Text) + 1).ToString());
idComboBox.Text = (Int32.Parse(idComboBox.Text) + 1).ToString();
//add to list
try
{
customerSchedule.Add(sObj);
}
catch
{
//do nothing
}
//go through and set rates
for (int i = 0; i < customerSchedule.Count; i++)
{
customerSchedule[i].customer.setRate(vehicalComboBox.Text, false);
}
//print training in box and testing
printTrainingToBox(customerSchedule);
printTestingToBox(customerSchedule);
}
//RUNS WHEN REMOVE ID BUTTON CLICKED
private void button1_Click(object sender, EventArgs e)
{
//make sure there are items to remove first
if (idComboBox.Items.Count != 1)
{
//remove the item of specified ID
int removeIndex = 0;
int largest = 0;
bool removable;
List<string> ids = new List<string>();
for (int i = 0; i < customerSchedule.Count; i++)
{
if (customerSchedule[i].id == idComboBox.Text)
{
removeIndex = i;
}
else
{
ids.Add(customerSchedule[i].id);
}
}
customerSchedule.RemoveAt(removeIndex);
//remove id number from combobox
for (int i = 0; i < idComboBox.Items.Count; i++)
{
if (idComboBox.GetItemText(idComboBox.Items[i]) == idComboBox.Text)
{
removeIndex = i;
}
}
idComboBox.Items.RemoveAt(removeIndex);
//go through and find unused IDs, remove them too
for (int i = 0; i < ids.Count; i++)
{
removable = true;
for (int j = 0; j < idComboBox.Items.Count; j++)
{
if (ids[i] == idComboBox.GetItemText(idComboBox.Items[j]))
{
removable = false;
}
}
if (removable)
{
for (int k = 0; k < idComboBox.Items.Count; k++)
{
if ((idComboBox.GetItemText(idComboBox.Items[k]) == ids[i]) && ids[i] != largest.ToString())
{
idComboBox.Items.RemoveAt(k);
}
}
}
}
for (int i = 0; i < idComboBox.Items.Count; i++)
{
if (Int32.Parse(idComboBox.GetItemText(idComboBox.Items[i])) > largest)
{
largest = Int32.Parse(idComboBox.GetItemText(idComboBox.Items[i]));
}
}
//new ID to set in idcombobox
idComboBox.Text = largest.ToString();
//print training in box and testing
printTrainingToBox(customerSchedule);
printTestingToBox(customerSchedule);
}
}
private void printTestingToBox(List<Schedule> s)
{
bool testDate = false;
for (int i = 0; i < s.Count; i++)
{
if (s[i].type == "test" ||s[i].type == "retest")
{
testDate = true;
}
}
if (!testDate)
{
return;
}
else
{
int total = 0;
//print testing header
richTextBox1.AppendText("\n\n\nTesting\n" + padString("ID", 5) + padString("Date", 20) + padString("Time", 15) + "\n");
//print data for each testing session
for (int i = 0; i < s.Count; i++)
{
if (s[i].type == "test" || s[i].type == "retest")
{
richTextBox1.AppendText(padString(s[i].id, 6) +
padString(s[i].date, 15) + padString(s[i].time, 12));
if (s[i].customer.tester == "Chris Humphrey")
{
richTextBox1.AppendText("w/Chris ");
}
else if (s[i].customer.tester == "Patrick Humphrey")
{
richTextBox1.AppendText("w/Pat ");
}
else if(s[i].customer.tester == "Dave Skutt")
{
richTextBox1.AppendText("w/Dave");
}
else if (s[i].customer.tester == "Ed Humphrey")
{
richTextBox1.AppendText("w/Ed ");
}
if (s[i].tentative == "Yes")
{
richTextBox1.AppendText(padString("(T)\n", 0));
}
else
{
richTextBox1.AppendText("\n");
}
total += s[i].customer.testingRate;
}
}
richTextBox1.AppendText("Testing Cost: $" + total);
}
}
private void printTrainingToBox(List<Schedule> s)
{
int total = 0;
richTextBox1.Clear();
//print training header
richTextBox1.AppendText("Training\n" + padString("ID", 5) +
padString("Length", 11) + padString("Date", 20) + padString("Time", 15) + "\n");
//print data for each training session
for (int i = 0; i < s.Count; i++)
{
if (s[i].type == "train")
{
richTextBox1.AppendText(padString(s[i].id, 6) + padString(s[i].hours, 14) +
padString(s[i].date, 15) + padString(s[i].time, 12));
if (s[i].customer.trainer == "Chris Humphrey")
{
richTextBox1.AppendText("w/Chris ");
}
else if (s[i].customer.trainer == "Patrick Humphrey")
{
richTextBox1.AppendText("w/Pat ");
}
else if (s[i].customer.trainer == "Ed Humphrey")
{
richTextBox1.AppendText("w/Ed ");
}
if (s[i].tentative == "Yes")
{
richTextBox1.AppendText(padString("(T)\n", 0));
}
else
{
richTextBox1.AppendText("\n");
}
total += s[i].hoursTrained * s[i].customer.trainingRate;
}
}
richTextBox1.AppendText("Training Cost: $" + total);
}
public string padString(string s, int p)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
count++;
}
p -= count;
for (; p > 0; p--)
{
s += " ";
}
return s;
}
/// <summary>
/// Print Button Clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
int totalHours = 0;
string filename;
string output = "";
Driver customer = customerSchedule[0].customer;
filename = "Humphrey's" + ".txt";
//define output string
output += "\r\n\r\n";
output += "Customer: " + customer.first_name + " " + customer.last_name + "\r\n";
output += "CDL Lot: 110 S. Delaney Rd. Owosso MI, 48867\r\n";
output += "Vehical: " + customer.vehical + ", " + customer.trans + " Trans, " + customer.brakes + " Brakes \r\n";
output += customer.restrictions(false);
output += "Class: " + "CDL-" + customer.cdl + "\r\n";
output += "Training Rate $" + customer.trainingRate + "/hr\r\n";
output += "Testing Rate $" + customer.testingRate + "\r\n";
output += "\r\n\r\n";
output += "Training Schedule\r\n" + padString("Date", 19) + padString("Time", 14) + padString("Length", 17) + padString("Trainer", 10) + "\r\n";
for (int i = 0; i < 65; i++)
{
output += "-";
}
output += "\r\n";
for (int i = 0; i < customerSchedule.Count; i++)
{
if (customerSchedule[i].type == "train")
{
output += padString(customerSchedule[i].date, 19) + padString(customerSchedule[i].time, 14) + padString(customerSchedule[i].hours, 17) + padString(customerSchedule[i].customer.trainer, 20);
if (customerSchedule[i].tentative == "Yes")
{
output += "(Tenative)\r\n";
}
output += "\r\n";
totalHours += customerSchedule[i].hoursTrained;
}
}
output += "\r\n\r\n\r\n\r\n\r\n";
output += "Testing Schedule\r\n" + padString("Date", 19) + padString("Time", 14) + padString("Length", 17) + padString("Trainer", 10) + "\r\n";
for (int i = 0; i < 65; i++)
{
output += "-";
}
output += "\r\n";
for (int i = 0; i < customerSchedule.Count; i++)
{
if (customerSchedule[i].type == "test")
{
output += padString(customerSchedule[i].date, 19) + padString(customerSchedule[i].time, 14) + padString(customerSchedule[i].hours, 17) + padString(customerSchedule[i].customer.tester, 20);
if (customerSchedule[i].tentative == "Yes")
{
output += "(Tenative)\r\n";
}
output += "\r\n";
}
}
output += "\r\n\r\n\r\n\r\n\r\n\r\n";
output += "Summary (Totals subject to change if deviating from this outline)\r\n";
for (int i = 0; i < 65; i++)
{
output += "-";
}
output += "\r\n";
output += "Training (" + totalHours + "hrs * $" + customer.trainingRate + "/hr) = $" + totalHours * customer.trainingRate + "\r\n";
output += "Test = $" + customer.testingRate + "\r\n\r\n";
output += "Grand Total = $" + ((totalHours * customer.trainingRate) + customer.testingRate);
System.IO.File.WriteAllText(filename, output);
System.Diagnostics.Process.Start(filename);
}
/// <summary>
/// HTML OUTPUT BUTTON
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button7_Click(object sender, EventArgs e)
{
try
{
//valid checks
if (firstTextBox.Text == "" || lastTextBox.Text == "")
{
MessageBox.Show("Enter a valid name for Customer!");
return;
}
bool hasTest = false;
button7.Enabled = false;
int totalHours = 0;
string filename;
string output = "";
Driver customer = customerSchedule[0].customer;
filename = "Humphrey's" + ".html";
output += @"<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: black;
text-align: left;
font-family: Helvetica;
font-size: 30px
}
.dba {
color: black;
font-family: Helvetica;
font-size: 15px;}
.hed{
color: black;
text-align: left;
font-family: Helvetica;
font-size: 11px;
}
.hed2{
color: left;
text-align: center;
font-family: bold Helvetica;
font-size: 13px;
}
.hed3{
color: black;
text-align: left;
font-family: bold Helvetica;
font-size: 15px;
}
.hed4{
color: black;
text-align: left;
font-family: Helvetica;
font-size: 13px;
text-transform: none;
}
p {
font-family: Helvetica;
font-size: 18px;
}
hr {
display: block;
margin-top: 0.1em;
margin-bottom: 0em;
margin-left: auto;
margin-right: auto;
border-style: inset;
border-width: 1px;
}
body {
font-family: Helvetica, sans;
font-size: 18px;
color: #333333;
font-weight: normal;
line-height: 1.2;
width: 960px;
margin: 0 auto;
padding: 0;
}
li {
list-style-type: none;
display: inline-block;
}
.header {
text-align: center;
padding: 5px auto;
}
.title {
text-align: center;
}
.title .span-text {
font-size: 14px;
}
.address {
padding-bottom: 10px;
border-bottom: 3px solid #a5a5a5;
text-align: center;
}
.cert {
font-weight: bold;
text-align: center;
padding-bottom: 20px;
}
.cust_detail {
/* No styles yet */
}
.cust_detail table td {
text-align: left;
padding-top: 5px;
padding-bottom: 5px;
width: 10%;
}
.schedule {
padding-top: 10px;
}
.schedule h3 {
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 3px solid #a5a5a5;
text-transform: uppercase;
color: #3e3e3e;
}
.schedule table tr th {
text-align: left;
padding-top: 5px;
padding-bottom: 5px;
width: 20%;
}
.schedule table tr td {
text-align: left;
padding-top: 5px;
padding-bottom: 5px;
font-weight: normal;
min-width: 150px;
}
.summary {
padding-top: 10px;
padding-bottom: 5px;
}
.summary h3 {
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 3px solid #a5a5a5;
text-transform: uppercase;
color: #3e3e3e;
}
.summary h3 span {
text-transform: none;
}
.summary table td {
text-align: left;
padding-top: 5px;
padding-bottom: 5px;
width: 10%;
}
</style>
</head>
<body>
<h1>Humphrey Driver Training and Testing <span class=" + "\"dba" + "\">" + "(DBA)</span></br><span class=" + "\"hed2" + "\">" + "Humphrey Enterprises, Inc.    </span>" +
"<span class=" + "\"hed2" + "\">" + "Office:  </span><span class=" + "\"hed" + "\">" + "2089 Corunna Ave. Owosso MI, 48867     </span><span class=" + "\"hed2" + "\">" +
"Phone:</span><span class=" + "\"hed" + "\">" + "  989-723-7176</span></br><hr><span class=" + "\"hed3" + "\">";
if (customer.vehical != "Customer's Car" && customer.vehical != "Car Rental")
{
output += "Department of State Certification #P000422      " +
"                              " +
"                      " +
"  </span></h1></br>";
}
else
{
output += "Department of State Certification #P000421      " +
"                              " +
"                      " +
"  </span></h1></br>";
}
output += " <p>" + "Customer: " + customer.first_name + " " + customer.last_name + "</br>";
if (customer.vehical != "Customer's Car" && customer.vehical != "Car Rental")
{
output += "CDL Lot: 110 S. Delaney Rd. Owosso MI, 48867</br>";
}
else
{
output += "Lot: 2089 Corunna Ave Owosso MI, 48867<br/>";
}
if (customer.vehical != "Customer's Car" && customer.vehical != "Car Rental")
{
output += "Vehical: " + customer.vehical + ", " + customer.trans + " Trans, " + customer.brakes + " Brakes <br/>";
}
else
{
output += "Vehical: " + customer.vehical + "<br/>";
}
output += customer.restrictions(true);
if (customer.vehical != "Customer's Car" && customer.vehical != "Car Rental")
{
output += "Class: " + "CDL-" + customer.cdl + "</br>";
}
output += "Training Rate $" + customer.trainingRate + "/hr</br>";
output += "Testing Rate $" + customer.testingRate + "</br>";
output += "</p><div class=\"schedule\">" +
@"<h3>Training Schedule</h3>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Length</th>
<th>Trainer</th>
</tr>";
for (int i = 0; i < customerSchedule.Count; i++)
{
if (customerSchedule[i].type == "train")
{
output += "<tr>";
output += "<td>" + customerSchedule[i].date + "</td>" + "<td>" + customerSchedule[i].time + "</td>" + "<td>" + customerSchedule[i].hours + "</td>" + "<td>" + customerSchedule[i].customer.trainer + "</td>";
output += "</tr>";
totalHours += customerSchedule[i].hoursTrained;
}
}
output += "</table></br></br>";
output += @"<h3>Testing Schedule</h3>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Length</th>
<th>Tester</th>
</tr>";
for (int i = 0; i < customerSchedule.Count; i++)
{
if (customerSchedule[i].type == "test" || customerSchedule[i].type == "retest")
{
output += "<tr>";
output += "<td>" + customerSchedule[i].date + "</td>" + "<td>" + customerSchedule[i].time + "</td>" + "<td>" + customerSchedule[i].hours + "</td>" + "<td>" + customerSchedule[i].customer.tester + "</td>";
output += "</tr>";
hasTest = true;
}
}
output += "</table></br></br>";
output += "<h3>Summary<span class=\"hed4\"> (Totals subject to change if deviating from this outline)</span></h3>";
output += "<p>Training (" + totalHours + "hrs * $" + customer.trainingRate + "/hr) = $" + totalHours * customer.trainingRate + "<br/>";
if (hasTest)
{
output += "Test = $" + customer.testingRate + "<br/><br/>";
output += "Grand Total = $" + ((totalHours * customer.trainingRate) + customer.testingRate);
}
else
{
output += "Test = $" + "0" + "<br/><br/>";
output += "Grand Total = $" + (totalHours * customer.trainingRate);
}
output += @"</div></p>
</body>
</html>";
System.IO.File.WriteAllText(filename, output);
System.Diagnostics.Process.Start(filename);
/*SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
SelectPdf.PdfDocument doc = converter.ConvertHtmlString(output);
try
{
doc.Save("Humphrey's.pdf");
}
catch
{
}
doc.Close();
System.Diagnostics.Process.Start("Humphrey's.pdf");
*/
button7.Enabled = true;
}
catch
{
MessageBox.Show("Something went wrong :(");
button7.Enabled = true;
}
}
private void button3_Click(object sender, EventArgs e)
{
//clear customerSchedule
customerSchedule = new List<Schedule>();
//print training in box and testing
printTrainingToBox(customerSchedule);
printTestingToBox(customerSchedule);
}
private void cdlComboBox_MouseClick(object sender, MouseEventArgs e)
{
cdlComboBox.DroppedDown = true;
}
private void transComboBox_MouseClick(object sender, MouseEventArgs e)
{
transComboBox.DroppedDown = true;
}
private void trainerComboBox_MouseClick(object sender, MouseEventArgs e)
{
trainerComboBox.DroppedDown = true;
}
private void testerComboBox_MouseClick(object sender, MouseEventArgs e)
{
testerComboBox.DroppedDown = true;
}
private void vehicalComboBox_MouseClick(object sender, MouseEventArgs e)
{
vehicalComboBox.DroppedDown = true;
}
private void brakeComboBox_MouseClick(object sender, MouseEventArgs e)
{
brakeComboBox.DroppedDown = true;
}
private void timeComboBox_MouseClick(object sender, MouseEventArgs e)
{
timeComboBox.DroppedDown = true;
}
private void idComboBox_MouseClick(object sender, MouseEventArgs e)
{
idComboBox.DroppedDown = true;
}
private void tenativeComboBox_MouseClick(object sender, MouseEventArgs e)
{
tenativeComboBox.DroppedDown = true;
}
private void lengthComboBox_MouseClick(object sender, MouseEventArgs e)
{
lengthComboBox.DroppedDown = true;
}
private void dateTimePicker1_MouseDown(object sender, MouseEventArgs e)
{
dateTimePicker1.Select();
SendKeys.Send("%{DOWN}");
}
private void vehicalComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (vehicalComboBox.Text == "Car Rental" || vehicalComboBox.Text == "Customer's Car")
{
cdlComboBox.Visible = false;
label10.Visible = false;
transComboBox.Visible = false;
label12.Visible = false;
brakeComboBox.Visible = false;
label11.Visible = false;
lengthComboBox.Text = "1hrs";
}
else
{
cdlComboBox.Visible = true;
label10.Visible = true;
transComboBox.Visible = true;
label12.Visible = true;
brakeComboBox.Visible = true;
label11.Visible = true;
lengthComboBox.Text = "3hrs";
}
}
//retest button clicked
private void button6_Click(object sender, EventArgs e)
{
//create driver object
Driver dObj = new Driver();
dObj.first_name = firstTextBox.Text;
dObj.last_name = lastTextBox.Text;
dObj.trainer = trainerComboBox.Text;
dObj.tester = testerComboBox.Text;
dObj.vehical = vehicalComboBox.Text;
dObj.trans = transComboBox.Text;
dObj.brakes = brakeComboBox.Text;
dObj.cdl = cdlComboBox.Text;
dObj.setRate(dObj.vehical, true);
//create schedule obj
Schedule sObj = new Schedule();
sObj.customer = dObj;
sObj.date = dateTimePicker1.Value.ToShortDateString();
sObj.time = timeComboBox.Text;
sObj.id = idComboBox.Text;
sObj.tentative = tenativeComboBox.Text;
if (dObj.vehical != "Car Rental" && dObj.vehical != "Customer's Car")
{
sObj.setHours(timeComboBox.Text);
}
else
{
sObj.setHours("1hrs");
}
sObj.type = "retest";
idComboBox.Items.Add((Int32.Parse(idComboBox.Text) + 1).ToString());
idComboBox.Text = (Int32.Parse(idComboBox.Text) + 1).ToString();
//add to list
try
{
customerSchedule.Add(sObj);
}
catch
{
//do nothing
}
//go through and set rates
for (int i = 0; i < customerSchedule.Count; i++)
{
customerSchedule[i].customer.setRate(vehicalComboBox.Text, true);
}
//print training in box and testing
printTrainingToBox(customerSchedule);
printTestingToBox(customerSchedule);
}
}
} | gpl-3.0 |
jantman/PHPsa | inc/common.php | 5215 | <?php
// common.php - common functions
//
// +----------------------------------------------------------------------+
// | PHPsa http://phpsa.jasonantman.com |
// +----------------------------------------------------------------------+
// | Copyright (c) 2009 Jason Antman. |
// | |
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation; either version 3 of the License, or |
// | (at your option) any later version. |
// | |
// | This program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to: |
// | |
// | Free Software Foundation, Inc. |
// | 59 Temple Place - Suite 330 |
// | Boston, MA 02111-1307, USA. |
// +----------------------------------------------------------------------+
// |Please use the above URL for bug reports and feature/support requests.|
// +----------------------------------------------------------------------+
// | Authors: Jason Antman <jason@jasonantman.com> |
// +----------------------------------------------------------------------+
// | $LastChangedRevision:: 11 $ |
// | $HeadURL:: http://svn.jasonantman.com/xmlfinal/inc/common.php $ |
// +----------------------------------------------------------------------+
// setup MySQL connection
//$conn = mysql_connect($config_db_host, $config_db_user, $config_db_pass) or die("Unable to connect to MySQL database.<br />");
//mysql_select_db($config_db_name) or die("Unable to select database: ".$config_db_name.".<br />");
require_once('html.php');
/**
* Strip out junk from subversion keyword-replaced variables
* @param string $s original string
* @return string
*/
function stripSVNstuff($s)
{
$s = substr($s, strpos($s, ":")+1);
$s = str_replace("$", "", $s);
return trim($s);
}
function dbConnect()
{
global $PHPsa_config_dbName, $PHPsa_config_dbHost, $PHPsa_config_dbUser, $PHPsa_config_dbPass;
$conn = mysql_connect($PHPsa_config_dbHost, $PHPsa_config_dbUser, $PHPsa_config_dbPass);
if(! $conn){ dberror("Connecting to MySQL...", mysql_error()); return false;}
mysql_select_db($PHPsa_config_dbName) or dberror("Selecting database: $PHPsa_config_dbName", mysql_error());
return $conn;
}
function dberror($query, $error)
{
error_log("Database error!\nQuery: $query\nError: $error\n");
die("Database error. Script dieing...<br />");
}
/**
* Get the string to use as the title for the current page
* @return string
*/
function getPageTitle()
{
$foo = "PHPsa - ".getCurrentModuleName();
$bar = getCurrentScriptTitle();
if($bar != "" && $bar != "Home")
{
$foo .= " - ".$bar;
}
return $foo;
}
/**
* returns the name of the active module, or "" for the main module
* @return string
*/
function getCurrentModuleName()
{
global $PHPsa_base_url_path, $PHPsa_path_modules;
$foo = $_SERVER["SCRIPT_NAME"];
if(strstr($foo, $PHPsa_base_url_path)){ $foo = substr($foo, strpos($foo, $PHPsa_base_url_path)+strlen($PHPsa_base_url_path));}
if(! strpos($foo, "/", 1)){ return "Home";}
$foo = substr($foo, 0, strrpos($foo, "/")+1);
return $PHPsa_path_modules[$foo];
}
/**
* returns the name of the active script
* @return string
*/
function getCurrentScriptName()
{
$foo = $_SERVER["SCRIPT_NAME"];
$foo = substr($foo, strrpos($foo, "/")+1);
return $foo;
}
/**
* get the title of the current script
* @return string
*/
function getCurrentScriptTitle()
{
//$PHPsa_modules['Logs']['pages'] = array('Home' => 'index.php', "Viewer" => 'viewer.php');
global $PHPsa_modules;
$name = getCurrentScriptName();
$mod = getCurrentModuleName();
if(in_array($name, $PHPsa_modules[$mod]['pages']))
{
return array_search($name, $PHPsa_modules[$mod]['pages']);
}
return "";
}
// returns array of files in a directory, optionally matching a regex
function listDirFiles($path, $regex = false)
{
$foo = array();
$dh = opendir($path);
while($entry = readdir($dh))
{
if(! is_file($path.$entry) || $entry == "." || $entry == "..") { continue;}
if(! $regex){ $foo[] = $entry;}
else
{
if(preg_match($regex, $entry) > 0){ $foo[] = $entry;}
}
}
closedir($dh);
return $foo;
}
?> | gpl-3.0 |
apballard/Marlin | Marlin/temperature.cpp | 67880 | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* temperature.cpp - temperature control
*/
#include "Marlin.h"
#if ENABLED(EXPERIMENTAL_LCD)
#include "experimental_lcd.h"
#else
#include "ultralcd.h"
#endif
#include "temperature.h"
#include "thermistortables.h"
#include "ultralcd.h"
#include "planner.h"
#include "language.h"
#if ENABLED(HEATER_0_USES_MAX6675)
#include "spi.h"
#endif
#if ENABLED(BABYSTEPPING)
#include "stepper.h"
#endif
#if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
#include "endstops.h"
#endif
#if ENABLED(USE_WATCHDOG)
#include "watchdog.h"
#endif
#ifdef K1 // Defined in Configuration.h in the PID settings
#define K2 (1.0-K1)
#endif
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
static void* heater_ttbl_map[2] = { (void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE };
static uint8_t heater_ttbllen_map[2] = { HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN };
#else
static void* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS((void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE, (void*)HEATER_2_TEMPTABLE, (void*)HEATER_3_TEMPTABLE, (void*)HEATER_4_TEMPTABLE);
static uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN, HEATER_3_TEMPTABLE_LEN, HEATER_4_TEMPTABLE_LEN);
#endif
Temperature thermalManager;
// public:
float Temperature::current_temperature[HOTENDS] = { 0.0 },
Temperature::current_temperature_bed = 0.0;
int16_t Temperature::current_temperature_raw[HOTENDS] = { 0 },
Temperature::target_temperature[HOTENDS] = { 0 },
Temperature::current_temperature_bed_raw = 0;
#if HAS_HEATER_BED
int16_t Temperature::target_temperature_bed = 0;
#endif
#if ENABLED(PIDTEMP)
#if ENABLED(PID_PARAMS_PER_HOTEND) && HOTENDS > 1
float Temperature::Kp[HOTENDS] = ARRAY_BY_HOTENDS1(DEFAULT_Kp),
Temperature::Ki[HOTENDS] = ARRAY_BY_HOTENDS1((DEFAULT_Ki) * (PID_dT)),
Temperature::Kd[HOTENDS] = ARRAY_BY_HOTENDS1((DEFAULT_Kd) / (PID_dT));
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::Kc[HOTENDS] = ARRAY_BY_HOTENDS1(DEFAULT_Kc);
#endif
#else
float Temperature::Kp = DEFAULT_Kp,
Temperature::Ki = (DEFAULT_Ki) * (PID_dT),
Temperature::Kd = (DEFAULT_Kd) / (PID_dT);
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::Kc = DEFAULT_Kc;
#endif
#endif
#endif
#if ENABLED(PIDTEMPBED)
float Temperature::bedKp = DEFAULT_bedKp,
Temperature::bedKi = ((DEFAULT_bedKi) * PID_dT),
Temperature::bedKd = ((DEFAULT_bedKd) / PID_dT);
#endif
#if ENABLED(BABYSTEPPING)
volatile int Temperature::babystepsTodo[XYZ] = { 0 };
#endif
#if WATCH_HOTENDS
uint16_t Temperature::watch_target_temp[HOTENDS] = { 0 };
millis_t Temperature::watch_heater_next_ms[HOTENDS] = { 0 };
#endif
#if WATCH_THE_BED
uint16_t Temperature::watch_target_bed_temp = 0;
millis_t Temperature::watch_bed_next_ms = 0;
#endif
#if ENABLED(PREVENT_COLD_EXTRUSION)
bool Temperature::allow_cold_extrude = false;
int16_t Temperature::extrude_min_temp = EXTRUDE_MINTEMP;
#endif
// private:
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
uint16_t Temperature::redundant_temperature_raw = 0;
float Temperature::redundant_temperature = 0.0;
#endif
volatile bool Temperature::temp_meas_ready = false;
#if ENABLED(PIDTEMP)
float Temperature::temp_iState[HOTENDS] = { 0 },
Temperature::temp_dState[HOTENDS] = { 0 },
Temperature::pTerm[HOTENDS],
Temperature::iTerm[HOTENDS],
Temperature::dTerm[HOTENDS];
#if ENABLED(PID_EXTRUSION_SCALING)
float Temperature::cTerm[HOTENDS];
long Temperature::last_e_position;
long Temperature::lpq[LPQ_MAX_LEN];
int Temperature::lpq_ptr = 0;
#endif
float Temperature::pid_error[HOTENDS];
bool Temperature::pid_reset[HOTENDS];
#endif
#if ENABLED(PIDTEMPBED)
float Temperature::temp_iState_bed = { 0 },
Temperature::temp_dState_bed = { 0 },
Temperature::pTerm_bed,
Temperature::iTerm_bed,
Temperature::dTerm_bed,
Temperature::pid_error_bed;
#else
millis_t Temperature::next_bed_check_ms;
#endif
uint16_t Temperature::raw_temp_value[MAX_EXTRUDERS] = { 0 },
Temperature::raw_temp_bed_value = 0;
// Init min and max temp with extreme values to prevent false errors during startup
int16_t Temperature::minttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP, HEATER_3_RAW_LO_TEMP, HEATER_4_RAW_LO_TEMP),
Temperature::maxttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP, HEATER_3_RAW_HI_TEMP, HEATER_4_RAW_HI_TEMP),
Temperature::minttemp[HOTENDS] = { 0 },
Temperature::maxttemp[HOTENDS] = ARRAY_BY_HOTENDS1(16383);
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
uint8_t Temperature::consecutive_low_temperature_error[HOTENDS] = { 0 };
#endif
#ifdef MILLISECONDS_PREHEAT_TIME
millis_t Temperature::preheat_end_time[HOTENDS] = { 0 };
#endif
#ifdef BED_MINTEMP
int16_t Temperature::bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
#endif
#ifdef BED_MAXTEMP
int16_t Temperature::bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
int8_t Temperature::meas_shift_index; // Index of a delayed sample in buffer
#endif
#if HAS_AUTO_FAN
millis_t Temperature::next_auto_fan_check_ms = 0;
#endif
uint8_t Temperature::soft_pwm_amount[HOTENDS],
Temperature::soft_pwm_amount_bed;
#if ENABLED(FAN_SOFT_PWM)
uint8_t Temperature::soft_pwm_amount_fan[FAN_COUNT],
Temperature::soft_pwm_count_fan[FAN_COUNT];
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
uint16_t Temperature::current_raw_filwidth = 0; // Measured filament diameter - one extruder only
#endif
#if ENABLED(PROBING_HEATERS_OFF)
bool Temperature::paused;
#endif
#if HEATER_IDLE_HANDLER
millis_t Temperature::heater_idle_timeout_ms[HOTENDS] = { 0 };
bool Temperature::heater_idle_timeout_exceeded[HOTENDS] = { false };
#if HAS_TEMP_BED
millis_t Temperature::bed_idle_timeout_ms = 0;
bool Temperature::bed_idle_timeout_exceeded = false;
#endif
#endif
#if HAS_PID_HEATING
void Temperature::PID_autotune(float temp, int hotend, int ncycles, bool set_result/*=false*/) {
float input = 0.0;
int cycles = 0;
bool heating = true;
millis_t temp_ms = millis(), t1 = temp_ms, t2 = temp_ms;
long t_high = 0, t_low = 0;
long bias, d;
float Ku, Tu;
float workKp = 0, workKi = 0, workKd = 0;
float max = 0, min = 10000;
#if HAS_AUTO_FAN
next_auto_fan_check_ms = temp_ms + 2500UL;
#endif
if (hotend >=
#if ENABLED(PIDTEMP)
HOTENDS
#else
0
#endif
|| hotend <
#if ENABLED(PIDTEMPBED)
-1
#else
0
#endif
) {
SERIAL_ECHOLN(MSG_PID_BAD_EXTRUDER_NUM);
return;
}
SERIAL_ECHOLN(MSG_PID_AUTOTUNE_START);
disable_all_heaters(); // switch off all heaters.
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_amount_bed = bias = d = (MAX_BED_POWER) >> 1;
else
soft_pwm_amount[hotend] = bias = d = (PID_MAX) >> 1;
#elif ENABLED(PIDTEMP)
soft_pwm_amount[hotend] = bias = d = (PID_MAX) >> 1;
#else
soft_pwm_amount_bed = bias = d = (MAX_BED_POWER) >> 1;
#endif
wait_for_heatup = true;
// PID Tuning loop
while (wait_for_heatup) {
millis_t ms = millis();
if (temp_meas_ready) { // temp sample ready
updateTemperaturesFromRawValues();
input =
#if HAS_PID_FOR_BOTH
hotend < 0 ? current_temperature_bed : current_temperature[hotend]
#elif ENABLED(PIDTEMP)
current_temperature[hotend]
#else
current_temperature_bed
#endif
;
NOLESS(max, input);
NOMORE(min, input);
#if HAS_AUTO_FAN
if (ELAPSED(ms, next_auto_fan_check_ms)) {
checkExtruderAutoFans();
next_auto_fan_check_ms = ms + 2500UL;
}
#endif
if (heating && input > temp) {
if (ELAPSED(ms, t2 + 5000UL)) {
heating = false;
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_amount_bed = (bias - d) >> 1;
else
soft_pwm_amount[hotend] = (bias - d) >> 1;
#elif ENABLED(PIDTEMP)
soft_pwm_amount[hotend] = (bias - d) >> 1;
#elif ENABLED(PIDTEMPBED)
soft_pwm_amount_bed = (bias - d) >> 1;
#endif
t1 = ms;
t_high = t1 - t2;
max = temp;
}
}
if (!heating && input < temp) {
if (ELAPSED(ms, t1 + 5000UL)) {
heating = true;
t2 = ms;
t_low = t2 - t1;
if (cycles > 0) {
long max_pow =
#if HAS_PID_FOR_BOTH
hotend < 0 ? MAX_BED_POWER : PID_MAX
#elif ENABLED(PIDTEMP)
PID_MAX
#else
MAX_BED_POWER
#endif
;
bias += (d * (t_high - t_low)) / (t_low + t_high);
bias = constrain(bias, 20, max_pow - 20);
d = (bias > max_pow / 2) ? max_pow - 1 - bias : bias;
SERIAL_PROTOCOLPAIR(MSG_BIAS, bias);
SERIAL_PROTOCOLPAIR(MSG_D, d);
SERIAL_PROTOCOLPAIR(MSG_T_MIN, min);
SERIAL_PROTOCOLPAIR(MSG_T_MAX, max);
if (cycles > 2) {
Ku = (4.0 * d) / (M_PI * (max - min) * 0.5);
Tu = ((float)(t_low + t_high) * 0.001);
SERIAL_PROTOCOLPAIR(MSG_KU, Ku);
SERIAL_PROTOCOLPAIR(MSG_TU, Tu);
workKp = 0.6 * Ku;
workKi = 2 * workKp / Tu;
workKd = workKp * Tu * 0.125;
SERIAL_PROTOCOLLNPGM("\n" MSG_CLASSIC_PID);
SERIAL_PROTOCOLPAIR(MSG_KP, workKp);
SERIAL_PROTOCOLPAIR(MSG_KI, workKi);
SERIAL_PROTOCOLLNPAIR(MSG_KD, workKd);
/**
workKp = 0.33*Ku;
workKi = workKp/Tu;
workKd = workKp*Tu/3;
SERIAL_PROTOCOLLNPGM(" Some overshoot");
SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
workKp = 0.2*Ku;
workKi = 2*workKp/Tu;
workKd = workKp*Tu/3;
SERIAL_PROTOCOLLNPGM(" No overshoot");
SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
*/
}
}
#if HAS_PID_FOR_BOTH
if (hotend < 0)
soft_pwm_amount_bed = (bias + d) >> 1;
else
soft_pwm_amount[hotend] = (bias + d) >> 1;
#elif ENABLED(PIDTEMP)
soft_pwm_amount[hotend] = (bias + d) >> 1;
#else
soft_pwm_amount_bed = (bias + d) >> 1;
#endif
cycles++;
min = temp;
}
}
}
#define MAX_OVERSHOOT_PID_AUTOTUNE 20
if (input > temp + MAX_OVERSHOOT_PID_AUTOTUNE) {
SERIAL_PROTOCOLLNPGM(MSG_PID_TEMP_TOO_HIGH);
return;
}
// Every 2 seconds...
if (ELAPSED(ms, temp_ms + 2000UL)) {
#if HAS_TEMP_HOTEND || HAS_TEMP_BED
print_heaterstates();
SERIAL_EOL();
#endif
temp_ms = ms;
} // every 2 seconds
// Over 2 minutes?
if (((ms - t1) + (ms - t2)) > (10L * 60L * 1000L * 2L)) {
SERIAL_PROTOCOLLNPGM(MSG_PID_TIMEOUT);
return;
}
if (cycles > ncycles) {
SERIAL_PROTOCOLLNPGM(MSG_PID_AUTOTUNE_FINISHED);
#if HAS_PID_FOR_BOTH
const char* estring = hotend < 0 ? "bed" : "";
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kp ", workKp); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Ki ", workKi); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kd ", workKd); SERIAL_EOL();
#elif ENABLED(PIDTEMP)
SERIAL_PROTOCOLPAIR("#define DEFAULT_Kp ", workKp); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_Ki ", workKi); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_Kd ", workKd); SERIAL_EOL();
#else
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKp ", workKp); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKi ", workKi); SERIAL_EOL();
SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKd ", workKd); SERIAL_EOL();
#endif
#define _SET_BED_PID() do { \
bedKp = workKp; \
bedKi = scalePID_i(workKi); \
bedKd = scalePID_d(workKd); \
updatePID(); }while(0)
#define _SET_EXTRUDER_PID() do { \
PID_PARAM(Kp, hotend) = workKp; \
PID_PARAM(Ki, hotend) = scalePID_i(workKi); \
PID_PARAM(Kd, hotend) = scalePID_d(workKd); \
updatePID(); }while(0)
// Use the result? (As with "M303 U1")
if (set_result) {
#if HAS_PID_FOR_BOTH
if (hotend < 0)
_SET_BED_PID();
else
_SET_EXTRUDER_PID();
#elif ENABLED(PIDTEMP)
_SET_EXTRUDER_PID();
#else
_SET_BED_PID();
#endif
}
return;
}
lcd_update();
}
if (!wait_for_heatup) disable_all_heaters();
}
#endif // HAS_PID_HEATING
/**
* Class and Instance Methods
*/
Temperature::Temperature() { }
void Temperature::updatePID() {
#if ENABLED(PIDTEMP)
#if ENABLED(PID_EXTRUSION_SCALING)
last_e_position = 0;
#endif
#endif
}
int Temperature::getHeaterPower(int heater) {
return heater < 0 ? soft_pwm_amount_bed : soft_pwm_amount[heater];
}
#if HAS_AUTO_FAN
void Temperature::checkExtruderAutoFans() {
static const int8_t fanPin[] PROGMEM = { E0_AUTO_FAN_PIN, E1_AUTO_FAN_PIN, E2_AUTO_FAN_PIN, E3_AUTO_FAN_PIN, E4_AUTO_FAN_PIN };
static const uint8_t fanBit[] PROGMEM = {
0,
AUTO_1_IS_0 ? 0 : 1,
AUTO_2_IS_0 ? 0 : AUTO_2_IS_1 ? 1 : 2,
AUTO_3_IS_0 ? 0 : AUTO_3_IS_1 ? 1 : AUTO_3_IS_2 ? 2 : 3,
AUTO_4_IS_0 ? 0 : AUTO_4_IS_1 ? 1 : AUTO_4_IS_2 ? 2 : AUTO_4_IS_3 ? 3 : 4
};
uint8_t fanState = 0;
HOTEND_LOOP()
if (current_temperature[e] > EXTRUDER_AUTO_FAN_TEMPERATURE)
SBI(fanState, pgm_read_byte(&fanBit[e]));
uint8_t fanDone = 0;
for (uint8_t f = 0; f < COUNT(fanPin); f++) {
int8_t pin = pgm_read_byte(&fanPin[f]);
const uint8_t bit = pgm_read_byte(&fanBit[f]);
if (pin >= 0 && !TEST(fanDone, bit)) {
uint8_t newFanSpeed = TEST(fanState, bit) ? EXTRUDER_AUTO_FAN_SPEED : 0;
// this idiom allows both digital and PWM fan outputs (see M42 handling).
digitalWrite(pin, newFanSpeed);
analogWrite(pin, newFanSpeed);
SBI(fanDone, bit);
}
}
}
#endif // HAS_AUTO_FAN
//
// Temperature Error Handlers
//
void Temperature::_temp_error(const int8_t e, const char * const serial_msg, const char * const lcd_msg) {
static bool killed = false;
if (IsRunning()) {
SERIAL_ERROR_START();
serialprintPGM(serial_msg);
SERIAL_ERRORPGM(MSG_STOPPED_HEATER);
if (e >= 0) SERIAL_ERRORLN((int)e); else SERIAL_ERRORLNPGM(MSG_HEATER_BED);
}
#if DISABLED(BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE)
if (!killed) {
Running = false;
killed = true;
kill(lcd_msg);
}
else
disable_all_heaters(); // paranoia
#endif
}
void Temperature::max_temp_error(const int8_t e) {
#if HAS_TEMP_BED
_temp_error(e, PSTR(MSG_T_MAXTEMP), e >= 0 ? PSTR(MSG_ERR_MAXTEMP) : PSTR(MSG_ERR_MAXTEMP_BED));
#else
_temp_error(HOTEND_INDEX, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP));
#if HOTENDS == 1
UNUSED(e);
#endif
#endif
}
void Temperature::min_temp_error(const int8_t e) {
#if HAS_TEMP_BED
_temp_error(e, PSTR(MSG_T_MINTEMP), e >= 0 ? PSTR(MSG_ERR_MINTEMP) : PSTR(MSG_ERR_MINTEMP_BED));
#else
_temp_error(HOTEND_INDEX, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP));
#if HOTENDS == 1
UNUSED(e);
#endif
#endif
}
float Temperature::get_pid_output(const int8_t e) {
#if HOTENDS == 1
UNUSED(e);
#define _HOTEND_TEST true
#else
#define _HOTEND_TEST e == active_extruder
#endif
float pid_output;
#if ENABLED(PIDTEMP)
#if DISABLED(PID_OPENLOOP)
pid_error[HOTEND_INDEX] = target_temperature[HOTEND_INDEX] - current_temperature[HOTEND_INDEX];
dTerm[HOTEND_INDEX] = K2 * PID_PARAM(Kd, HOTEND_INDEX) * (current_temperature[HOTEND_INDEX] - temp_dState[HOTEND_INDEX]) + K1 * dTerm[HOTEND_INDEX];
temp_dState[HOTEND_INDEX] = current_temperature[HOTEND_INDEX];
#if HEATER_IDLE_HANDLER
if (heater_idle_timeout_exceeded[HOTEND_INDEX]) {
pid_output = 0;
pid_reset[HOTEND_INDEX] = true;
}
else
#endif
if (pid_error[HOTEND_INDEX] > PID_FUNCTIONAL_RANGE) {
pid_output = BANG_MAX;
pid_reset[HOTEND_INDEX] = true;
}
else if (pid_error[HOTEND_INDEX] < -(PID_FUNCTIONAL_RANGE) || target_temperature[HOTEND_INDEX] == 0
#if HEATER_IDLE_HANDLER
|| heater_idle_timeout_exceeded[HOTEND_INDEX]
#endif
) {
pid_output = 0;
pid_reset[HOTEND_INDEX] = true;
}
else {
if (pid_reset[HOTEND_INDEX]) {
temp_iState[HOTEND_INDEX] = 0.0;
pid_reset[HOTEND_INDEX] = false;
}
pTerm[HOTEND_INDEX] = PID_PARAM(Kp, HOTEND_INDEX) * pid_error[HOTEND_INDEX];
temp_iState[HOTEND_INDEX] += pid_error[HOTEND_INDEX];
iTerm[HOTEND_INDEX] = PID_PARAM(Ki, HOTEND_INDEX) * temp_iState[HOTEND_INDEX];
pid_output = pTerm[HOTEND_INDEX] + iTerm[HOTEND_INDEX] - dTerm[HOTEND_INDEX];
#if ENABLED(PID_EXTRUSION_SCALING)
cTerm[HOTEND_INDEX] = 0;
if (_HOTEND_TEST) {
long e_position = stepper.position(E_AXIS);
if (e_position > last_e_position) {
lpq[lpq_ptr] = e_position - last_e_position;
last_e_position = e_position;
}
else {
lpq[lpq_ptr] = 0;
}
if (++lpq_ptr >= lpq_len) lpq_ptr = 0;
cTerm[HOTEND_INDEX] = (lpq[lpq_ptr] * planner.steps_to_mm[E_AXIS]) * PID_PARAM(Kc, HOTEND_INDEX);
pid_output += cTerm[HOTEND_INDEX];
}
#endif // PID_EXTRUSION_SCALING
if (pid_output > PID_MAX) {
if (pid_error[HOTEND_INDEX] > 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
pid_output = PID_MAX;
}
else if (pid_output < 0) {
if (pid_error[HOTEND_INDEX] < 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
pid_output = 0;
}
}
#else
pid_output = constrain(target_temperature[HOTEND_INDEX], 0, PID_MAX);
#endif // PID_OPENLOOP
#if ENABLED(PID_DEBUG)
SERIAL_ECHO_START();
SERIAL_ECHOPAIR(MSG_PID_DEBUG, HOTEND_INDEX);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_INPUT, current_temperature[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_OUTPUT, pid_output);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_PTERM, pTerm[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_ITERM, iTerm[HOTEND_INDEX]);
SERIAL_ECHOPAIR(MSG_PID_DEBUG_DTERM, dTerm[HOTEND_INDEX]);
#if ENABLED(PID_EXTRUSION_SCALING)
SERIAL_ECHOPAIR(MSG_PID_DEBUG_CTERM, cTerm[HOTEND_INDEX]);
#endif
SERIAL_EOL();
#endif // PID_DEBUG
#else /* PID off */
#if HEATER_IDLE_HANDLER
if (heater_idle_timeout_exceeded[HOTEND_INDEX])
pid_output = 0;
else
#endif
pid_output = (current_temperature[HOTEND_INDEX] < target_temperature[HOTEND_INDEX]) ? PID_MAX : 0;
#endif
return pid_output;
}
#if ENABLED(PIDTEMPBED)
float Temperature::get_pid_output_bed() {
float pid_output;
#if DISABLED(PID_OPENLOOP)
pid_error_bed = target_temperature_bed - current_temperature_bed;
pTerm_bed = bedKp * pid_error_bed;
temp_iState_bed += pid_error_bed;
iTerm_bed = bedKi * temp_iState_bed;
dTerm_bed = K2 * bedKd * (current_temperature_bed - temp_dState_bed) + K1 * dTerm_bed;
temp_dState_bed = current_temperature_bed;
pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
if (pid_output > MAX_BED_POWER) {
if (pid_error_bed > 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
pid_output = MAX_BED_POWER;
}
else if (pid_output < 0) {
if (pid_error_bed < 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
pid_output = 0;
}
#else
pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
#endif // PID_OPENLOOP
#if ENABLED(PID_BED_DEBUG)
SERIAL_ECHO_START();
SERIAL_ECHOPGM(" PID_BED_DEBUG ");
SERIAL_ECHOPGM(": Input ");
SERIAL_ECHO(current_temperature_bed);
SERIAL_ECHOPGM(" Output ");
SERIAL_ECHO(pid_output);
SERIAL_ECHOPGM(" pTerm ");
SERIAL_ECHO(pTerm_bed);
SERIAL_ECHOPGM(" iTerm ");
SERIAL_ECHO(iTerm_bed);
SERIAL_ECHOPGM(" dTerm ");
SERIAL_ECHOLN(dTerm_bed);
#endif // PID_BED_DEBUG
return pid_output;
}
#endif // PIDTEMPBED
/**
* Manage heating activities for extruder hot-ends and a heated bed
* - Acquire updated temperature readings
* - Also resets the watchdog timer
* - Invoke thermal runaway protection
* - Manage extruder auto-fan
* - Apply filament width to the extrusion rate (may move)
* - Update the heated bed PID output value
*/
/**
* The following line SOMETIMES results in the dreaded "unable to find a register to spill in class 'POINTER_REGS'"
* compile error.
* thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
*
* This is due to a bug in the C++ compiler used by the Arduino IDE from 1.6.10 to at least 1.8.1.
*
* The work around is to add the compiler flag "__attribute__((__optimize__("O2")))" to the declaration for manage_heater()
*/
//void Temperature::manage_heater() __attribute__((__optimize__("O2")));
void Temperature::manage_heater() {
if (!temp_meas_ready) return;
updateTemperaturesFromRawValues(); // also resets the watchdog
#if ENABLED(HEATER_0_USES_MAX6675)
if (current_temperature[0] > min(HEATER_0_MAXTEMP, MAX6675_TMAX - 1.0)) max_temp_error(0);
if (current_temperature[0] < max(HEATER_0_MINTEMP, MAX6675_TMIN + .01)) min_temp_error(0);
#endif
#if WATCH_HOTENDS || WATCH_THE_BED || DISABLED(PIDTEMPBED) || HAS_AUTO_FAN || HEATER_IDLE_HANDLER
millis_t ms = millis();
#endif
HOTEND_LOOP() {
#if HEATER_IDLE_HANDLER
if (!heater_idle_timeout_exceeded[e] && heater_idle_timeout_ms[e] && ELAPSED(ms, heater_idle_timeout_ms[e]))
heater_idle_timeout_exceeded[e] = true;
#endif
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
// Check for thermal runaway
thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
#endif
soft_pwm_amount[e] = (current_temperature[e] > minttemp[e] || is_preheating(e)) && current_temperature[e] < maxttemp[e] ? (int)get_pid_output(e) >> 1 : 0;
#if WATCH_HOTENDS
// Make sure temperature is increasing
if (watch_heater_next_ms[e] && ELAPSED(ms, watch_heater_next_ms[e])) { // Time to check this extruder?
if (degHotend(e) < watch_target_temp[e]) // Failed to increase enough?
_temp_error(e, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
else // Start again if the target is still far off
start_watching_heater(e);
}
#endif
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
// Make sure measured temperatures are close together
if (FABS(current_temperature[0] - redundant_temperature) > MAX_REDUNDANT_TEMP_SENSOR_DIFF)
_temp_error(0, PSTR(MSG_REDUNDANCY), PSTR(MSG_ERR_REDUNDANT_TEMP));
#endif
} // HOTEND_LOOP
#if HAS_AUTO_FAN
if (ELAPSED(ms, next_auto_fan_check_ms)) { // only need to check fan state very infrequently
checkExtruderAutoFans();
next_auto_fan_check_ms = ms + 2500UL;
}
#endif
// Control the extruder rate based on the width sensor
#if ENABLED(FILAMENT_WIDTH_SENSOR)
if (filament_sensor) {
meas_shift_index = filwidth_delay_index[0] - meas_delay_cm;
if (meas_shift_index < 0) meas_shift_index += MAX_MEASUREMENT_DELAY + 1; //loop around buffer if needed
meas_shift_index = constrain(meas_shift_index, 0, MAX_MEASUREMENT_DELAY);
// Get the delayed info and add 100 to reconstitute to a percent of
// the nominal filament diameter then square it to get an area
const float vmroot = measurement_delay[meas_shift_index] * 0.01 + 1.0;
volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = vmroot <= 0.1 ? 0.01 : sq(vmroot);
}
#endif // FILAMENT_WIDTH_SENSOR
#if WATCH_THE_BED
// Make sure temperature is increasing
if (watch_bed_next_ms && ELAPSED(ms, watch_bed_next_ms)) { // Time to check the bed?
if (degBed() < watch_target_bed_temp) // Failed to increase enough?
_temp_error(-1, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
else // Start again if the target is still far off
start_watching_bed();
}
#endif // WATCH_THE_BED
#if DISABLED(PIDTEMPBED)
if (PENDING(ms, next_bed_check_ms)) return;
next_bed_check_ms = ms + BED_CHECK_INTERVAL;
#endif
#if HAS_TEMP_BED
#if HEATER_IDLE_HANDLER
if (!bed_idle_timeout_exceeded && bed_idle_timeout_ms && ELAPSED(ms, bed_idle_timeout_ms))
bed_idle_timeout_exceeded = true;
#endif
#if HAS_THERMALLY_PROTECTED_BED
thermal_runaway_protection(&thermal_runaway_bed_state_machine, &thermal_runaway_bed_timer, current_temperature_bed, target_temperature_bed, -1, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS);
#endif
#if HEATER_IDLE_HANDLER
if (bed_idle_timeout_exceeded)
{
soft_pwm_amount_bed = 0;
#if DISABLED(PIDTEMPBED)
WRITE_HEATER_BED(LOW);
#endif
}
else
#endif
{
#if ENABLED(PIDTEMPBED)
soft_pwm_amount_bed = WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP) ? (int)get_pid_output_bed() >> 1 : 0;
#elif ENABLED(BED_LIMIT_SWITCHING)
// Check if temperature is within the correct band
if (WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP)) {
if (current_temperature_bed >= target_temperature_bed + BED_HYSTERESIS)
soft_pwm_amount_bed = 0;
else if (current_temperature_bed <= target_temperature_bed - (BED_HYSTERESIS))
soft_pwm_amount_bed = MAX_BED_POWER >> 1;
}
else {
soft_pwm_amount_bed = 0;
WRITE_HEATER_BED(LOW);
}
#else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
// Check if temperature is within the correct range
if (WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP)) {
soft_pwm_amount_bed = current_temperature_bed < target_temperature_bed ? MAX_BED_POWER >> 1 : 0;
}
else {
soft_pwm_amount_bed = 0;
WRITE_HEATER_BED(LOW);
}
#endif
}
#endif // HAS_TEMP_BED
}
#define PGM_RD_W(x) (short)pgm_read_word(&x)
// Derived from RepRap FiveD extruder::getTemperature()
// For hot end temperature measurement.
float Temperature::analog2temp(int raw, uint8_t e) {
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
if (e > HOTENDS)
#else
if (e >= HOTENDS)
#endif
{
SERIAL_ERROR_START();
SERIAL_ERROR((int)e);
SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER_NUM);
kill(PSTR(MSG_KILLED));
return 0.0;
}
#if ENABLED(HEATER_0_USES_MAX6675)
if (e == 0) return 0.25 * raw;
#endif
if (heater_ttbl_map[e] != NULL) {
float celsius = 0;
uint8_t i;
short(*tt)[][2] = (short(*)[][2])(heater_ttbl_map[e]);
for (i = 1; i < heater_ttbllen_map[e]; i++) {
if (PGM_RD_W((*tt)[i][0]) > raw) {
celsius = PGM_RD_W((*tt)[i - 1][1]) +
(raw - PGM_RD_W((*tt)[i - 1][0])) *
(float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i - 1][1])) /
(float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i - 1][0]));
break;
}
}
// Overflow: Set to last value in the table
if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i - 1][1]);
return celsius;
}
return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
}
// Derived from RepRap FiveD extruder::getTemperature()
// For bed temperature measurement.
float Temperature::analog2tempBed(const int raw) {
#if ENABLED(BED_USES_THERMISTOR)
float celsius = 0;
byte i;
for (i = 1; i < BEDTEMPTABLE_LEN; i++) {
if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw) {
celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]) +
(raw - PGM_RD_W(BEDTEMPTABLE[i - 1][0])) *
(float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i - 1][1])) /
(float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i - 1][0]));
break;
}
}
// Overflow: Set to last value in the table
if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]);
return celsius;
#elif defined(BED_USES_AD595)
return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
#else
UNUSED(raw);
return 0;
#endif
}
/**
* Get the raw values into the actual temperatures.
* The raw values are created in interrupt context,
* and this function is called from normal context
* as it would block the stepper routine.
*/
void Temperature::updateTemperaturesFromRawValues() {
#if ENABLED(HEATER_0_USES_MAX6675)
current_temperature_raw[0] = read_max6675();
#endif
HOTEND_LOOP()
current_temperature[e] = Temperature::analog2temp(current_temperature_raw[e], e);
current_temperature_bed = Temperature::analog2tempBed(current_temperature_bed_raw);
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
redundant_temperature = Temperature::analog2temp(redundant_temperature_raw, 1);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
filament_width_meas = analog2widthFil();
#endif
#if ENABLED(USE_WATCHDOG)
// Reset the watchdog after we know we have a temperature measurement.
watchdog_reset();
#endif
CRITICAL_SECTION_START;
temp_meas_ready = false;
CRITICAL_SECTION_END;
}
#if ENABLED(FILAMENT_WIDTH_SENSOR)
// Convert raw Filament Width to millimeters
float Temperature::analog2widthFil() {
return current_raw_filwidth * 5.0 * (1.0 / 16383.0);
//return current_raw_filwidth;
}
// Convert raw Filament Width to a ratio
int Temperature::widthFil_to_size_ratio() {
float temp = filament_width_meas;
if (temp < MEASURED_LOWER_LIMIT) temp = filament_width_nominal; //assume sensor cut out
else NOMORE(temp, MEASURED_UPPER_LIMIT);
return filament_width_nominal / temp * 100;
}
#endif
#if ENABLED(HEATER_0_USES_MAX6675)
#ifndef MAX6675_SCK_PIN
#define MAX6675_SCK_PIN SCK_PIN
#endif
#ifndef MAX6675_DO_PIN
#define MAX6675_DO_PIN MISO_PIN
#endif
SPI<MAX6675_DO_PIN, MOSI_PIN, MAX6675_SCK_PIN> max6675_spi;
#endif
/**
* Initialize the temperature manager
* The manager is implemented by periodic calls to manage_heater()
*/
void Temperature::init() {
#if MB(RUMBA) && (TEMP_SENSOR_0 == -1 || TEMP_SENSOR_1 == -1 || TEMP_SENSOR_2 == -1 || TEMP_SENSOR_BED == -1)
// Disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
MCUCR = _BV(JTD);
MCUCR = _BV(JTD);
#endif
// Finish init of mult hotend arrays
HOTEND_LOOP() maxttemp[e] = maxttemp[0];
#if ENABLED(PIDTEMP) && ENABLED(PID_EXTRUSION_SCALING)
last_e_position = 0;
#endif
#if HAS_HEATER_0
SET_OUTPUT(HEATER_0_PIN);
#endif
#if HAS_HEATER_1
SET_OUTPUT(HEATER_1_PIN);
#endif
#if HAS_HEATER_2
SET_OUTPUT(HEATER_2_PIN);
#endif
#if HAS_HEATER_3
SET_OUTPUT(HEATER_3_PIN);
#endif
#if HAS_HEATER_4
SET_OUTPUT(HEATER_3_PIN);
#endif
#if HAS_HEATER_BED
SET_OUTPUT(HEATER_BED_PIN);
#endif
#if HAS_FAN0
SET_OUTPUT(FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#endif
#if HAS_FAN1
SET_OUTPUT(FAN1_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN1_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#endif
#if HAS_FAN2
SET_OUTPUT(FAN2_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(FAN2_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#endif
#if ENABLED(HEATER_0_USES_MAX6675)
OUT_WRITE(SCK_PIN, LOW);
OUT_WRITE(MOSI_PIN, HIGH);
SET_INPUT_PULLUP(MISO_PIN);
max6675_spi.init();
OUT_WRITE(SS_PIN, HIGH);
OUT_WRITE(MAX6675_SS, HIGH);
#endif // HEATER_0_USES_MAX6675
#ifdef DIDR2
#define ANALOG_SELECT(pin) do{ if (pin < 8) SBI(DIDR0, pin); else SBI(DIDR2, pin - 8); }while(0)
#else
#define ANALOG_SELECT(pin) do{ SBI(DIDR0, pin); }while(0)
#endif
// Set analog inputs
ADCSRA = _BV(ADEN) | _BV(ADSC) | _BV(ADIF) | 0x07;
DIDR0 = 0;
#ifdef DIDR2
DIDR2 = 0;
#endif
#if HAS_TEMP_0
ANALOG_SELECT(TEMP_0_PIN);
#endif
#if HAS_TEMP_1
ANALOG_SELECT(TEMP_1_PIN);
#endif
#if HAS_TEMP_2
ANALOG_SELECT(TEMP_2_PIN);
#endif
#if HAS_TEMP_3
ANALOG_SELECT(TEMP_3_PIN);
#endif
#if HAS_TEMP_4
ANALOG_SELECT(TEMP_4_PIN);
#endif
#if HAS_TEMP_BED
ANALOG_SELECT(TEMP_BED_PIN);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
ANALOG_SELECT(FILWIDTH_PIN);
#endif
#if HAS_AUTO_FAN_0
#if E0_AUTO_FAN_PIN == FAN1_PIN
SET_OUTPUT(E0_AUTO_FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(E0_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#else
SET_OUTPUT(E0_AUTO_FAN_PIN);
#endif
#endif
#if HAS_AUTO_FAN_1 && !AUTO_1_IS_0
#if E1_AUTO_FAN_PIN == FAN1_PIN
SET_OUTPUT(E1_AUTO_FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(E1_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#else
SET_OUTPUT(E1_AUTO_FAN_PIN);
#endif
#endif
#if HAS_AUTO_FAN_2 && !AUTO_2_IS_0 && !AUTO_2_IS_1
#if E2_AUTO_FAN_PIN == FAN1_PIN
SET_OUTPUT(E2_AUTO_FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(E2_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#else
SET_OUTPUT(E2_AUTO_FAN_PIN);
#endif
#endif
#if HAS_AUTO_FAN_3 && !AUTO_3_IS_0 && !AUTO_3_IS_1 && !AUTO_3_IS_2
#if E3_AUTO_FAN_PIN == FAN1_PIN
SET_OUTPUT(E3_AUTO_FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(E3_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#else
SET_OUTPUT(E3_AUTO_FAN_PIN);
#endif
#endif
#if HAS_AUTO_FAN_4 && !AUTO_4_IS_0 && !AUTO_4_IS_1 && !AUTO_4_IS_2 && !AUTO_4_IS_3
#if E4_AUTO_FAN_PIN == FAN1_PIN
SET_OUTPUT(E4_AUTO_FAN_PIN);
#if ENABLED(FAST_PWM_FAN)
setPwmFrequency(E4_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
#endif
#else
SET_OUTPUT(E4_AUTO_FAN_PIN);
#endif
#endif
// Use timer0 for temperature measurement
// Interleave temperature interrupt with millies interrupt
OCR0B = 128;
SBI(TIMSK0, OCIE0B);
// Wait for temperature measurement to settle
delay(250);
#define TEMP_MIN_ROUTINE(NR) \
minttemp[NR] = HEATER_ ##NR## _MINTEMP; \
while (analog2temp(minttemp_raw[NR], NR) < HEATER_ ##NR## _MINTEMP) { \
if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
minttemp_raw[NR] += OVERSAMPLENR; \
else \
minttemp_raw[NR] -= OVERSAMPLENR; \
}
#define TEMP_MAX_ROUTINE(NR) \
maxttemp[NR] = HEATER_ ##NR## _MAXTEMP; \
while (analog2temp(maxttemp_raw[NR], NR) > HEATER_ ##NR## _MAXTEMP) { \
if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
maxttemp_raw[NR] -= OVERSAMPLENR; \
else \
maxttemp_raw[NR] += OVERSAMPLENR; \
}
#ifdef HEATER_0_MINTEMP
TEMP_MIN_ROUTINE(0);
#endif
#ifdef HEATER_0_MAXTEMP
TEMP_MAX_ROUTINE(0);
#endif
#if HOTENDS > 1
#ifdef HEATER_1_MINTEMP
TEMP_MIN_ROUTINE(1);
#endif
#ifdef HEATER_1_MAXTEMP
TEMP_MAX_ROUTINE(1);
#endif
#if HOTENDS > 2
#ifdef HEATER_2_MINTEMP
TEMP_MIN_ROUTINE(2);
#endif
#ifdef HEATER_2_MAXTEMP
TEMP_MAX_ROUTINE(2);
#endif
#if HOTENDS > 3
#ifdef HEATER_3_MINTEMP
TEMP_MIN_ROUTINE(3);
#endif
#ifdef HEATER_3_MAXTEMP
TEMP_MAX_ROUTINE(3);
#endif
#if HOTENDS > 4
#ifdef HEATER_4_MINTEMP
TEMP_MIN_ROUTINE(4);
#endif
#ifdef HEATER_4_MAXTEMP
TEMP_MAX_ROUTINE(4);
#endif
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#ifdef BED_MINTEMP
while (analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
#if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
bed_minttemp_raw += OVERSAMPLENR;
#else
bed_minttemp_raw -= OVERSAMPLENR;
#endif
}
#endif // BED_MINTEMP
#ifdef BED_MAXTEMP
while (analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
#if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
bed_maxttemp_raw -= OVERSAMPLENR;
#else
bed_maxttemp_raw += OVERSAMPLENR;
#endif
}
#endif // BED_MAXTEMP
#if ENABLED(PROBING_HEATERS_OFF)
paused = false;
#endif
}
#if WATCH_HOTENDS
/**
* Start Heating Sanity Check for hotends that are below
* their target temperature by a configurable margin.
* This is called when the temperature is set. (M104, M109)
*/
void Temperature::start_watching_heater(uint8_t e) {
#if HOTENDS == 1
UNUSED(e);
#endif
if (degHotend(HOTEND_INDEX) < degTargetHotend(HOTEND_INDEX) - (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)) {
watch_target_temp[HOTEND_INDEX] = degHotend(HOTEND_INDEX) + WATCH_TEMP_INCREASE;
watch_heater_next_ms[HOTEND_INDEX] = millis() + (WATCH_TEMP_PERIOD) * 1000UL;
}
else
watch_heater_next_ms[HOTEND_INDEX] = 0;
}
#endif
#if WATCH_THE_BED
/**
* Start Heating Sanity Check for hotends that are below
* their target temperature by a configurable margin.
* This is called when the temperature is set. (M140, M190)
*/
void Temperature::start_watching_bed() {
if (degBed() < degTargetBed() - (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1)) {
watch_target_bed_temp = degBed() + WATCH_BED_TEMP_INCREASE;
watch_bed_next_ms = millis() + (WATCH_BED_TEMP_PERIOD) * 1000UL;
}
else
watch_bed_next_ms = 0;
}
#endif
#if ENABLED(THERMAL_PROTECTION_HOTENDS) || HAS_THERMALLY_PROTECTED_BED
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
Temperature::TRState Temperature::thermal_runaway_state_machine[HOTENDS] = { TRInactive };
millis_t Temperature::thermal_runaway_timer[HOTENDS] = { 0 };
#endif
#if HAS_THERMALLY_PROTECTED_BED
Temperature::TRState Temperature::thermal_runaway_bed_state_machine = TRInactive;
millis_t Temperature::thermal_runaway_bed_timer;
#endif
void Temperature::thermal_runaway_protection(Temperature::TRState* state, millis_t* timer, float current, float target, int heater_id, int period_seconds, int hysteresis_degc) {
static float tr_target_temperature[HOTENDS + 1] = { 0.0 };
/**
SERIAL_ECHO_START();
SERIAL_ECHOPGM("Thermal Thermal Runaway Running. Heater ID: ");
if (heater_id < 0) SERIAL_ECHOPGM("bed"); else SERIAL_ECHO(heater_id);
SERIAL_ECHOPAIR(" ; State:", *state);
SERIAL_ECHOPAIR(" ; Timer:", *timer);
SERIAL_ECHOPAIR(" ; Temperature:", current);
SERIAL_ECHOPAIR(" ; Target Temp:", target);
if (heater_id >= 0)
SERIAL_ECHOPAIR(" ; Idle Timeout:", heater_idle_timeout_exceeded[heater_id]);
else
SERIAL_ECHOPAIR(" ; Idle Timeout:", bed_idle_timeout_exceeded);
SERIAL_EOL();
*/
const int heater_index = heater_id >= 0 ? heater_id : HOTENDS;
#if HEATER_IDLE_HANDLER
// If the heater idle timeout expires, restart
if (heater_id >= 0 && heater_idle_timeout_exceeded[heater_id]) {
*state = TRInactive;
tr_target_temperature[heater_index] = 0;
}
#if HAS_TEMP_BED
else if (heater_id < 0 && bed_idle_timeout_exceeded) {
*state = TRInactive;
tr_target_temperature[heater_index] = 0;
}
#endif
else
#endif
// If the target temperature changes, restart
if (tr_target_temperature[heater_index] != target) {
tr_target_temperature[heater_index] = target;
*state = target > 0 ? TRFirstHeating : TRInactive;
}
switch (*state) {
// Inactive state waits for a target temperature to be set
case TRInactive: break;
// When first heating, wait for the temperature to be reached then go to Stable state
case TRFirstHeating:
if (current < tr_target_temperature[heater_index]) break;
*state = TRStable;
// While the temperature is stable watch for a bad temperature
case TRStable:
if (current >= tr_target_temperature[heater_index] - hysteresis_degc) {
*timer = millis() + period_seconds * 1000UL;
break;
}
else if (PENDING(millis(), *timer)) break;
*state = TRRunaway;
case TRRunaway:
_temp_error(heater_id, PSTR(MSG_T_THERMAL_RUNAWAY), PSTR(MSG_THERMAL_RUNAWAY));
}
}
#endif // THERMAL_PROTECTION_HOTENDS || THERMAL_PROTECTION_BED
void Temperature::disable_all_heaters() {
#if ENABLED(AUTOTEMP)
planner.autotemp_enabled = false;
#endif
HOTEND_LOOP() setTargetHotend(0, e);
setTargetBed(0);
// Unpause and reset everything
#if ENABLED(PROBING_HEATERS_OFF)
pause(false);
#endif
// If all heaters go down then for sure our print job has stopped
print_job_timer.stop();
#define DISABLE_HEATER(NR) { \
setTargetHotend(0, NR); \
soft_pwm_amount[NR] = 0; \
WRITE_HEATER_ ##NR (LOW); \
}
#if HAS_TEMP_HOTEND
DISABLE_HEATER(0);
#if HOTENDS > 1
DISABLE_HEATER(1);
#if HOTENDS > 2
DISABLE_HEATER(2);
#if HOTENDS > 3
DISABLE_HEATER(3);
#if HOTENDS > 4
DISABLE_HEATER(4);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#endif
#if HAS_TEMP_BED
target_temperature_bed = 0;
soft_pwm_amount_bed = 0;
#if HAS_HEATER_BED
WRITE_HEATER_BED(LOW);
#endif
#endif
}
#if ENABLED(PROBING_HEATERS_OFF)
void Temperature::pause(const bool p) {
if (p != paused) {
paused = p;
if (p) {
HOTEND_LOOP() start_heater_idle_timer(e, 0); // timeout immediately
#if HAS_TEMP_BED
start_bed_idle_timer(0); // timeout immediately
#endif
}
else {
HOTEND_LOOP() reset_heater_idle_timer(e);
#if HAS_TEMP_BED
reset_bed_idle_timer();
#endif
}
}
}
#endif // PROBING_HEATERS_OFF
#if ENABLED(HEATER_0_USES_MAX6675)
#define MAX6675_HEAT_INTERVAL 250u
#if ENABLED(MAX6675_IS_MAX31855)
uint32_t max6675_temp = 2000;
#define MAX6675_ERROR_MASK 7
#define MAX6675_DISCARD_BITS 18
#define MAX6675_SPEED_BITS (_BV(SPR1)) // clock ÷ 64
#else
uint16_t max6675_temp = 2000;
#define MAX6675_ERROR_MASK 4
#define MAX6675_DISCARD_BITS 3
#define MAX6675_SPEED_BITS (_BV(SPR0)) // clock ÷ 16
#endif
int Temperature::read_max6675() {
static millis_t next_max6675_ms = 0;
millis_t ms = millis();
if (PENDING(ms, next_max6675_ms)) return (int)max6675_temp;
next_max6675_ms = ms + MAX6675_HEAT_INTERVAL;
CBI(
#ifdef PRR
PRR
#elif defined(PRR0)
PRR0
#endif
, PRSPI);
SPCR = _BV(MSTR) | _BV(SPE) | MAX6675_SPEED_BITS;
WRITE(MAX6675_SS, 0); // enable TT_MAX6675
// ensure 100ns delay - a bit extra is fine
asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
// Read a big-endian temperature value
max6675_temp = 0;
for (uint8_t i = sizeof(max6675_temp); i--;) {
max6675_temp |= max6675_spi.receive();
if (i > 0) max6675_temp <<= 8; // shift left if not the last byte
}
WRITE(MAX6675_SS, 1); // disable TT_MAX6675
if (max6675_temp & MAX6675_ERROR_MASK) {
SERIAL_ERROR_START();
SERIAL_ERRORPGM("Temp measurement error! ");
#if MAX6675_ERROR_MASK == 7
SERIAL_ERRORPGM("MAX31855 ");
if (max6675_temp & 1)
SERIAL_ERRORLNPGM("Open Circuit");
else if (max6675_temp & 2)
SERIAL_ERRORLNPGM("Short to GND");
else if (max6675_temp & 4)
SERIAL_ERRORLNPGM("Short to VCC");
#else
SERIAL_ERRORLNPGM("MAX6675");
#endif
max6675_temp = MAX6675_TMAX * 4; // thermocouple open
}
else
max6675_temp >>= MAX6675_DISCARD_BITS;
#if ENABLED(MAX6675_IS_MAX31855)
// Support negative temperature
if (max6675_temp & 0x00002000) max6675_temp |= 0xFFFFC000;
#endif
return (int)max6675_temp;
}
#endif // HEATER_0_USES_MAX6675
/**
* Get raw temperatures
*/
void Temperature::set_current_temp_raw() {
#if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
current_temperature_raw[0] = raw_temp_value[0];
#endif
#if HAS_TEMP_1
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
redundant_temperature_raw = raw_temp_value[1];
#else
current_temperature_raw[1] = raw_temp_value[1];
#endif
#if HAS_TEMP_2
current_temperature_raw[2] = raw_temp_value[2];
#if HAS_TEMP_3
current_temperature_raw[3] = raw_temp_value[3];
#if HAS_TEMP_4
current_temperature_raw[4] = raw_temp_value[4];
#endif
#endif
#endif
#endif
current_temperature_bed_raw = raw_temp_bed_value;
temp_meas_ready = true;
}
#if ENABLED(PINS_DEBUGGING)
/**
* monitors endstops & Z probe for changes
*
* If a change is detected then the LED is toggled and
* a message is sent out the serial port
*
* Yes, we could miss a rapid back & forth change but
* that won't matter because this is all manual.
*
*/
void endstop_monitor() {
static uint16_t old_endstop_bits_local = 0;
static uint8_t local_LED_status = 0;
uint16_t current_endstop_bits_local = 0;
#if HAS_X_MIN
if (READ(X_MIN_PIN)) SBI(current_endstop_bits_local, X_MIN);
#endif
#if HAS_X_MAX
if (READ(X_MAX_PIN)) SBI(current_endstop_bits_local, X_MAX);
#endif
#if HAS_Y_MIN
if (READ(Y_MIN_PIN)) SBI(current_endstop_bits_local, Y_MIN);
#endif
#if HAS_Y_MAX
if (READ(Y_MAX_PIN)) SBI(current_endstop_bits_local, Y_MAX);
#endif
#if HAS_Z_MIN
if (READ(Z_MIN_PIN)) SBI(current_endstop_bits_local, Z_MIN);
#endif
#if HAS_Z_MAX
if (READ(Z_MAX_PIN)) SBI(current_endstop_bits_local, Z_MAX);
#endif
#if HAS_Z_MIN_PROBE_PIN
if (READ(Z_MIN_PROBE_PIN)) SBI(current_endstop_bits_local, Z_MIN_PROBE);
#endif
#if HAS_Z2_MIN
if (READ(Z2_MIN_PIN)) SBI(current_endstop_bits_local, Z2_MIN);
#endif
#if HAS_Z2_MAX
if (READ(Z2_MAX_PIN)) SBI(current_endstop_bits_local, Z2_MAX);
#endif
uint16_t endstop_change = current_endstop_bits_local ^ old_endstop_bits_local;
if (endstop_change) {
#if HAS_X_MIN
if (TEST(endstop_change, X_MIN)) SERIAL_PROTOCOLPAIR("X_MIN:", !!TEST(current_endstop_bits_local, X_MIN));
#endif
#if HAS_X_MAX
if (TEST(endstop_change, X_MAX)) SERIAL_PROTOCOLPAIR(" X_MAX:", !!TEST(current_endstop_bits_local, X_MAX));
#endif
#if HAS_Y_MIN
if (TEST(endstop_change, Y_MIN)) SERIAL_PROTOCOLPAIR(" Y_MIN:", !!TEST(current_endstop_bits_local, Y_MIN));
#endif
#if HAS_Y_MAX
if (TEST(endstop_change, Y_MAX)) SERIAL_PROTOCOLPAIR(" Y_MAX:", !!TEST(current_endstop_bits_local, Y_MAX));
#endif
#if HAS_Z_MIN
if (TEST(endstop_change, Z_MIN)) SERIAL_PROTOCOLPAIR(" Z_MIN:", !!TEST(current_endstop_bits_local, Z_MIN));
#endif
#if HAS_Z_MAX
if (TEST(endstop_change, Z_MAX)) SERIAL_PROTOCOLPAIR(" Z_MAX:", !!TEST(current_endstop_bits_local, Z_MAX));
#endif
#if HAS_Z_MIN_PROBE_PIN
if (TEST(endstop_change, Z_MIN_PROBE)) SERIAL_PROTOCOLPAIR(" PROBE:", !!TEST(current_endstop_bits_local, Z_MIN_PROBE));
#endif
#if HAS_Z2_MIN
if (TEST(endstop_change, Z2_MIN)) SERIAL_PROTOCOLPAIR(" Z2_MIN:", !!TEST(current_endstop_bits_local, Z2_MIN));
#endif
#if HAS_Z2_MAX
if (TEST(endstop_change, Z2_MAX)) SERIAL_PROTOCOLPAIR(" Z2_MAX:", !!TEST(current_endstop_bits_local, Z2_MAX));
#endif
SERIAL_PROTOCOLPGM("\n\n");
analogWrite(LED_PIN, local_LED_status);
local_LED_status ^= 255;
old_endstop_bits_local = current_endstop_bits_local;
}
}
#endif // PINS_DEBUGGING
/**
* Timer 0 is shared with millies so don't change the prescaler.
*
* This ISR uses the compare method so it runs at the base
* frequency (16 MHz / 64 / 256 = 976.5625 Hz), but at the TCNT0 set
* in OCR0B above (128 or halfway between OVFs).
*
* - Manage PWM to all the heaters and fan
* - Prepare or Measure one of the raw ADC sensor values
* - Check new temperature values for MIN/MAX errors (kill on error)
* - Step the babysteps value for each axis towards 0
* - For PINS_DEBUGGING, monitor and report endstop pins
* - For ENDSTOP_INTERRUPTS_FEATURE check endstops if flagged
*/
ISR(TIMER0_COMPB_vect) { Temperature::isr(); }
volatile bool Temperature::in_temp_isr = false;
void Temperature::isr() {
// The stepper ISR can interrupt this ISR. When it does it re-enables this ISR
// at the end of its run, potentially causing re-entry. This flag prevents it.
if (in_temp_isr) return;
in_temp_isr = true;
// Allow UART and stepper ISRs
CBI(TIMSK0, OCIE0B); //Disable Temperature ISR
sei();
static int8_t temp_count = -1;
static ADCSensorState adc_sensor_state = StartupDelay;
static uint8_t pwm_count = _BV(SOFT_PWM_SCALE);
// avoid multiple loads of pwm_count
uint8_t pwm_count_tmp = pwm_count;
// Static members for each heater
#if ENABLED(SLOW_PWM_HEATERS)
static uint8_t slow_pwm_count = 0;
#define ISR_STATICS(n) \
static uint8_t soft_pwm_count_ ## n, \
state_heater_ ## n = 0, \
state_timer_heater_ ## n = 0
#else
#define ISR_STATICS(n) static uint8_t soft_pwm_count_ ## n = 0
#endif
// Statics per heater
ISR_STATICS(0);
#if HOTENDS > 1
ISR_STATICS(1);
#if HOTENDS > 2
ISR_STATICS(2);
#if HOTENDS > 3
ISR_STATICS(3);
#if HOTENDS > 4
ISR_STATICS(4);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
ISR_STATICS(BED);
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
static unsigned long raw_filwidth_value = 0;
#endif
#if DISABLED(SLOW_PWM_HEATERS)
constexpr uint8_t pwm_mask =
#if ENABLED(SOFT_PWM_DITHER)
_BV(SOFT_PWM_SCALE) - 1
#else
0
#endif
;
/**
* Standard PWM modulation
*/
if (pwm_count_tmp >= 127) {
pwm_count_tmp -= 127;
soft_pwm_count_0 = (soft_pwm_count_0 & pwm_mask) + soft_pwm_amount[0];
WRITE_HEATER_0(soft_pwm_count_0 > pwm_mask ? HIGH : LOW);
#if HOTENDS > 1
soft_pwm_count_1 = (soft_pwm_count_1 & pwm_mask) + soft_pwm_amount[1];
WRITE_HEATER_1(soft_pwm_count_1 > pwm_mask ? HIGH : LOW);
#if HOTENDS > 2
soft_pwm_count_2 = (soft_pwm_count_2 & pwm_mask) + soft_pwm_amount[2];
WRITE_HEATER_2(soft_pwm_count_2 > pwm_mask ? HIGH : LOW);
#if HOTENDS > 3
soft_pwm_count_3 = (soft_pwm_count_3 & pwm_mask) + soft_pwm_amount[3];
WRITE_HEATER_3(soft_pwm_count_3 > pwm_mask ? HIGH : LOW);
#if HOTENDS > 4
soft_pwm_count_4 = (soft_pwm_count_4 & pwm_mask) + soft_pwm_amount[4];
WRITE_HEATER_4(soft_pwm_count_4 > pwm_mask ? HIGH : LOW);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
soft_pwm_count_BED = (soft_pwm_count_BED & pwm_mask) + soft_pwm_amount_bed;
WRITE_HEATER_BED(soft_pwm_count_BED > pwm_mask ? HIGH : LOW);
#endif
#if ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
soft_pwm_count_fan[0] = (soft_pwm_count_fan[0] & pwm_mask) + soft_pwm_amount_fan[0] >> 1;
WRITE_FAN(soft_pwm_count_fan[0] > pwm_mask ? HIGH : LOW);
#endif
#if HAS_FAN1
soft_pwm_count_fan[1] = (soft_pwm_count_fan[1] & pwm_mask) + soft_pwm_amount_fan[1] >> 1;
WRITE_FAN1(soft_pwm_count_fan[1] > pwm_mask ? HIGH : LOW);
#endif
#if HAS_FAN2
soft_pwm_count_fan[2] = (soft_pwm_count_fan[2] & pwm_mask) + soft_pwm_amount_fan[2] >> 1;
WRITE_FAN2(soft_pwm_count_fan[2] > pwm_mask ? HIGH : LOW);
#endif
#endif
}
else {
if (soft_pwm_count_0 <= pwm_count_tmp) WRITE_HEATER_0(0);
#if HOTENDS > 1
if (soft_pwm_count_1 <= pwm_count_tmp) WRITE_HEATER_1(0);
#if HOTENDS > 2
if (soft_pwm_count_2 <= pwm_count_tmp) WRITE_HEATER_2(0);
#if HOTENDS > 3
if (soft_pwm_count_3 <= pwm_count_tmp) WRITE_HEATER_3(0);
#if HOTENDS > 4
if (soft_pwm_count_4 <= pwm_count_tmp) WRITE_HEATER_4(0);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
if (soft_pwm_count_BED <= pwm_count_tmp) WRITE_HEATER_BED(0);
#endif
#if ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0);
#endif
#if HAS_FAN1
if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(0);
#endif
#if HAS_FAN2
if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(0);
#endif
#endif
}
// SOFT_PWM_SCALE to frequency:
//
// 0: 16000000/64/256/128 = 7.6294 Hz
// 1: / 64 = 15.2588 Hz
// 2: / 32 = 30.5176 Hz
// 3: / 16 = 61.0352 Hz
// 4: / 8 = 122.0703 Hz
// 5: / 4 = 244.1406 Hz
pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
#else // SLOW_PWM_HEATERS
/**
* SLOW PWM HEATERS
*
* For relay-driven heaters
*/
#ifndef MIN_STATE_TIME
#define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
#endif
// Macros for Slow PWM timer logic
#define _SLOW_PWM_ROUTINE(NR, src) \
soft_pwm_ ##NR = src; \
if (soft_pwm_ ##NR > 0) { \
if (state_timer_heater_ ##NR == 0) { \
if (state_heater_ ##NR == 0) state_timer_heater_ ##NR = MIN_STATE_TIME; \
state_heater_ ##NR = 1; \
WRITE_HEATER_ ##NR(1); \
} \
} \
else { \
if (state_timer_heater_ ##NR == 0) { \
if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
state_heater_ ##NR = 0; \
WRITE_HEATER_ ##NR(0); \
} \
}
#define SLOW_PWM_ROUTINE(n) _SLOW_PWM_ROUTINE(n, soft_pwm_amount[n])
#define PWM_OFF_ROUTINE(NR) \
if (soft_pwm_ ##NR < slow_pwm_count) { \
if (state_timer_heater_ ##NR == 0) { \
if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
state_heater_ ##NR = 0; \
WRITE_HEATER_ ##NR (0); \
} \
}
if (slow_pwm_count == 0) {
SLOW_PWM_ROUTINE(0);
#if HOTENDS > 1
SLOW_PWM_ROUTINE(1);
#if HOTENDS > 2
SLOW_PWM_ROUTINE(2);
#if HOTENDS > 3
SLOW_PWM_ROUTINE(3);
#if HOTENDS > 4
SLOW_PWM_ROUTINE(4);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
_SLOW_PWM_ROUTINE(BED, soft_pwm_amount_bed); // BED
#endif
} // slow_pwm_count == 0
PWM_OFF_ROUTINE(0);
#if HOTENDS > 1
PWM_OFF_ROUTINE(1);
#if HOTENDS > 2
PWM_OFF_ROUTINE(2);
#if HOTENDS > 3
PWM_OFF_ROUTINE(3);
#if HOTENDS > 4
PWM_OFF_ROUTINE(4);
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
PWM_OFF_ROUTINE(BED); // BED
#endif
#if ENABLED(FAN_SOFT_PWM)
if (pwm_count_tmp >= 127) {
pwm_count_tmp = 0;
#if HAS_FAN0
soft_pwm_count_fan[0] = soft_pwm_amount_fan[0] >> 1;
WRITE_FAN(soft_pwm_count_fan[0] > 0 ? HIGH : LOW);
#endif
#if HAS_FAN1
soft_pwm_count_fan[1] = soft_pwm_amount_fan[1] >> 1;
WRITE_FAN1(soft_pwm_count_fan[1] > 0 ? HIGH : LOW);
#endif
#if HAS_FAN2
soft_pwm_count_fan[2] = soft_pwm_amount_fan[2] >> 1;
WRITE_FAN2(soft_pwm_count_fan[2] > 0 ? HIGH : LOW);
#endif
}
#if HAS_FAN0
if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0);
#endif
#if HAS_FAN1
if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(0);
#endif
#if HAS_FAN2
if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(0);
#endif
#endif // FAN_SOFT_PWM
// SOFT_PWM_SCALE to frequency:
//
// 0: 16000000/64/256/128 = 7.6294 Hz
// 1: / 64 = 15.2588 Hz
// 2: / 32 = 30.5176 Hz
// 3: / 16 = 61.0352 Hz
// 4: / 8 = 122.0703 Hz
// 5: / 4 = 244.1406 Hz
pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
// increment slow_pwm_count only every 64th pwm_count,
// i.e. yielding a PWM frequency of 16/128 Hz (8s).
if (((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0) {
slow_pwm_count++;
slow_pwm_count &= 0x7F;
if (state_timer_heater_0 > 0) state_timer_heater_0--;
#if HOTENDS > 1
if (state_timer_heater_1 > 0) state_timer_heater_1--;
#if HOTENDS > 2
if (state_timer_heater_2 > 0) state_timer_heater_2--;
#if HOTENDS > 3
if (state_timer_heater_3 > 0) state_timer_heater_3--;
#if HOTENDS > 4
if (state_timer_heater_4 > 0) state_timer_heater_4--;
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#if HAS_HEATER_BED
if (state_timer_heater_BED > 0) state_timer_heater_BED--;
#endif
} // ((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0
#endif // SLOW_PWM_HEATERS
//
// Update lcd buttons 488 times per second
//
static bool do_buttons;
if ((do_buttons ^= true)) lcd_buttons_update();
/**
* One sensor is sampled on every other call of the ISR.
* Each sensor is read 16 (OVERSAMPLENR) times, taking the average.
*
* On each Prepare pass, ADC is started for a sensor pin.
* On the next pass, the ADC value is read and accumulated.
*
* This gives each ADC 0.9765ms to charge up.
*/
#define SET_ADMUX_ADCSRA(pin) ADMUX = _BV(REFS0) | (pin & 0x07); SBI(ADCSRA, ADSC)
#ifdef MUX5
#define START_ADC(pin) if (pin > 7) ADCSRB = _BV(MUX5); else ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
#else
#define START_ADC(pin) ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
#endif
switch (adc_sensor_state) {
case SensorsReady: {
// All sensors have been read. Stay in this state for a few
// ISRs to save on calls to temp update/checking code below.
constexpr int8_t extra_loops = MIN_ADC_ISR_LOOPS - (int8_t)SensorsReady;
static uint8_t delay_count = 0;
if (extra_loops > 0) {
if (delay_count == 0) delay_count = extra_loops; // Init this delay
if (--delay_count) // While delaying...
adc_sensor_state = (ADCSensorState)(int(SensorsReady) - 1); // retain this state (else, next state will be 0)
break;
}
else
adc_sensor_state = (ADCSensorState)0; // Fall-through to start first sensor now
}
#if HAS_TEMP_0
case PrepareTemp_0:
START_ADC(TEMP_0_PIN);
break;
case MeasureTemp_0:
raw_temp_value[0] += ADC;
break;
#endif
#if HAS_TEMP_BED
case PrepareTemp_BED:
START_ADC(TEMP_BED_PIN);
break;
case MeasureTemp_BED:
raw_temp_bed_value += ADC;
break;
#endif
#if HAS_TEMP_1
case PrepareTemp_1:
START_ADC(TEMP_1_PIN);
break;
case MeasureTemp_1:
raw_temp_value[1] += ADC;
break;
#endif
#if HAS_TEMP_2
case PrepareTemp_2:
START_ADC(TEMP_2_PIN);
break;
case MeasureTemp_2:
raw_temp_value[2] += ADC;
break;
#endif
#if HAS_TEMP_3
case PrepareTemp_3:
START_ADC(TEMP_3_PIN);
break;
case MeasureTemp_3:
raw_temp_value[3] += ADC;
break;
#endif
#if HAS_TEMP_4
case PrepareTemp_4:
START_ADC(TEMP_4_PIN);
break;
case MeasureTemp_4:
raw_temp_value[4] += ADC;
break;
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
case Prepare_FILWIDTH:
START_ADC(FILWIDTH_PIN);
break;
case Measure_FILWIDTH:
if (ADC > 102) { // Make sure ADC is reading > 0.5 volts, otherwise don't read.
raw_filwidth_value -= (raw_filwidth_value >> 7); // Subtract 1/128th of the raw_filwidth_value
raw_filwidth_value += ((unsigned long)ADC << 7); // Add new ADC reading, scaled by 128
}
break;
#endif
case StartupDelay: break;
} // switch(adc_sensor_state)
if (!adc_sensor_state && ++temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms.
temp_count = 0;
// Update the raw values if they've been read. Else we could be updating them during reading.
if (!temp_meas_ready) set_current_temp_raw();
// Filament Sensor - can be read any time since IIR filtering is used
#if ENABLED(FILAMENT_WIDTH_SENSOR)
current_raw_filwidth = raw_filwidth_value >> 10; // Divide to get to 0-16384 range since we used 1/128 IIR filter approach
#endif
ZERO(raw_temp_value);
raw_temp_bed_value = 0;
#define TEMPDIR(N) ((HEATER_##N##_RAW_LO_TEMP) > (HEATER_##N##_RAW_HI_TEMP) ? -1 : 1)
int constexpr temp_dir[] = {
#if ENABLED(HEATER_0_USES_MAX6675)
0
#else
TEMPDIR(0)
#endif
#if HOTENDS > 1
, TEMPDIR(1)
#if HOTENDS > 2
, TEMPDIR(2)
#if HOTENDS > 3
, TEMPDIR(3)
#if HOTENDS > 4
, TEMPDIR(4)
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
};
for (uint8_t e = 0; e < COUNT(temp_dir); e++) {
const int16_t tdir = temp_dir[e], rawtemp = current_temperature_raw[e] * tdir;
if (rawtemp > maxttemp_raw[e] * tdir && target_temperature[e] > 0) max_temp_error(e);
if (rawtemp < minttemp_raw[e] * tdir && !is_preheating(e) && target_temperature[e] > 0) {
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
if (++consecutive_low_temperature_error[e] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
#endif
min_temp_error(e);
}
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
else
consecutive_low_temperature_error[e] = 0;
#endif
}
#if HAS_TEMP_BED
#if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
#define GEBED <=
#else
#define GEBED >=
#endif
if (current_temperature_bed_raw GEBED bed_maxttemp_raw && target_temperature_bed > 0) max_temp_error(-1);
if (bed_minttemp_raw GEBED current_temperature_bed_raw && target_temperature_bed > 0) min_temp_error(-1);
#endif
} // temp_count >= OVERSAMPLENR
// Go to the next state, up to SensorsReady
adc_sensor_state = (ADCSensorState)((int(adc_sensor_state) + 1) % int(StartupDelay));
#if ENABLED(BABYSTEPPING)
LOOP_XYZ(axis) {
const int curTodo = babystepsTodo[axis]; // get rid of volatile for performance
if (curTodo > 0) {
stepper.babystep((AxisEnum)axis, /*fwd*/true);
babystepsTodo[axis]--;
}
else if (curTodo < 0) {
stepper.babystep((AxisEnum)axis, /*fwd*/false);
babystepsTodo[axis]++;
}
}
#endif // BABYSTEPPING
#if ENABLED(PINS_DEBUGGING)
extern bool endstop_monitor_flag;
// run the endstop monitor at 15Hz
static uint8_t endstop_monitor_count = 16; // offset this check from the others
if (endstop_monitor_flag) {
endstop_monitor_count += _BV(1); // 15 Hz
endstop_monitor_count &= 0x7F;
if (!endstop_monitor_count) endstop_monitor(); // report changes in endstop status
}
#endif
#if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
extern volatile uint8_t e_hit;
if (e_hit && ENDSTOPS_ENABLED) {
endstops.update(); // call endstop update routine
e_hit--;
}
#endif
cli();
in_temp_isr = false;
SBI(TIMSK0, OCIE0B); //re-enable Temperature ISR
}
| gpl-3.0 |
jgeboski/Insomnia | app/src/main/java/com/github/jgeboski/insomnia/service/MainThread.java | 3693 | /*
* Copyright 2015 James Geboski <jgeboski@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.jgeboski.insomnia.service;
import java.util.List;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import com.github.jgeboski.insomnia.Insomnia;
import com.github.jgeboski.insomnia.Log;
import com.github.jgeboski.insomnia.Util;
import com.github.jgeboski.insomnia.model.AppItem;
public class MainThread
extends Thread
{
public static final long TIMEOUT_MAX =
/* The maximum time supported by Android */
(((long) Integer.MAX_VALUE) * 1000) - 1;
public MainService service;
public boolean running;
public WakeLock block;
public WakeLock dlock;
public MainThread(MainService service)
{
this.service = service;
this.running = false;
PowerManager pm = (PowerManager)
service.getSystemService(Context.POWER_SERVICE);
int appid = service.getApplicationInfo().labelRes;
String tag = service.getString(appid);
block = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag);
dlock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, tag);
}
@Override
public void run()
{
long timeout;
running = true;
Log.info("Service thread started");
while (running) {
if (Util.isScreenOn(service)) {
List<AppItem> items = service.getRunningAppItems();
timeout = Insomnia.getTimeout(items, service.timeout);
if (!items.isEmpty()) {
acquireLock();
} else {
releaseLock();
}
} else {
timeout = TIMEOUT_MAX;
releaseLock();
}
try {
Log.debug("Sleeping for %d ms", timeout);
sleep(timeout);
} catch (InterruptedException e) {
}
}
Log.info("Service thread stopped");
}
public void reset()
{
if (isAlive()) {
interrupt();
}
}
public void close()
{
if (!isAlive()) {
return;
}
running = false;
interrupt();
try {
join();
} catch (InterruptedException e) {
}
releaseLock();
}
private void acquireLock()
{
if (!service.dimmable && !block.isHeld()) {
releaseLock();
Log.info("Acquiring bright wake lock");
block.acquire();
} else if (service.dimmable && !dlock.isHeld()) {
releaseLock();
Log.info("Acquiring dim wake lock");
dlock.acquire();
}
}
private void releaseLock()
{
if (block.isHeld()) {
Log.info("Releasing bright wake lock");
block.release();
}
if (dlock.isHeld()) {
Log.info("Releasing dim wake lock");
dlock.release();
}
}
}
| gpl-3.0 |
RoederProjects/promeda | src/core/bricks/Store.java | 46 | package core.bricks;
public class Store {
}
| gpl-3.0 |
MorellatoAriel/PyGobstones | interpreter/vxgbs/lang/gbs_constructs.py | 9943 | #
# Copyright (C) 2011, 2012 Pablo Barenbaum <foones@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""Definition of program constructs, used in the lint step.
A program construct is any kind of value that an
identifier might take, such as "user-defined function"
or "built-in constant".
"""
import common.i18n as i18n
import common.position
class ProgramConstruct(object):
"""Base class to represent Gobstones constructs, such as constants,
variables, functions and procedures.
"""
def __init__(self, name):
self._name = name
def name(self):
"Returns the name of this construct."
return self._name
def where(self):
"""Returns a string, describing the place where this construct is
defined.
"""
return 'at unknown place'
def area(self):
"""Returns a program area indicating the place where this construct is
defined.
"""
return common.position.ProgramArea()
def underlying_construct(self):
"Returns the original construct (used for renames/aliases)."
return self
class RenameConstruct(ProgramConstruct):
"Represents a construct which is an alias for another one."
def __init__(self, new_name, value):
self._name = new_name
self._value = value
def underlying_construct(self):
"Returns the original construct, for which this one is an alias."
return self._value
## Construct kinds (callable and atomic)
class CallableConstruct(ProgramConstruct):
"Represents a construct that can be called (function or procedure)."
def kind(self):
"Returns the kind of this construct."
return 'callable'
def num_params(self):
"Returns the number of arguments of this construct."
return len(self.params())
class EntryPointConstruct(ProgramConstruct):
"""Represents a construct that cannot be called (entrypoint)"""
def kind(self):
"Returns the kind of this construct."
return 'entrypoint'
class AtomicConstruct(ProgramConstruct):
"""Represents an atomic construct, which is not a collection
and cannot be called.
"""
def kind(self):
"Returns the kind of this construct."
return 'atomic'
## Construct types (procedure, function, constant and variable)
class ProgramEntryPoint(EntryPointConstruct):
"""Represents a Gobstones program block"""
def type(self):
"Returns the type of this construct."
return 'program'
class InteractiveEntryPoint(EntryPointConstruct):
"""Represents a Gobstones interactive program block"""
def type(self):
"Returns the type of this construct."
return 'interactive'
class Procedure(CallableConstruct):
"Represents a Gobstones procedure."
def type(self):
"Returns the type of this construct."
return 'procedure'
class Function(CallableConstruct):
"Represents a Gobstones function."
def type(self):
"Returns the type of this construct."
return 'function'
class Constant(AtomicConstruct):
"Represents a Gobstones constant."
def type(self):
"Returns the type of this construct."
return 'constant'
class Variable(AtomicConstruct):
"Represents a Gobstones variable."
def type(self):
"Returns the type of this construct."
return 'variable'
class Type(AtomicConstruct):
"Represents a Gobstones Type"
def type(self):
"Returns the type of this construct"
return 'type'
##
class Builtin(ProgramConstruct):
"Represents a builtin construct, defined by the Gobstones runtime."
def __init__(self, name, gbstype, primitive):
ProgramConstruct.__init__(self, name)
self._gbstype = gbstype
self._primitive = primitive
def gbstype(self):
"Returns the Gobstones type of this construct."
return self._gbstype
def where(self):
"""Returns a string, describing the place where this construct is
defined.
"""
return i18n.i18n('as a built-in')
def is_builtin(self):
"""Returns True iff this construct is a builtin. (Builtin constructs
always return True).
"""
return True
def primitive(self):
"Returns the denotated value of this construct."
return self._primitive
class BuiltinType(Builtin, Type):
def __init__(self, name, gbstype):
super(BuiltinType, self).__init__(name, gbstype, gbstype)
class BuiltinCallable(Builtin):
"""Represents a callable builtin construct, a procedure or function
defined by the Gobstones runtime.
"""
def __init__(self, name, gbstype, primitive):
Builtin.__init__(self, name, gbstype, primitive)
self._params = [repr(p).lower() for p in gbstype.parameters()]
def params(self):
"""Return a list of parameter names for this builtin callable
construct. The names are taken from its types. E.g.: Poner(color).
"""
return self._params
class BuiltinProcedure(BuiltinCallable, Procedure):
"Represents a builtin procedure."
pass
class BuiltinFunction(BuiltinCallable, Function):
"Represents a builtin function."
def __init__(self, name, gbstype, primitive):
BuiltinCallable.__init__(self, name, gbstype, primitive)
self._nretvals = len(gbstype.result())
def num_retvals(self):
"Returns the number of values that this function returns."
return self._nretvals
class BuiltinConstant(Builtin, Constant):
"Represents a builtin constant."
pass
##
class UserConstruct(ProgramConstruct):
"Represents a user-defined construct."
def __init__(self, name, tree):
ProgramConstruct.__init__(self, name)
self._tree = tree
def tree(self):
"""Returns the AST corresponding to this user-defined construct's
definition."""
return self._tree
def where(self):
"""Returns a string, describing the place where this construct is
defined.
"""
return i18n.i18n('at %s') % (self._tree.pos_begin.file_row_col(),)
def area(self):
"""Returns a program area indicating the place where this user-defined
construct is defined.
"""
return common.position.ProgramAreaNear(self._tree)
def is_builtin(self):
"""Returns True iff this construct is a builtin. (User defined
constructs always return False).
"""
return False
class UserEntryPoint(UserConstruct):
"Represents a user-defined entrypoint construct."
def identifier(self):
return self.tree().children[1]
class UserProgramEntryPoint(UserEntryPoint, ProgramEntryPoint):
"Represents a user-defined program entrypoint."
pass
class UserInteractiveEntryPoint(UserEntryPoint, ProgramEntryPoint):
"Represents a user-defined interactive program entrypoint."
pass
class UserCallable(UserConstruct):
"Represents a user-defined callable construct."
def params(self):
"""Return a list of parameter names for this user-defined callable
construct. The names are taken from the callable construct's source code.
"""
return [p.value for p in self.tree().children[2].children]
def identifier(self):
return self.tree().children[1]
class UserProcedure(UserCallable, Procedure):
"Represents a user-defined procedure."
pass
class UserFunction(UserCallable, Function):
"Represents a user-defined function."
def num_retvals(self):
"""Returns the number of values that this user-defined function
returns.
"""
body = self.tree().children[3]
return_clause = body.children[-1]
tup = return_clause.children[1]
return len(tup.children)
class UserVariable(UserConstruct, Variable):
"Represents a user-defined variable."
def identifier(self):
return self.tree()
class UserType(UserConstruct, Type):
"Represents a user-defined type."
def identifier(self):
return self.tree().children[1]
class UserParameter(UserVariable):
"Represents a parameter in a user-defined routine."
def type(self):
"Returns the type of this construct."
return 'parameter'
class UserIndex(UserVariable):
"Represents an index in a repeatWith, repeat or foreach."
def type(self):
"Returns the type of this construct."
return 'index'
## Compiled constructs
class UserCompiledConstruct(ProgramConstruct):
"Represents a compiled construct."
def __init__(self, name):
ProgramConstruct.__init__(self, name)
def is_builtin(self):
"""Returns True iff this construct is a builtin. (Compiled
constructs always return False).
"""
return False
class UserCompiledCallable(ProgramConstruct):
"Represents a compiled callable construct."
def __init__(self, name, params):
ProgramConstruct.__init__(self, name)
self._params = params
def params(self):
"Return the list of names of this compiled callable construct."
return self._params
class UserCompiledProcedure(UserCompiledCallable, Procedure):
"Represents a compiled callable procedure."
pass
class UserCompiledFunction(UserCompiledCallable, Function):
"Represents a compiled callable function."
pass
class UserCompiledEntrypoint(UserCompiledConstruct, UserEntryPoint):
"Represents a compiled entrypoint."
pass | gpl-3.0 |
redhataccess/rhi-pool | insights/test.py | 3837 | import logging
import unittest
from datetime import datetime
import os
import sys
from insights.configs import settings
from insights.ui.browser import browser
from insights.ui.configuration import Configuration
from insights.ui.header import Header
from insights.ui.login import Login
from insights.ui.overview import Overview
from insights.ui.inventory import Inventory
from insights.ui.actions import Actions
from insights.ui.planner import Planner
from insights.ui.rules import Rules
from insights.configs.base import get_project_root
LOGGER = logging.getLogger(__name__)
class TestCase(unittest.TestCase):
"""Insights Test Case."""
@classmethod
def setUpClass(cls):
super(TestCase, cls).setUpClass()
if not settings.configured:
settings.configure()
cls.insights_user = settings.rhn_login.rhn_username
cls.insights_password = settings.rhn_login.rhn_password
@classmethod
def tearDownClass(cls):
logging.info("In teardown class")
def setUp(self):
LOGGER.info("Started test : ")
def tearDown(self):
LOGGER.info("Finished test : ")
class UITestCase(TestCase):
"""Insights UI Test Case."""
@classmethod
def setUpClass(cls):
super(UITestCase, cls).setUpClass()
cls.driver_name = settings.webdriver
cls.driver_binary = settings.webdriver_binary
cls.server_name = settings.rhn_login.base_url
@classmethod
def tearDownClass(cls):
super(UITestCase, cls).tearDownClass()
def setUp(self):
super(UITestCase, self).setUp()
self.browser = browser()
self.addCleanup(self.browser.quit)
self.browser.maximize_window()
self.browser.get(settings.rhn_login.base_url)
self.addCleanup(self.take_screenshot)
#Library methods
self.login = Login(self.browser)
self.overview = Overview(self.browser)
self.inventory = Inventory(self.browser)
self.actions = Actions(self.browser)
self.planner = Planner(self.browser)
self.configuration = Configuration(self.browser)
self.rules = Rules(self.browser)
self.header = Header(self.browser)
def take_screenshot(self):
"""Take screen shot from the current browser window.
The screenshot named ``screenshot-YYYY-mm-dd_HH_MM_SS.png`` will be
placed on the path specified by
``settings.screenshots_path/YYYY-mm-dd/ClassName-method_name-``.
All directories will be created if they don't exist. Make sure that the
user running insights have the right permissions to create files and
directories matching the complete.
"""
if sys.exc_info()[0]:
# Take screenshot if any exception is raised and the test method is
# not in the skipped tests.
now = datetime.now()
if not settings.screenshots_path:
#Screenshots will be saved at project root path
path = os.path.join(
get_project_root(),
'screenshots',
now.strftime('%Y-%m-%d'),
)
else:
#Screenshots will be saved at specified location in pool.conf
path = os.path.join(
settings.screenshots_path,
now.strftime('%Y-%m-%d'),
)
if not os.path.exists(path):
os.makedirs(path)
filename = '{0}-{1}-screenshot-{2}.png'.format(
type(self).__name__,
self._testMethodName,
now.strftime('%Y-%m-%d_%H_%M_%S')
)
path = os.path.join(path, filename)
LOGGER.debug('Saving screenshot %s', path)
self.browser.save_screenshot(path)
| gpl-3.0 |
VosDerrick/Volsteria | src/main/java/slimeknights/tconstruct/shared/block/BlockLiquidSlime.java | 2564 | package slimeknights.tconstruct.shared.block;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLiving;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import java.util.Random;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.smeltery.block.BlockTinkerFluid;
import slimeknights.tconstruct.world.TinkerWorld;
public class BlockLiquidSlime extends BlockTinkerFluid {
public BlockLiquidSlime(Fluid fluid, Material material) {
super(fluid, material);
}
@Override
public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) {
int oldLevel = state.getValue(LEVEL);
super.updateTick(world, pos, state, rand);
// no fluid update but flowing?
if(oldLevel > 0 && oldLevel == state.getValue(LEVEL)) {
if(rand.nextFloat() > 0.6f) {
// only if they have dirt below them
Block blockDown = world.getBlockState(pos.down()).getBlock();
if(blockDown == Blocks.DIRT) {
// check if the block we flowed from has slimedirt below it and move the slime with us!
for(EnumFacing dir : EnumFacing.HORIZONTALS) {
IBlockState state2 = world.getBlockState(pos.offset(dir));
// same block and a higher flow
if(state2.getBlock() == this && state2.getValue(LEVEL) == state.getValue(LEVEL) - 1) {
IBlockState dirt = world.getBlockState(pos.offset(dir).down());
if(dirt.getBlock() == TinkerWorld.slimeDirt) {
// we got a block we flowed from and the block we flowed from has slimedirt below
// change the dirt below us to slimedirt too
world.setBlockState(pos.down(), dirt);
}
if(dirt.getBlock() == TinkerWorld.slimeGrass) {
world.setBlockState(pos.down(), TinkerWorld.slimeGrass.getDirtState(dirt));
}
}
}
}
}
world.scheduleBlockUpdate(pos, this, 400 + rand.nextInt(200), 0);
}
}
@Override
public boolean canCreatureSpawn(@Nonnull IBlockState state, @Nonnull IBlockAccess world, @Nonnull BlockPos pos, EntityLiving.SpawnPlacementType type) {
return type == EntityLiving.SpawnPlacementType.IN_WATER || super.canCreatureSpawn(state, world, pos, type);
}
}
| gpl-3.0 |
triguero/Keel3.0 | src/keel/Algorithms/UnsupervisedLearning/AssociationRules/IntervalRuleLearning/Alatasetal/Alatasetal.java | 10402 | /***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
package keel.Algorithms.UnsupervisedLearning.AssociationRules.IntervalRuleLearning.Alatasetal;
/**
* <p>
* @author Written by Alberto Fernández (University of Granada)
* @author Modified by Nicolò Flugy Papè (Politecnico di Milano) 24/03/2009
* @author Modified by Diana Martín (dmartin@ceis.cujae.edu.cu)
* @version 1.1
* @since JDK1.6
* </p>
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.core.*;
import keel.Dataset.*;
public class Alatasetal {
/**
* <p>
* It gathers all the parameters, launches the algorithm, and prints out the results
* </p>
*/
private myDataset trans;
private String rulesFilename;
private String valuesFilename;
String valuesOrderFilename;
private AlatasetalProcess proc;
private ArrayList<AssociationRule> associationRules;
private String fileTime, fileHora, namedataset;
private int nTrials;
private int randomChromosomes;
private int r;
private int tournamentSize;
private double pc;
private double pmMin;
private double pmMax;
private double a1;
private double a2;
private double a3;
private double a4;
private double a5;
private double af;
private double minSupport;
long startTime, totalTime;
private boolean somethingWrong = false; //to check if everything is correct.
/**
* Default constructor
*/
public Alatasetal() {
}
/**
* It reads the data from the input files and parse all the parameters from the parameters array
* @param parameters It contains the input files, output files and parameters
*/
public Alatasetal(parseParameters parameters) {
this.startTime = System.currentTimeMillis();
this.trans = new myDataset();
try {
this.namedataset = parameters.getTransactionsInputFile();
System.out.println("\nReading the transaction set: " + parameters.getTransactionsInputFile());
trans.readDataSet( parameters.getTransactionsInputFile() );
}
catch (IOException e) {
System.err.println("There was a problem while reading the input transaction set: " + e);
somethingWrong = true;
}
//We may check if there are some numerical attributes, because our algorithm may not handle them:
//somethingWrong = somethingWrong || train.hasNumericalAttributes();
this.somethingWrong = this.somethingWrong || this.trans.hasMissingAttributes();
this.rulesFilename = parameters.getAssociationRulesFile();
this.valuesFilename = parameters.getOutputFile(0);
this.valuesOrderFilename = parameters.getOutputFile(1);
this.fileTime = (parameters.getOutputFile(0)).substring(0,(parameters.getOutputFile(0)).lastIndexOf('/')) + "/time.txt";
this.fileHora = (parameters.getOutputFile(0)).substring(0,(parameters.getOutputFile(0)).lastIndexOf('/')) + "/hora.txt";
long seed = Long.parseLong(parameters.getParameter(0));
this.nTrials = Integer.parseInt( parameters.getParameter(1) );
this.randomChromosomes = Integer.parseInt( parameters.getParameter(2) );
int r = Integer.parseInt( parameters.getParameter(3) );
this.tournamentSize = Integer.parseInt( parameters.getParameter(4) );
this.pc = Double.parseDouble( parameters.getParameter(5) );
this.pmMin = Double.parseDouble( parameters.getParameter(6) );
this.pmMax = Double.parseDouble( parameters.getParameter(7) );
this.a1 = Double.parseDouble( parameters.getParameter(8) );
this.a2 = Double.parseDouble( parameters.getParameter(9) );
this.a3 = Double.parseDouble( parameters.getParameter(10) );
this.a4 = Double.parseDouble( parameters.getParameter(11) );
this.a5 = Double.parseDouble( parameters.getParameter(12) );
this.af = Double.parseDouble( parameters.getParameter(13) );
this.minSupport = 0.001;
this.r = (this.trans.getnVars() >= r) ? r : this.trans.getnVars();
Randomize.setSeed(seed);
}
/**
* It launches the algorithm
*/
public void execute() {
if (somethingWrong) { //We do not execute the program
System.err.println("An error was found");
System.err.println("Aborting the program");
//We should not use the statement: System.exit(-1);
}
else {
this.proc = new AlatasetalProcess(this.trans, this.nTrials, this.randomChromosomes, this.r, this.tournamentSize, this.pc, this.pmMin, this.pmMax, this.a1, this.a2, this.a3, this.a4, this.a5, this.af);
this.proc.run();
this.associationRules = this.proc.generateRulesSet(this.minSupport);// we do not use minConfidence
try {
int r, i;
AssociationRule a_r;
Gene[] terms;
ArrayList<Integer> id_attrs;
PrintWriter rules_writer = new PrintWriter(this.rulesFilename);
PrintWriter values_writer = new PrintWriter(this.valuesFilename);
PrintWriter valueOrder_writer = new PrintWriter(this.valuesOrderFilename);
rules_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
rules_writer.println("<association_rules>");
values_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
values_writer.println("<values>");
valueOrder_writer.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
valueOrder_writer.println("<values>");
for (r=0; r < this.associationRules.size(); r++) {
a_r = this.associationRules.get(r);
rules_writer.println("<rule id=\"" + r + "\">");
values_writer.println("<rule id=\"" + r + "\" rule_support=\"" + AlatasetalProcess.roundDouble(a_r.getSupport(),2) + "\" antecedent_support=\"" + AlatasetalProcess.roundDouble(a_r.getAntecedentSupport(),2) + "\" consequent_support=\"" + AlatasetalProcess.roundDouble(a_r.getConsequentSupport(),2)
+ "\" confidence=\"" + AlatasetalProcess.roundDouble(a_r.getConfidence(),2) +"\" lift=\"" + AlatasetalProcess.roundDouble(a_r.getLift(),2) + "\" conviction=\"" + AlatasetalProcess.roundDouble(a_r.getConv(),2) + "\" certainFactor=\"" + AlatasetalProcess.roundDouble(a_r.getCF(),2) + "\" netConf=\"" + AlatasetalProcess.roundDouble(a_r.getnetConf(),2) + "\" yulesQ=\"" + AlatasetalProcess.roundDouble(a_r.getyulesQ(),2) + "\" nAttributes=\"" + (a_r.getAntecedents().length + a_r.getConsequents().length) + "\"/>");
rules_writer.println("<antecedents>");
terms = a_r.getAntecedents();
id_attrs = a_r.getIdOfAntecedents();
for (i=0; i < terms.length; i++)
createRule(terms[i], id_attrs.get(i), rules_writer);
rules_writer.println("</antecedents>");
rules_writer.println("<consequents>");
terms = a_r.getConsequents();
id_attrs = a_r.getIdOfConsequents();
for (i=0; i < terms.length; i++)
createRule(terms[i], id_attrs.get(i), rules_writer);
rules_writer.println("</consequents>");
rules_writer.println("</rule>");
}
rules_writer.println("</association_rules>");
values_writer.println("</values>");
this.proc.saveReport(this.associationRules, values_writer);
rules_writer.close();
values_writer.close();
valueOrder_writer.print(this.proc.printRules(this.associationRules));
valueOrder_writer.println("</values>");
valueOrder_writer.close();
totalTime = System.currentTimeMillis() - startTime;
this.writeTime();
System.out.println("Algorithm Finished");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
public void writeTime() {
long seg, min, hor;
String stringOut = new String("");
stringOut = "" + totalTime / 1000 + " " + this.namedataset + rulesFilename + "\n";
Files.addToFile(this.fileTime, stringOut);
totalTime /= 1000;
seg = totalTime % 60;
totalTime /= 60;
min = totalTime % 60;
hor = totalTime / 60;
stringOut = "";
if (hor < 10) stringOut = stringOut + "0"+ hor + ":";
else stringOut = stringOut + hor + ":";
if (min < 10) stringOut = stringOut + "0"+ min + ":";
else stringOut = stringOut + min + ":";
if (seg < 10) stringOut = stringOut + "0"+ seg;
else stringOut = stringOut + seg;
stringOut = stringOut + " " + rulesFilename + "\n";
Files.addToFile(this.fileHora, stringOut);
}
private void createRule(Gene g, int id_attr, PrintWriter w) {
w.println("<attribute name=\"" + Attributes.getAttribute(id_attr).getName() + "\" value=\"");
if (! g.getIsPositiveInterval()) w.print("NOT ");
if ( trans.getAttributeType(id_attr) == myDataset.NOMINAL ) w.print(Attributes.getAttribute(id_attr).getNominalValue( (int)g.getLowerBound() ));
else w.print("[" + g.getLowerBound() + ", " + g.getUpperBound() + "]");
w.print("\" />");
}
}
| gpl-3.0 |
TheLanguageArchive/lamus2 | wicket/src/main/java/nl/mpi/lamus/web/components/UploadPanel.java | 10680 | /*
* Copyright (C) 2013 Max Planck Institute for Psycholinguistics
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.mpi.lamus.web.components;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipInputStream;
import nl.mpi.lamus.archive.implementation.LamusArchiveFileHelper;
import nl.mpi.lamus.exception.DisallowedPathException;
import nl.mpi.lamus.exception.WorkspaceException;
import nl.mpi.lamus.service.WorkspaceService;
import nl.mpi.lamus.web.pages.LamusPage;
import nl.mpi.lamus.web.session.LamusSession;
import nl.mpi.lamus.workspace.importing.implementation.FileImportProblem;
import nl.mpi.lamus.workspace.model.Workspace;
import nl.mpi.lamus.workspace.importing.implementation.ImportProblem;
import nl.mpi.lamus.workspace.importing.implementation.LinkImportProblem;
import nl.mpi.lamus.workspace.importing.implementation.MatchImportProblem;
import nl.mpi.lamus.workspace.upload.implementation.ZipUploadResult;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadProgressBar;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Panel where the file upload activity will take place.
* @author guisil
*/
public class UploadPanel extends FeedbackPanelAwarePanel<Workspace> {
private static final Logger log = LoggerFactory.getLogger(UploadPanel.class);
public static final PackageResourceReference DELETE_IMAGE_RESOURCE_REFERENCE = new PackageResourceReference(LamusPage.class, "delete.gif");
@SpringBean
private WorkspaceService workspaceService;
private final IModel<Workspace> model;
public UploadPanel(String id, IModel<Workspace> model, FeedbackPanel feedbackPanel) {
super(id, model, feedbackPanel);
this.model = model;
// Add upload form with progress bar that uses HTML <input type="file" multiple />, so it can upload
// more than one file in browsers which support "multiple" attribute
final FileUploadForm progressUploadForm = new FileUploadForm("progressUpload");
progressUploadForm.add(new UploadProgressBar("progress", progressUploadForm,
progressUploadForm.fileUploadField));
add(progressUploadForm);
}
private class FileUploadForm extends Form<Void> {
FileUploadField fileUploadField;
FileUploadForm(String name) {
super(name);
// set this form to multipart mode (allways needed for uploads!)
setMultiPart(true);
// Add one file input field
add(fileUploadField = new FileUploadField("fileInput"));
add(new AutoDisablingAjaxButton("uploadButton", this) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
target.add(getFeedbackPanel());
final List<FileUpload> uploads = fileUploadField.getFileUploads();
if (uploads != null) {
File uploadDirectory = workspaceService.getWorkspaceUploadDirectory(model.getObject().getWorkspaceID());
Collection<File> copiedFiles = new ArrayList<>();
Collection<ImportProblem> uploadProblems = new ArrayList<>();
int failedUploadsCount = 0;
for (FileUpload upload : uploads) {
// Create a new file
File newFile = new File(uploadDirectory, upload.getClientFileName());
if (newFile.isDirectory()) {
continue;
} else {
LamusArchiveFileHelper lah = new LamusArchiveFileHelper();
newFile = lah.getFinalFile(uploadDirectory, upload.getClientFileName());
}
if (newFile.getName().endsWith(".zip")) {
try {
InputStream newInputStream = upload.getInputStream();
try (ZipInputStream zipInputStream = new ZipInputStream(newInputStream)) {
ZipUploadResult zipUploadResults =
workspaceService.uploadZipFileIntoWorkspace(LamusSession.get().getUserId(), model.getObject().getWorkspaceID(), zipInputStream, newFile.getName());
copiedFiles.addAll(zipUploadResults.getSuccessfulUploads());
uploadProblems.addAll(zipUploadResults.getFailedUploads());
failedUploadsCount += uploadProblems.size();
}
} catch (IOException | DisallowedPathException ex) {
UploadPanel.this.error(ex.getMessage());
}
} else {
try {
if(newFile.exists()) {
uploadProblems.add(new FileImportProblem(newFile, "Uploaded file with the same path already exists.", null));
failedUploadsCount++;
continue;
}
File tempCopiedFile =
workspaceService.uploadFileIntoWorkspace(LamusSession.get().getUserId(), model.getObject().getWorkspaceID(), upload.getInputStream(), newFile.getName());
copiedFiles.add(tempCopiedFile);
} catch (IOException | DisallowedPathException ex) {
UploadPanel.this.error(ex.getMessage());
}
}
}
if(copiedFiles.isEmpty() && uploadProblems.isEmpty()) {
UploadPanel.this.info(getLocalizer().getString("upload_panel_no_files", this));
return;
}
try {
uploadProblems.addAll(workspaceService.processUploadedFiles(LamusSession.get().getUserId(), model.getObject().getWorkspaceID(), copiedFiles));
int failedLinksCount = 0;
for (ImportProblem problem : uploadProblems) {
UploadPanel.this.error("Problem with upload: " + problem.getErrorMessage());
if(problem instanceof FileImportProblem) {
failedUploadsCount++;
} else if(problem instanceof LinkImportProblem || problem instanceof MatchImportProblem) {
failedLinksCount++;
}
}
StringBuilder feedbackMessage = new StringBuilder();
if (uploadProblems.isEmpty() && !copiedFiles.isEmpty()) {
feedbackMessage.append(getLocalizer().getString("upload_panel_success_message", this));
feedbackMessage.append(getLocalizer().getString("upload_panel_total_successful_files", this));
feedbackMessage.append(copiedFiles.size());
UploadPanel.this.info(feedbackMessage.toString());
}
if (!uploadProblems.isEmpty()) {
feedbackMessage.append(getLocalizer().getString("upload_panel_fail_message", this));
if(failedUploadsCount != 0) {
feedbackMessage.append(getLocalizer().getString("upload_panel_total_failed_files", this));
feedbackMessage.append(failedUploadsCount);
feedbackMessage.append("; ");
}
if(failedLinksCount != 0) {
feedbackMessage.append(getLocalizer().getString("upload_panel_total_failed_links", this));
feedbackMessage.append(failedLinksCount);
feedbackMessage.append("; ");
}
feedbackMessage.append(getLocalizer().getString("upload_panel_total_successful_files", this));
feedbackMessage.append(copiedFiles.size() - failedUploadsCount);
UploadPanel.this.error(feedbackMessage.toString());
}
} catch (WorkspaceException ex) {
UploadPanel.this.error(ex.getMessage());
}
}
}
});
}
}
}
| gpl-3.0 |
oboudou/railisa_beta | consultation/urls.py | 159 | from django.conf.urls import url, include
from .views import ValueListView
urlpatterns = [
url(r'^list$', ValueListView.as_view(), name='value_list'),
]
| gpl-3.0 |
adrexia/mahara | htdocs/lib/mahara.php | 143071 | <?php
/**
*
* @package mahara
* @subpackage core
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
* @copyright (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
*/
defined('INTERNAL') || die();
/**
* work around silly php settings
* and broken setup stuff about the install
* and raise a warning/fail depending on severity
*/
function ensure_sanity() {
// PHP version
$phpversionrequired = '5.3.0';
if (version_compare(phpversion(), $phpversionrequired) < 0) {
throw new ConfigSanityException(get_string('phpversion', 'error', $phpversionrequired));
}
// Various required extensions
if (!extension_loaded('json')) {
throw new ConfigSanityException(get_string('jsonextensionnotloaded', 'error'));
}
switch (get_config('dbtype')) {
case 'postgres':
case 'postgres8': // for legacy purposes we also accept "postgres8"
if (!extension_loaded('pgsql')) {
throw new ConfigSanityException(get_string('pgsqldbextensionnotloaded', 'error'));
}
break;
case 'mysql':
case 'mysql5': // for legacy purposes we also accept "mysql5"
if (!extension_loaded('mysqli') && !extension_loaded('mysql')) {
throw new ConfigSanityException(get_string('mysqldbextensionnotloaded', 'error'));
}
break;
default:
throw new ConfigSanityException(get_string('unknowndbtype', 'error'));
}
if (!extension_loaded('xml')) {
throw new ConfigSanityException(get_string('xmlextensionnotloaded', 'error', 'xml'));
}
if (!extension_loaded('libxml')) {
throw new ConfigSanityException(get_string('xmlextensionnotloaded', 'error', 'libxml'));
}
if (!extension_loaded('gd')) {
throw new ConfigSanityException(get_string('gdextensionnotloaded', 'error'));
}
if (!extension_loaded('session')) {
throw new ConfigSanityException(get_string('sessionextensionnotloaded', 'error'));
}
if(!extension_loaded('curl')) {
throw new ConfigSanityException(get_string('curllibrarynotinstalled', 'error'));
}
if (!extension_loaded('dom')) {
throw new ConfigSanityException(get_string('domextensionnotloaded', 'error'));
}
// Check for freetype in the gd extension
$gd_info = gd_info();
if (!$gd_info['FreeType Support']) {
throw new ConfigSanityException(get_string('gdfreetypenotloaded', 'error'));
}
// register globals workaround
if (ini_get_bool('register_globals')) {
$massivearray = array_keys(array_merge($_POST, $_GET, $_COOKIE, $_SERVER, $_REQUEST, $_FILES));
foreach ($massivearray as $tounset) {
unset($GLOBALS[$tounset]);
}
}
// magic_quotes_gpc workaround
if (!defined('CRON') && ini_get_bool('magic_quotes_gpc')) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
$servervars = array('REQUEST_URI','QUERY_STRING','HTTP_REFERER','PATH_INFO','PHP_SELF','PATH_TRANSLATED');
foreach ($servervars as $tocheck) {
if (array_key_exists($tocheck,$_SERVER) && !empty($_SERVER[$tocheck])) {
$_SERVER[$tocheck] = stripslashes($_SERVER[$tocheck]);
}
}
}
if (ini_get_bool('magic_quotes_runtime')) {
// Turn of magic_quotes_runtime. Anyone with this on deserves a slap in the face
set_magic_quotes_runtime(0);
}
if (ini_get_bool('magic_quotes_sybase')) {
// See above comment re. magic_quotes_runtime
@ini_set('magic_quotes_sybase', 0);
}
if (ini_get_bool('safe_mode')) {
// We don't run with safe mode
throw new ConfigSanityException(get_string('safemodeon', 'error'));
}
if ('0' === ini_get('apc.stat') or 'off' === ini_get('apc.stat')) {
// We don't run with apc.stat=0 (see https://bugs.launchpad.net/mahara/+bug/548333)
throw new ConfigSanityException(get_string('apcstatoff', 'error'));
}
// Other things that might be worth checking:
// memory limit
// file_uploads (off|on)
// upload_max_filesize
// allow_url_fopen (only if we use this)
//
// dataroot inside document root.
if (strpos(get_config('dataroot'), get_config('docroot')) !== false) {
throw new ConfigSanityException(get_string('datarootinsidedocroot', 'error'));
}
// dataroot not writable..
if (!check_dir_exists(get_config('dataroot')) || !is_writable(get_config('dataroot'))) {
$message = get_string('datarootnotwritable', 'error', get_config('dataroot'));
if ($openbasedir = ini_get('open_basedir')) {
$message .= "\n(" . get_string('openbasedirenabled', 'error') . ' '
. get_string('openbasedirpaths', 'error', htmlspecialchars($openbasedir)) // hsc() is not defined yet
. ')';
}
throw new ConfigSanityException($message);
}
if (
!check_dir_exists(get_config('dataroot') . 'smarty/compile') ||
!check_dir_exists(get_config('dataroot') . 'smarty/cache') ||
!check_dir_exists(get_config('dataroot') . 'temp') ||
!check_dir_exists(get_config('dataroot') . 'langpacks') ||
!check_dir_exists(get_config('dataroot') . 'htmlpurifier') ||
!check_dir_exists(get_config('dataroot') . 'log') ||
!check_dir_exists(get_config('dataroot') . 'images')) {
throw new ConfigSanityException(get_string('couldnotmakedatadirectories', 'error'));
}
// Since sessionpath can now exist outside of the the dataroot, check it separately.
// NOTE: If we implement separate session handlers, we may want to remove or alter this check
if (!check_dir_exists(get_config('sessionpath')) || !is_writable(get_config('sessionpath'))) {
throw new ConfigSanityException(get_string('sessionpathnotwritable', 'error', get_config('sessionpath')));
}
raise_memory_limit('128M');
}
/**
* Check sanity of things that we only check at installation time - not on
* every request, like ensure_sanity() does
*/
function ensure_install_sanity() {
// Must must must be a UTF8 database!
if (!db_is_utf8()) {
throw new ConfigSanityException(get_string('dbnotutf8', 'error'));
}
if (is_postgres() && !postgres_create_language('plpgsql')) {
throw new ConfigSanityException(get_string('plpgsqlnotavailable', 'error'));
}
if (is_mysql() && !mysql_has_trigger_privilege()) {
throw new ConfigSanityException(get_string('mysqlnotriggerprivilege', 'error'));
}
}
function ensure_upgrade_sanity() {
// Check column collation is equal to the default
if (is_mysql()) {
require_once('ddl.php');
if (table_exists(new XMLDBTable('event_type'))) {
if (!column_collation_is_default('event_type', 'name')) {
throw new ConfigSanityException(get_string('dbcollationmismatch', 'admin'));
}
}
if (!mysql_has_trigger_privilege()) {
throw new ConfigSanityException(get_string('mysqlnotriggerprivilege', 'error'));
}
}
if (is_postgres() && !postgres_create_language('plpgsql')) {
throw new ConfigSanityException(get_string('plpgsqlnotavailable', 'error'));
}
}
/**
* Upgrade/Install the specified mahara components
*
* @param array $upgrades The list of components to install or upgrade
* @return void
*/
function upgrade_mahara($upgrades) {
if (isset($upgrades['firstcoredata']) && $upgrades['firstcoredata']) {
$install = true;
}
else {
$install = false;
}
uksort($upgrades, 'sort_upgrades');
foreach ($upgrades as $name => $data) {
if ($name == 'settings') {
continue;
}
if ($install) {
log_info(get_string('installingplugin', 'admin', $name));
}
else {
log_info(get_string('upgradingplugin', 'admin', $name));
}
if ($name == 'firstcoredata' || $name == 'lastcoredata') {
$funname = 'core_install_' . $name . '_defaults';
$funname();
continue;
}
else if ($install && $name == 'localpreinst') {
$name(array('localdata' => true));
}
else if ($install && $name == 'localpostinst') {
// Update local version
$config = new StdClass;
require(get_config('docroot') . 'local/version.php');
set_config('localversion', $config->version);
set_config('localrelease', $config->release);
// Installation is finished
set_config('installed', true);
log_info('Installation complete.');
}
else {
if ($name == 'core') {
$funname = 'upgrade_core';
}
else if ($name == 'local') {
$funname = 'upgrade_local';
}
else {
$funname = 'upgrade_plugin';
}
$data->name = $name;
$funname($data);
}
}
}
/**
* Check to see if the internal plugins are installed. Die if they are not.
*/
function ensure_internal_plugins_exist() {
// Internal things installed
if (get_config('installed')) {
foreach (plugin_types() as $type) {
if (!record_exists($type . '_installed', 'name', 'internal')) {
throw new ConfigSanityException(get_string($type . 'notinstalled'));
}
}
}
}
function get_string($identifier, $section='mahara') {
$variables = func_get_args();
if (count($variables) > 2) { // we have some stuff we need to sprintf
array_shift($variables);
array_shift($variables); //shift off the first two.
}
else {
$variables = array();
}
return get_string_location($identifier, $section, $variables);
}
function get_string_from_language($lang, $identifier, $section='mahara') {
$variables = func_get_args();
if (count($variables) > 3) { // we have some stuff we need to sprintf
array_shift($variables);
array_shift($variables);
array_shift($variables); //shift off the first three.
}
else {
$variables = array();
}
return get_string_location($identifier, $section, $variables, 'format_langstring', $lang);
}
function get_helpfile($plugintype, $pluginname, $form, $element, $page=null, $section=null) {
if ($langfile = get_helpfile_location($plugintype, $pluginname, $form, $element, $page, $section)) {
return file_get_contents($langfile);
}
return false;
}
function get_helpfile_location($plugintype, $pluginname, $form, $element, $page=null, $section=null) {
$subdir = 'help/';
if ($page) {
$pagebits = explode('-', $page);
$file = array_pop($pagebits) . '.html';
if ($plugintype != 'core') {
$subdir .= 'pages/' . join('/', $pagebits) . '/';
}
else {
$subdir .= 'pages/' . $pluginname . '/' . join('/', $pagebits) . '/';
}
}
else if ($section) {
$subdir .= 'sections/';
$file = $section . '.html';
}
else if (!empty($form) && !empty($element)) {
$subdir .= 'forms/';
$file = $form . '.' . $element . '.html';
}
else if (!empty($form) && empty($element)) {
$subdir .= 'forms/';
$file = $form . '.html';
}
else {
return false;
}
// now we have to try and locate the help file
$lang = current_language();
if ($lang == 'en.utf8') {
$trieden = true;
}
else {
$trieden = false;
}
//try the local settings
$langfile = get_config('docroot') . 'local/lang/' . $lang . '/' . $subdir;
if ($plugintype != 'core') {
$langfile .= $plugintype . '.' . $pluginname . '.' . $file;
}
else {
$langfile .= $file;
}
if (is_readable($langfile)) {
return $langfile;
}
if ($plugintype == 'blocktype') { // these are a bit of a special case
$bits = explode('/', $pluginname);
if (count($bits) == 2) {
$location = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1] . '/lang/';
}
else {
try {
if ($artefactplugin = blocktype_artefactplugin($pluginname)) {
$location = 'artefact/' . $artefactplugin . '/blocktype/' . $pluginname . '/lang/';
}
else {
$location = 'blocktype/' . $pluginname . '/lang/';
}
}
catch (SQLException $e) {
if (get_config('installed')) {
throw $e;
}
}
}
}
else if ($plugintype != 'core') {
$location = $plugintype . '/' . $pluginname . '/lang/';
}
else {
$location = 'lang/';
}
// try the current language
$langfile = get_language_root() . $location . $lang . '/' . $subdir . $file;
if (is_readable($langfile)) {
return $langfile;
}
// if it's not found, try the parent language if there is one...
if (empty($data) && empty($trieden)) {
$langfile = get_language_root($lang) . 'lang/' . $lang . '/langconfig.php';
if ($parentlang = get_string_from_file('parentlanguage', $langfile)) {
if ($parentlang == 'en.utf8') {
$trieden = true;
}
$langfile = get_language_root($parentlang) . $location . $parentlang . '/' . $subdir . $file;
if (is_readable($langfile)) {
return $langfile;
}
}
}
// if it's STILL not found, and we haven't already tried english ...
if (empty($data) && empty($trieden)) {
$langfile = get_language_root('en.utf8') . $location . 'en.utf8/' . $subdir . $file;
if (is_readable($langfile)) {
return $langfile;
}
}
// if it's a form element, try the wildcard form name
if (!empty($form) && !empty($element) && $form !== 'ANY') {
// if it's a block instance config form element, try the wildcard form name
// and element without it's prefixes
if (preg_match('/^instconf_/', $element)) {
$element = end(explode('_', $element));
}
return get_helpfile_location('core', '', 'ANY', $element, $page, $section);
}
return false;
}
// get a string without sprintfing it.
function get_raw_string($identifier, $section='mahara') {
// For a raw string we don't want to format any arguments using
// sprintf, so the replace function passed to get_string_location
// should just return the first argument and ignore the second.
return get_string_location($identifier, $section, array(), 'raw_langstring');
}
/**
* This function gets a language string identified by $identifier from
* an appropriate location, and formats the string and any arguments
* in $variables using the function $replacefunc.
*
* @param string $identifier
* @param string $section
* @param array $variables
* @param function $replacefunc
* @return string
*/
function get_string_location($identifier, $section, $variables, $replacefunc='format_langstring', $lang='') {
$langconfigstrs = array('parentlanguage', 'thislanguage');
if ($section == 'mahara' &&
(in_array($identifier, $langconfigstrs)
|| strpos($identifier, 'strftime') === 0
|| strpos($identifier, 'strfday') === 0)) {
$section = 'langconfig';
}
if (empty($lang)) {
$lang = current_language();
}
// Define the locations of language strings for this section
$langstringroot = get_language_root($lang);
$docroot = get_config('docroot');
$langdirectory = ''; // The directory in which the language file for this string should ideally reside, if the language has implemented it
if (false === strpos($section, '.')) {
$langdirectory = 'lang/';
}
else {
$extras = plugin_types();
$extras[] = 'theme'; // Allow themes to have lang files the same as plugins
foreach ($extras as $tocheck) {
if (strpos($section, $tocheck . '.') === 0) {
$pluginname = substr($section ,strlen($tocheck) + 1);
if ($tocheck == 'blocktype' &&
strpos($pluginname, '/') !== false) { // it belongs to an artefact plugin
$bits = explode('/', $pluginname);
$langdirectory = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1] . '/lang/';
$section = 'blocktype.' . $bits[1];
}
else {
$langdirectory = $tocheck . '/' . $pluginname . '/lang/';
}
}
}
}
// First check the theme/plugin locations
$result = get_string_local($docroot . $langdirectory, $lang . '/' . $section . '.php', $identifier);
if ($result !== false) {
return $replacefunc($result, $variables, $lang);
}
// Then check the default location for the string in the current language
$result = get_string_local($langstringroot . $langdirectory, $lang . '/' . $section . '.php', $identifier);
if ($result !== false) {
return $replacefunc($result, $variables, $lang);
}
// If the preferred language was English (utf8) we can abort now
// saving some checks beacuse it's the only "root" lang
if ($lang == 'en.utf8') {
return '[[' . $identifier . '/' . $section . ']]';
}
// Is a parent language defined? If so, try to find this string in a parent language file
$langfile = $langstringroot . 'lang/' . $lang . '/langconfig.php';
if (is_readable($langfile)) {
if ($parentlang = get_string_from_file('parentlanguage', $langfile)) {
// First check the theme/plugin locations
$result = get_string_local($docroot . $langdirectory, $parentlang . '/' . $section . '.php', $identifier);
if ($result !== false) {
return $replacefunc($result, $variables, $parentlang);
}
// Then check the default location for the string in the current language
$result = get_string_local(get_language_root($parentlang) . $langdirectory, $parentlang . '/' . $section . '.php', $identifier);
if ($result !== false) {
return $replacefunc($result, $variables, $parentlang);
}
}
}
/// Our only remaining option is to try English
$result = get_string_local(get_config('docroot') . $langdirectory, 'en.utf8/' . $section . '.php', $identifier);
if ($result !== false) {
return $replacefunc($result, $variables);
}
return '[[' . $identifier . '/' . $section . ']]'; // Last resort
}
/**
* Get string from a file, checking the appropriate local customisation directory first
*
*/
function get_string_local($langpath, $langfile, $identifier) {
foreach (array(get_config('docroot') . 'local/lang/', $langpath) as $dir) {
$file = $dir . $langfile;
if (is_readable($file)) {
$result = get_string_from_file($identifier, $file);
if ($result !== false) {
return $result;
}
}
}
return false;
}
/**
* Return a list of available languages
*
*/
function get_languages() {
static $langs = array();
if (!$langs) {
foreach (language_get_searchpaths() as $searchpath) {
$langbase = $searchpath . 'lang/';
if ($langdir = @opendir($langbase)) {
while (false !== ($subdir = readdir($langdir))) {
if (preg_match('/\.utf8$/', $subdir) && is_dir($langbase . $subdir)) {
$langfile = $langbase . $subdir . '/langconfig.php';
if (is_readable($langfile)) {
if ($langname = get_string_from_file('thislanguage', $langfile)) {
$langs[$subdir] = $langname;
}
}
}
}
closedir($langdir);
asort($langs);
}
else {
log_warn('Unable to read language directory ' . $langbase);
}
}
}
return $langs;
}
/**
* Returns whether the given language is installed/available for use
*/
function language_installed($lang) {
foreach (language_get_searchpaths() as $searchpath) {
if (is_readable($searchpath . 'lang/' . $lang . '/langconfig.php')) {
return true;
}
}
return false;
}
/**
* Returns a list of directories in which to search for language packs.
*
* This is influenced by the configuration variable 'langpacksearchpaths'
*/
function language_get_searchpaths() {
static $searchpaths = array();
if (!$searchpaths) {
// Construct the search path
$docrootpath = array(get_config('docroot'));
// Paths to language files in dataroot
$datarootbase = get_config('dataroot') . 'langpacks/*';
$datarootpaths = glob($datarootbase, GLOB_MARK | GLOB_ONLYDIR);
if ($datarootpaths === false) {
log_warn("Problem searching for langfiles at this path: " . $datarootbase);
$datarootpaths = array();
}
// langpacksearchpaths configuration variable - for experts :)
$lpsearchpaths = (array)get_config('langpacksearchpaths');
$langpacksearchpaths = array();
foreach ($lpsearchpaths as $path) {
if (is_dir($path)) {
$langpacksearchpaths[] = (substr($path, -1) == '/') ? $path : "$path/";
}
else {
log_warn("Path in langpacksearchpaths is not a directory: $path");
}
}
$searchpaths = array_merge($docrootpath, $datarootpaths, $langpacksearchpaths);
}
return $searchpaths;
}
/**
* Get the directory in which the specified language pack resides.
*
* Defaults to getting the directory for the current_language() - i.e. the
* language the user is using
*
* Returns null if the language can't be found
*
* @param string $language The language to look for
*/
function get_language_root($language=null) {
static $language_root_cache = array();
if (!isset($language_root_cache[$language])) {
if ($language == null) {
$language = current_language();
}
foreach (language_get_searchpaths() as $path) {
if (is_dir("$path/lang/$language")) {
return $language_root_cache[$language] = $path;
}
}
// Oh noes, can't be found
$language_root_cache[$language] = null;
}
return $language_root_cache[$language];
}
/**
* Return a list of all available themes.
* @return array subdir => name
*/
function get_all_themes() {
static $themes = null;
if (is_null($themes)) {
$themes = array();
$themelist = get_all_theme_objects();
foreach ($themelist AS $subdir => $theme) {
$themes[$subdir] = isset($theme->displayname) ? $theme->displayname : $subdir;
}
}
return $themes;
}
/**
* Return a list of themes available to this user
* If the user is a member of any institutions, only themes available to
* those institutions are returned; or
* If a user is not a member of any institution, all themes not marked as
* institution specific are returned.
* @return array subdir => name
*/
function get_user_accessible_themes() {
global $USER;
$themes = array();
if ($institutions = $USER->get('institutions')) {
// Get themes for all of this users institutions
foreach ($institutions AS $i) {
$themes = array_merge($themes, get_institution_themes($i->institution));
}
}
else {
$themelist = get_all_theme_objects();
foreach ($themelist AS $subdir => $theme) {
if (!isset($theme->institutions) || !is_array($theme->institutions)) {
$themes[$subdir] = isset($theme->displayname) ? $theme->displayname : $subdir;
}
}
}
$themes = array_merge(array('sitedefault' => get_string('nothemeselected', 'view')), $themes);
unset($themes['custom']);
return $themes;
}
/**
* Return a list of themes available to the specified institution
* @param string institution the name of the institution to load themes for
* @return array subdir => name
* @throws SystemException if unable to read the theme directory
*/
function get_institution_themes($institution) {
static $institutionthemes = array();
if (!isset($institutionthemes[$institution])) {
$themes = get_all_theme_objects();
$r = array();
foreach ($themes AS $subdir => $theme) {
if (empty($theme->institutions) || !is_array($theme->institutions) || in_array($institution, $theme->institutions)) {
$r[$subdir] = isset($theme->displayname) ? $theme->displayname : $subdir;
}
}
$institutionthemes[$institution] = $r;
}
return $institutionthemes[$institution];
}
/**
* Return a list of all themes available on the system
* @return array An array of theme objects
* @throws SystemException if unable to read the theme directory
*/
function get_all_theme_objects() {
static $themes = null;
if (is_null($themes)) {
$themes = array();
$themebase = get_config('docroot') . 'theme/';
if (!$themedir = opendir($themebase)) {
throw new SystemException('Unable to read theme directory '.$themebase);
}
while (false !== ($subdir = readdir($themedir))) {
if (substr($subdir, 0, 1) != "." && is_dir($themebase . $subdir)) {
// is the theme directory name valid?
if (!Theme::name_is_valid($subdir)) {
log_warn(get_string('themenameinvalid', 'error', $subdir));
} else {
$config_path = $themebase . $subdir . '/themeconfig.php';
if (is_readable($config_path)) {
require($config_path);
if (empty($theme->disabled) || !$theme->disabled) {
$themes[$subdir] = $theme;
}
}
}
}
}
closedir($themedir);
asort($themes);
}
return $themes;
}
/**
* This function is only used from {@link get_string()}.
*
* @internal Only used from get_string, not meant to be public API
* @param string $identifier ?
* @param string $langfile ?
* @param string $destination ?
* @return string|false ?
* @staticvar array $strings Localized strings
* @access private
* @todo Finish documenting this function.
*/
function get_string_from_file($identifier, $langfile) {
static $strings; // Keep the strings cached in memory.
if (empty($strings[$langfile])) {
$string = array();
include ($langfile);
$strings[$langfile] = $string;
} else {
$string = &$strings[$langfile];
}
if (!isset ($string[$identifier])) {
return false;
}
return $string[$identifier];
}
/**
* This function makes the return value of ini_get consistent if you are
* setting server directives through the .htaccess file in apache.
* Current behavior for value set from php.ini On = 1, Off = [blank]
* Current behavior for value set from .htaccess On = On, Off = Off
* Contributed by jdell @ unr.edu
*
* @param string $ini_get_arg setting to look for
* @return bool
*/
function ini_get_bool($ini_get_arg) {
$temp = ini_get($ini_get_arg);
if ($temp == '1' or strtolower($temp) == 'on') {
return true;
}
return false;
}
/**
* This function loads up the basic $CFG
* from the database table
* note that it doesn't load plugin config
* as not every page needs them
* @return boolean false if the assignment fails (generally if the databse is not installed)
*/
function load_config() {
global $CFG;
global $OVERRIDDEN; // array containing the config fields overridden by $CFG
// Get a full list of overridden fields
foreach ($CFG as $field => $value) {
$OVERRIDDEN[] = $field;
}
$dbconfig = get_records_array('config', '', '', '', 'field, value');
foreach ($dbconfig as $cfg) {
if (!isset($CFG->{$cfg->field})) {
$CFG->{$cfg->field} = $cfg->value;
}
}
return true;
}
/**
* This function returns a value from $CFG
* or null if it is not found
*
* @param string $key config setting to look for
* @return mixed
*/
function get_config($key) {
global $CFG;
if (isset($CFG->$key)) {
return $CFG->$key;
}
return null;
}
/**
* This function sets a config variable
* both in $CFG and in the database
*
* @param string $key config field to set
* @param string $value config value
*/
function set_config($key, $value) {
global $CFG;
db_ignore_sql_exceptions(true);
if (get_record('config', 'field', $key)) {
if (set_field('config', 'value', $value, 'field', $key)) {
$status = true;
}
}
else {
$config = new StdClass;
$config->field = $key;
$config->value = $value;
$status = insert_record('config', $config);
}
db_ignore_sql_exceptions(false);
if (!empty($status)) {
$CFG->{$key} = $value;
return true;
}
return false;
}
/**
* This function returns a value for $CFG for a plugin
* or null if it is not found.
*
* It will give precedence to config values set in config.php like so:
* $cfg->plugin_{$plugintype}_{$pluginname}_{$key} = 'whatever';
*
* If it doesn't find one of those, it will look for the config value in
* the database.
*
* @param string $plugintype eg artefact
* @param string $pluginname eg blog
* @param string $key the config setting to look for
* @return mixed The value of the key if found, or NULL if not found
*/
function get_config_plugin($plugintype, $pluginname, $key) {
global $CFG;
static $pluginsfetched = array();
$typename = "{$plugintype}_{$pluginname}";
$configname = "plugin_{$typename}_{$key}";
if (isset($CFG->{$configname})) {
return $CFG->{$configname};
}
else if (isset($CFG->plugin->{$plugintype}->{$pluginname}->{$key})) {
log_warn(
"Mahara 1.9-format plugin config detected in your config.php: \$cfg->plugin->{$plugintype}->{$pluginname}->{$key}."
. " You should change this to the Mahara 1.10 format: \$cfg->plugin_{$plugintype}_{$pluginname}_{$key}."
);
return $CFG->plugin->{$plugintype}->{$pluginname}->{$key};
}
// If we have already fetched this plugin's data from the database, then return NULL.
// (Note that some values may come from config.php before we hit the database.)
else if (in_array($typename, $pluginsfetched)) {
return null;
}
// We haven't fetched this plugin's data yet. So do it!
else {
// To minimize database calls, get all the records for this plugin from the database at once.
$records = get_records_array($plugintype . '_config', 'plugin', $pluginname, 'field');
if (!empty($records)) {
foreach ($records as $record) {
$storeconfigname = "plugin_{$typename}_{$record->field}";
if (!isset($CFG->{$storeconfigname})) {
$CFG->{$storeconfigname} = $record->value;
}
}
}
// Make a note that we've now hit the database over this one.
$pluginsfetched[] = $typename;
// Now, return it if we found it, otherwise null.
// (This could be done by a recursive call to get_config_plugin(), but it's
// less error-prone to do it this way and it doesn't cause that much duplication)
if (isset($CFG->{$configname})) {
return $CFG->{$configname};
}
else {
return null;
}
}
}
/**
* Set or update a plugin config value.
*
* @param string $plugintype The plugin type: 'artefact', 'blocktype', etc
* @param string $pluginname The plugin name: 'file', 'creativecommons', etc
* @param string $key The config name
* @param string $value The config's new value
* @return boolean Whether or not the config was updated successfully
*/
function set_config_plugin($plugintype, $pluginname, $key, $value) {
global $CFG;
$table = $plugintype . '_config';
$success = false;
if (false !== get_field($table, 'value', 'plugin', $pluginname, 'field', $key)) {
$success = set_field($table, 'value', $value, 'plugin', $pluginname, 'field', $key);
}
else {
$pconfig = new stdClass();
$pconfig->plugin = $pluginname;
$pconfig->field = $key;
$pconfig->value = $value;
$success = insert_record($table, $pconfig);
}
// Now update the cached version
if ($success) {
$configname = "plugin_{$plugintype}_{$pluginname}_{$key}";
$CFG->{$configname} = $value;
return true;
}
return false;
}
/**
* This function returns a value for $CFG for a plugin instance
* or null if it is not found. Initially this is interesting only
* for multiauth. Note that it may go and look in the database
*
* @param string $plugintype E.g. auth
* @param string $pluginname E.g. internal
* @param string $pluginid Instance id
* @param string $key The config setting to look for
*/
function get_config_plugin_instance($plugintype, $pluginid, $key) {
global $CFG;
// Must be unlikely to exist as a config option for any plugin
$instance = '_i_n_s_t' . $pluginid;
// Suppress NOTICE with @ in case $key is not yet cached
$configname = "plugin_{$plugintype}_{$instance}_{$key}";
@$value = $CFG->{$configname};
if (isset($value)) {
return $value;
}
$records = get_records_array($plugintype . '_instance_config', 'instance', $pluginid, 'field', 'field, value');
if (!empty($records)) {
foreach($records as $record) {
$storeconfigname = "plugin_{$plugintype}_{$instance}_{$record->field}";
$CFG->{$storeconfigname} = $record->value;
if ($record->field == $key) {
$value = $record->value;
}
}
}
return $value;
}
/**
* This function returns a value for $CFG for a plugin instance
* or null if it is not found. Initially this is interesting only
* for multiauth. Note that it may go and look in the database
*
* @param string $plugintype E.g. auth
* @param string $pluginname E.g. internal
* @param string $pluginid Instance id
* @param string $key The config setting to look for
*/
function set_config_plugin_instance($plugintype, $pluginname, $pluginid, $key, $value) {
global $CFG;
$table = $plugintype . '_instance_config';
if (false !== get_field($table, 'value', 'instance', $pluginid, 'field', $key)) {
if (set_field($table, 'value', $value, 'instance', $pluginid, 'field', $key)) {
$status = true;
}
}
else {
$pconfig = new StdClass;
$pconfig->instance = $pluginid;
$pconfig->field = $key;
$pconfig->value = $value;
$status = insert_record($table, $pconfig);
}
if ($status) {
// Must be unlikely to exist as a config option for any plugin
$instance = '_i_n_s_t' . $pluginid;
$configname = "plugin_{$plugintype}_{$instance}_{$key}";
$CFG->{$configname} = $value;
return true;
}
return false;
}
/**
* Fetch an institution configuration (from either the "institution" or "institution_config" table)
*
* TODO: If needed, create a corresponding set_config_institution(). This would be most useful if there's
* a situation where you need to manipulate individual institution configs. If you want to manipulate
* them in batch, you can use the Institution class's __set() and commit() methods.
*
* @param string $institutionname
* @param string $key
* @return mixed The value of the key or NULL if the key is not valid
*/
function get_config_institution($institutionname, $key) {
global $CFG;
require_once(get_config('docroot').'/lib/institution.php');
// First, check the cache for an Institution object with this name
if (isset($CFG->fetchedinst->{$institutionname})) {
$inst = $CFG->fetchedinst->{$institutionname};
}
else {
// No cache hit, so instatiate a new Institution object
try {
$inst = new Institution($institutionname);
// Cache it (in $CFG so if we ever write set_config_institution() we can make it update the cache)
if (!isset($CFG->fetchedinst)) {
$CFG->fetchedinst = new stdClass();
}
$CFG->fetchedinst->{$institutionname} = $inst;
}
catch (ParamOutOfRangeException $e) {
return null;
}
}
// Use the magical __get() function of the Institution class
return $inst->{$key};
}
/**
* Fetch a config setting for the specified user's institutions (from either the "institution" or "institution_config" table)
*
* @param string $key
* @param int $userid (Optional) If not supplied, fetch for the current user's institutions
* @return array The results for the all the users' institutions, in the order
* supplied by load_user_institutions(). Array key is institution name.
*/
function get_configs_user_institutions($key, $userid = null) {
global $USER, $CFG;
if ($userid === null) {
$userid = $USER->id;
}
// Check for the user and key in the cache (The cache is stored in $CFG so it can be cleared/updated
// if we ever write a set_config_institution() method)
$userobj = "user{$userid}";
if (isset($CFG->userinstconf->{$userobj}->{$key})) {
return $CFG->userinstconf->{$userobj}->{$key};
}
// We didn't hit the cache, so retrieve the config from their
// institution.
// First, get a list of their institution names
if (!$userid) {
// The logged-out user has no institutions.
$institutions = false;
}
else if ($userid == $USER->id) {
// Institutions for current logged-in user
$institutions = $USER->get('institutions');
}
else {
$institutions = load_user_institutions($userid);
}
// If the user belongs to no institution, check the Mahara institution
if (!$institutions) {
// For compatibility with $USER->get('institutions') and
// load_user_institutions(), we only really care about the
// array keys
$institutions = array('mahara' => 'mahara');
}
$results = array();
foreach ($institutions as $instname => $inst) {
$results[$instname] = get_config_institution($instname, $key);
}
// Cache the result
if (!isset($CFG->userinstconf)) {
$CFG->userinstconf = new stdClass();
}
if (!isset($CFG->userinstconf->{$userobj})) {
$CFG->userinstconf->{$userobj} = new stdClass();
}
$CFG->userinstconf->{$userobj}->{$key} = $results;
return $results;
}
/**
* This function prints an array or object
* wrapped inside <pre></pre>
*
* @param $mixed value to print
*/
function print_object($mixed) {
echo '<pre>';
print_r($mixed);
echo '</pre>';
}
/**
* Reads the locales string from a language pack and attempts to set the current locale
* based on the contents of that string.
*
* @param string $lang
*/
function set_locale_for_language($lang) {
if (empty($lang)) {
return;
}
if ($args = explode(',', get_string_location('locales', 'langconfig', array(), 'raw_langstring', $lang))) {
array_unshift($args, LC_ALL);
call_user_func_array('setlocale', $args);
}
}
/**
* This function returns the current language to use, either for a given user
* or sitewide, or the default.
*
* This method is invoked in every call to get_string(), so make it performant!
*
* @return string
*/
function current_language() {
global $USER, $CFG, $SESSION;
static $userlang, $lastlang, $instlang;
$loggedin = $USER instanceof User && $USER->is_logged_in();
// Retrieve & cache the user lang pref (if the user is logged in)
if (!isset($userlang) && $loggedin) {
$userlang = $USER->get_account_preference('lang');
if ($userlang !== null && $userlang != 'default') {
if (!language_installed($userlang)) {
$USER->set_account_preference('lang', 'default');
$userlang = 'default';
}
}
}
// Retrieve & cache the institution language (if the user is logged in)
if (!isset($instlang) && $loggedin) {
$instlang = get_user_institution_language();
}
// Retrieve the $SESSION lang (from the user selecting a language while logged-out)
// Note that if the user selected a language while logged out, and then logs in,
// we will have set their user account pref to match that lang, over in
// LiveUser->authenticate().
if (!$loggedin && is_a($SESSION, 'Session')) {
$sesslang = $SESSION->get('lang');
}
else {
$sesslang = null;
}
// Logged-in user's language preference
if (!empty($userlang) && $userlang != 'default') {
$lang = $userlang;
}
// Logged-out user's language menu selection
else if (!empty($sesslang) && $sesslang != 'default') {
$lang = $sesslang;
}
// Logged-in user's institution language setting
else if (!empty($instlang) && $instlang != 'default') {
$lang = $instlang;
}
// If there's no language from the user pref or the logged-out lang menu...
if (empty($lang)) {
$lang = !empty($CFG->lang) ? $CFG->lang : 'en.utf8';
}
if ($lang == $lastlang) {
return $lang;
}
set_locale_for_language($lang);
return $lastlang = $lang;
}
/**
* Find out a user's institution language. If they belong to one institution that has specified
* a language, then this will be that institution's language. If they belong to multiple
* institutions that have specified languages, it will be the arbitrarily "first" institution.
* If they belong to no institution that has specified a language, it will return null.
*
* @param int $userid Which user to check (defaults to $USER)
* @param string $sourceinst If provided, the source institution for the language will be
* returned here by reference
* @return string A language, or 'default'
*/
function get_user_institution_language($userid = null, &$sourceinst = null) {
global $USER;
if ($userid == null) {
$userid = $USER->id;
}
$instlangs = get_configs_user_institutions('lang', $userid);
// Every user belongs to at least one institution
foreach ($instlangs as $name => $lang) {
$sourceinst = $name;
$instlang = $lang;
// If the user belongs to multiple institutions, arbitrarily use the language
// from the first one that has specified a language.
if (!empty($instlang) && $instlang != 'default' && language_installed($instlang)) {
break;
}
}
if (!$instlang) {
$instlang = 'default';
}
return $instlang;
}
/**
* Helper function to sprintf language strings
* with a variable number of arguments
*
* @param mixed $string raw string to use, or an array of strings, one for each plural form
* @param array $args arguments to sprintf
* @param string $lang The language
*/
function format_langstring($string, $args, $lang='en.utf8') {
if (is_array($string) && isset($args[0]) && is_numeric($args[0])) {
// If there are multiple strings here, there must be one for each plural
// form in the language. The first argument is passed into the plural
// function, which returns an index into the array of strings.
$pluralfunction = get_string_location('pluralfunction', 'langconfig', array(), 'raw_langstring', $lang);
$index = function_exists($pluralfunction) ? $pluralfunction($args[0]) : 0;
$string = isset($string[$index]) ? $string[$index] : current($string);
}
return call_user_func_array('sprintf',array_merge(array($string),$args));
}
function raw_langstring($string) {
return $string;
}
/**
* Helper function to figure out whether an array is an array or a hash
* @param array $array array to check
* @return bool true if the array is a hash
*/
function is_hash($array) {
if (!is_array($array)) {
return false;
}
$diff = array_diff_assoc($array,array_values($array));
return !empty($diff);
}
/**
* Function to check if a directory exists and optionally create it.
*
* @param string absolute directory path
* @param boolean create directory if does not exist
* @param boolean create directory recursively
*
* @return boolean true if directory exists or created
*/
function check_dir_exists($dir, $create=true, $recursive=true) {
$status = true;
$dir = trim($dir);
if(!is_dir($dir)) {
if (!$create) {
$status = false;
} else {
$mask = umask(0000);
$status = @mkdir($dir, get_config('directorypermissions'), true);
umask($mask);
}
}
return $status;
}
/**
* Function to require a plugin file. This is to avoid doing
* require and include directly with variables.
*
* This function is the one safe point to require plugin files.
* so USE it :)
*
* blocktypes are special cases. eg:
* system blocks: safe_require('blocktype', 'wall');
* artefact blocks: safe_require('blocktype', 'file/html');
*
* import/export plugins are special cases. eg:
* main library: safe_require('export', 'leap');
* artefact plugin implementation: safe_require('export', 'leap/file');
*
* @param string $plugintype the type of plugin (eg artefact)
* @param string $pluginname the name of the plugin (eg blog)
* @param string $filename the name of the file to include within the plugin structure
* @param string $function (optional, defaults to require) the require/include function to use
* @param string $nonfatal (optional, defaults to false) just returns false if the file doesn't exist
*/
function safe_require($plugintype, $pluginname, $filename='lib.php', $function='require_once', $nonfatal=false) {
$plugintypes = plugin_types();
if (!in_array($plugintype, $plugintypes)) {
throw new SystemException("\"$plugintype\" is not a valid plugin type");
}
require_once(get_config('docroot') . $plugintype . '/lib.php');
if (!in_array($function,array('require', 'include', 'require_once', 'include_once'))) {
if (!empty($nonfatal)) {
return false;
}
throw new SystemException ('Invalid require type');
}
if ($plugintype == 'blocktype') { // these are a bit of a special case
$bits = explode('/', $pluginname);
if (count($bits) == 2) {
$fullpath = get_config('docroot') . 'artefact/' . $bits[0] . '/blocktype/' . $bits[1] . '/' . $filename;
}
else {
try {
if ($artefactplugin = blocktype_artefactplugin($pluginname)) {
$fullpath = get_config('docroot') . 'artefact/' . $artefactplugin . '/blocktype/' . $pluginname . '/'. $filename;
}
}
catch (SQLException $e) {
if (get_config('installed')) {
throw $e;
}
}
}
}
// these can have parts living inside artefact directories as well.
else if ($plugintype == 'export' || $plugintype == 'import') {
$bits = explode('/', $pluginname);
if (count($bits) == 2) {
$fullpath = get_config('docroot') . 'artefact/' . $bits[1] . '/' . $plugintype . '/' . $bits[0] . '/' . $filename;
}
}
if (empty($fullpath)) {
$fullpath = get_config('docroot') . $plugintype . '/' . $pluginname . '/' . $filename;
}
if (!file_exists($fullpath)) {
if (!empty($nonfatal)) {
return false;
}
throw new SystemException ("File $fullpath did not exist");
}
$realpath = realpath($fullpath);
if (strpos($realpath, get_config('docroot') !== 0)) {
if (!empty($nonfatal)) {
return false;
}
throw new SystemException ("File $fullpath was outside document root!");
}
if ($function == 'require') { return require($realpath); }
if ($function == 'include') { return include($realpath); }
if ($function == 'require_once') { return require_once($realpath); }
if ($function == 'include_once') { return include_once($realpath); }
}
/**
* This function is a wrapper around safe_require which will attempt to
* handle missing plugins more gracefully.
*
* If a missing plugin is detected, then that plugin will be disabled, and
* an e-mail will be sent to site administrators to inform them of the
* issue.
*
* See @safe_require for further information on that function.
*
* @param string $plugintype the type of plugin (eg artefact)
* @param string $pluginname the name of the plugin (eg blog)
* @param string $filename the name of the file to include within the plugin structure
* @param string $function (optional, defaults to require) the require/include function to use
* @param string $nonfatal (optional, defaults to false) just returns false if the file doesn't exist
*/
function safe_require_plugin($plugintype, $pluginname, $filename='lib.php', $function='require_once', $nonfatal=false) {
try {
safe_require($plugintype, $pluginname, $filename, $function, $nonfatal);
return true;
}
catch (SystemException $e) {
if (get_field($plugintype . '_installed', 'active', 'name', $pluginname) == 1) {
global $SESSION;
set_field($plugintype . '_installed', 'active', 0, 'name', $pluginname);
$SESSION->add_error_msg(get_string('missingplugindisabled', 'admin', hsc("$plugintype:$pluginname")));
// Reset the plugin cache.
plugins_installed('', TRUE, TRUE);
// Alert site admins that the plugin is broken so was disabled
$message = new stdClass();
$message->users = get_column('usr', 'id', 'admin', 1);
$message->subject = get_string('pluginbrokenanddisabledtitle', 'mahara', $pluginname);
$message->message = get_string('pluginbrokenanddisabled', 'mahara', $pluginname, $e->getMessage());
require_once('activity.php');
activity_occurred('maharamessage', $message);
}
return false;
}
}
/**
* Check to see if a particular plugin is installed and is active by plugin name
*
* @param string $pluginname Name of plugin
* @return bool
*/
function is_plugin_active($pluginname) {
foreach (plugin_types() as $type) {
if (record_exists($type . '_installed', 'name', $pluginname, 'active', 1)) {
return true;
}
}
return false;
}
/**
* This function returns the list of plugintypes we currently care about.
*
* NOTE: use plugin_types_installed if you just want the installed ones.
*
* @return array of names
*/
function plugin_types() {
static $pluginstocheck;
if (empty($pluginstocheck)) {
// ORDER MATTERS! artefact has to be before blocktype
$pluginstocheck = array('artefact', 'auth', 'notification', 'search', 'blocktype', 'interaction', 'grouptype', 'import', 'export', 'module');
}
return $pluginstocheck;
}
/**
* Returns plugin types that are actually installed
*/
function plugin_types_installed() {
static $plugins = array();
if (empty($plugins)) {
require_once('ddl.php');
foreach (plugin_types() as $plugin) {
if (table_exists(new XMLDBTable("{$plugin}_installed"))) {
$plugins[] = $plugin;
}
}
}
return $plugins;
}
/**
* This returns the names of plugins installed
* for the given plugin type.
*
* @param string $plugintype type of plugin
* @param bool $all - return all (true) or only active (false) plugins
* @param bool $reset - whether to reset the cache (when disabling a plugin due to unavailability)
* @return array of objects with fields (version (int), release (str), active (bool), name (str))
*/
function plugins_installed($plugintype, $all=false, $reset=false) {
static $records = array();
if ($reset) {
$records = array();
return false;
}
if (defined('INSTALLER') || defined('TESTSRUNNING') || !isset($records[$plugintype][true])) {
$sort = $plugintype == 'blocktype' ? 'artefactplugin,name' : 'name';
if ($rs = get_records_assoc($plugintype . '_installed', '', '', $sort)) {
$records[$plugintype][true] = $rs;
}
else {
$records[$plugintype][true] = array();
}
$records[$plugintype][false] = array();
foreach ($records[$plugintype][true] as $r) {
if ($r->active) {
$records[$plugintype][false][$r->name] = $r;
}
}
}
if (isset($records[$plugintype])) {
return $records[$plugintype][$all];
}
return false;
}
/**
* This returns the names of plugins installed
* for all plugin types.
*
* @param bool $all - return all (true) or only active (false) plugins
* @return array of objects with fields (version (int), release (str), active (bool), name (str))
*/
function plugin_all_installed($all=false) {
$plugintypes = plugin_types_installed();
$result = array();
foreach ($plugintypes as $plugintype) {
$plugins = plugins_installed($plugintype, $all);
foreach ($plugins as $plugin) {
$plugin->plugintype = $plugintype;
$result[] = $plugin;
}
}
return $result;
}
/**
* Helper to call a static method when you do not know the name of the class
* you want to call the method on. PHP5 does not support $class::method().
*/
function call_static_method($class, $method) {
$args = func_get_args();
array_shift($args);
array_shift($args);
return call_user_func_array(array($class, $method), $args);
}
function generate_class_name() {
$args = func_get_args();
if (count($args) == 2 && $args[0] == 'blocktype') {
return 'PluginBlocktype' . ucfirst(blocktype_namespaced_to_single($args[1]));
}
return 'Plugin' . implode('', array_map('ucfirst', $args));
}
function generate_artefact_class_name($type) {
return 'ArtefactType' . ucfirst($type);
}
function generate_interaction_instance_class_name($type) {
return 'Interaction' . ucfirst($type) . 'Instance';
}
function generate_generator_class_name() {
$args = func_get_args();
return 'DataGenerator' . implode('', array_map('ucfirst', $args));
}
function blocktype_namespaced_to_single($blocktype) {
if (strpos($blocktype, '/') === false) { // system blocktype
return $blocktype;
}
return substr($blocktype, strpos($blocktype, '/') + 1 );
}
function blocktype_single_to_namespaced($blocktype, $artefact='') {
if (empty($artefact)) {
return $blocktype;
}
return $artefact . '/' . $blocktype;
}
/**
* Given a blocktype name, convert it to the namespaced version.
*
* This will be $artefacttype/$blocktype, or just plain $blocktype for system
* blocktypes.
*
* This is useful for language strings
*/
function blocktype_name_to_namespaced($blocktype) {
static $resultcache = array();
if (!isset($resultcache[$blocktype])) {
$artefactplugin = blocktype_artefactplugin($blocktype);
if ($artefactplugin) {
$resultcache[$blocktype] = "$artefactplugin/$blocktype";
}
else {
$resultcache[$blocktype] = $blocktype;
}
}
return $resultcache[$blocktype];
}
/* Get the name of the artefact plugin that provides a given blocktype */
function blocktype_artefactplugin($blocktype) {
$installed = plugins_installed('blocktype', true);
if (isset($installed[$blocktype])) {
return $installed[$blocktype]->artefactplugin;
}
return false;
}
/**
* Fires an event which can be handled by different parts of the system
*/
function handle_event($event, $data) {
global $USER;
static $event_types = array(), $coreevents_cache = array(), $eventsubs_cache = array();
if (empty($event_types)) {
$event_types = array_fill_keys(get_column('event_type', 'name'), true);
}
$e = $event_types[$event];
if (is_null($e)) {
throw new SystemException("Invalid event");
}
if ($data instanceof ArtefactType) {
// leave $data alone, but convert for the event log
$logdata = $data->to_stdclass();
}
else if ($data instanceof BlockInstance) {
// leave $data alone, but convert for the event log
$logdata = array(
'id' => $data->get('id'),
'blocktype' => $data->get('blocktype'),
);
}
else if (is_object($data)) {
$data = (array)$data;
}
else if (is_numeric($data)) {
$data = array('id' => $data);
}
$parentuser = $USER->get('parentuser');
$eventloglevel = get_config('eventloglevel');
if ($eventloglevel === 'all'
or ($parentuser and $eventloglevel === 'masq')) {
$logentry = (object) array(
'usr' => $USER->get('id'),
'realusr' => $parentuser ? $parentuser->id : $USER->get('id'),
'event' => $event,
'data' => json_encode(isset($logdata) ? $logdata : $data),
'time' => db_format_timestamp(time()),
);
insert_record('event_log', $logentry);
}
if (empty($coreevents_cache)) {
$rs = get_recordset('event_subscription');
foreach($rs as $record) {
$coreevents_cache[$record['event']][] = $record['callfunction'];
}
$rs->close();
}
$coreevents = isset($coreevents_cache[$event]) ? $coreevents_cache[$event] : array();
if (!empty($coreevents)) {
require_once('activity.php'); // core events can generate activity.
foreach ($coreevents as $ce) {
if (function_exists($ce)) {
call_user_func($ce, $data);
}
else {
log_warn("Event $event caused a problem with a core subscription "
. " $ce, which wasn't callable. Continuing with event handlers");
}
}
}
$plugintypes = plugin_types_installed();
foreach ($plugintypes as $name) {
$cache_key = "{$event}__{$name}";
if (!isset($eventsubs_cache[$cache_key])) {
$eventsubs_cache[$cache_key] = get_records_array($name . '_event_subscription', 'event', $event);
}
if ($eventsubs_cache[$cache_key]) {
$pluginsinstalled = plugins_installed($name);
foreach ($eventsubs_cache[$cache_key] as $sub) {
if (!isset($pluginsinstalled[$sub->plugin])) {
continue;
}
safe_require($name, $sub->plugin);
$classname = 'Plugin' . ucfirst($name) . ucfirst($sub->plugin);
try {
call_static_method($classname, $sub->callfunction, $event, $data);
}
catch (Exception $e) {
log_warn("Event $event caused an exception from plugin $classname "
. "with function $sub->callfunction. Continuing with event handlers");
}
}
}
}
}
/**
* function to convert an array of objects to
* an array containing one field per place
*
* @param array $array input array
* @param mixed $field field to look for in each object
*/
function mixed_array_to_field_array($array, $field) {
$repl_fun = create_function('$n, $field', '$n = (object)$n; return $n->{$field};');
$fields = array_pad(array(), count($array), $field);
return array_map($repl_fun, $array, $fields);
}
/**
* Used by XMLDB
*/
function debugging($message, $level) {
log_debug($message);
}
function xmldb_dbg($message) {
log_warn($message);
}
define('DEBUG_DEVELOPER', 'whocares');
/**
* Helper interface to hold the Plugin class's abstract static functions
*/
interface IPlugin {
/**
* The name of this plugintype. Used in directory names, table names, etc.
* @return string
*/
public static function get_plugintype_name();
}
/**
* Base class for all plugintypes.
*/
abstract class Plugin implements IPlugin {
/**
* This function returns an array of crons it wants to have run.
*
* The return value should be an array of objects. Each object should have these fields:
*
* - callfunction (mandatory): The name of the cron function. This must be a public static function
* of the particular plugin subclass. It will be called with no parameters, and should return no
* value.
* - minute (defaults to *)
* - hour (defaults to *)
* - day (defaults to *)
* - month (defaults to *)
* - dayofweek (defaults to *)
*
* @return array
*/
public static function get_cron() {
return array();
}
/**
* This function returns an array of events to subscribe to by unique name.
* If an event the plugin is trying to subscribe to is unknown by the
* core, an exception will be thrown.
*
* The return value should be array of objects. Each object should have these fields:
*
* - event: The name of the event to subscribe. Must be present in the "event_type" table.
* - plugin: The name of the plugin that holds the callfunction (probably this one!)
* - callfunction: The function to call when the event occurs.
*
* @return array
*/
public static function get_event_subscriptions() {
return array();
}
/**
* This function will be run after every upgrade to the plugin.
*
* @param int $fromversion version upgrading from (or 0 if installing)
* @return boolean to indicate whether upgrade was successful or not
*/
public static function postinst($fromversion) {
return true;
}
/**
* Whether this plugin should show a config form on the Administration->Extensions screen.
*
* If you return true here, you will also need to define the following methods:
* - get_config_options()
* - [optional] validate_config_options($form, $values)
* - save_config_options($form, $values)
*
* @return boolean
*/
public static function has_config() {
return false;
}
/**
* If has_config() is true, this function should return a pieform array, which must at least
* contain an "elements" list. This list does NOT need to contain a submit button, and it should not
* contain any elements called "plugintype", "pluginname", "type", or "save".
*
* The form definition does NOT need to contain a successcallbac, validatecallback, or jsform setting.
* If these are present, they'll be ignored.
*
* @return false|array
*/
public static function get_config_options() {
throw new SystemException("get_config_options not defined");
}
/**
* If has_config() is true, this function will be used as the Pieform validation callback function.
*
* @param Pieform $form
* @param array $values
*/
public static function validate_config_options(Pieform $form, $values) {
}
/**
* If has_config() is true, this function will be used as the Pieform success callback function
* for the plugin's config form.
*
* @param Pieform $form
* @param array $values
*/
public static function save_config_options(Pieform $form, $values) {
throw new SystemException("save_config_options not defined");
}
/**
* This function returns a list of activities this plugin brings. (i.e. things that can
* send notifications to users)
*
* It should return an array of objects. Each object should have these fields:
* - name: The (internal) name of the activity type
* - defaultmethod: The default notification to be used for this activity
* - admin
* - delay
* - allowonemethod
* - onlyapplyifwatched
*
* These fields correspond directly with the columns in the "activity_type" table.
*
* You must also implement in the plugin's lib.php file an ActivityTypePlugin subclass whose name
* matches the pattern ActivityType{$Plugintype}{$Pluginname}{$ActivityName}. For instance,
* ActivityTypeInteractionForumNewpost.
*
* @return array
*/
public static function get_activity_types() {
return array();
}
/**
* Indicates whether this plugin can be disabled.
*
* All internal type plugins, and ones in which Mahara won't work should override this.
* Probably at least one plugin per plugin-type should override this.
*/
public static function can_be_disabled() {
return true;
}
/**
* Check whether this plugin is okay to be installed.
*
* To prevent installation, throw an InstallationException
*
* @throws InstallationException
*/
public static function sanity_check() {
}
/**
* The relative path for this plugin's stuff in theme directories.
*
* @param string $pluginname The middle part in a dwoo reference, i.e. in "export:html/file:index.tpl", it's the "html/file".
* @return string
*/
public static function get_theme_path($pluginname) {
return static::get_plugintype_name() . '/' . $pluginname;
}
/**
* Get institution preference page settings for current artefact.
* @param Institution $institution
* @return array of form elements
*/
public static function get_institutionprefs_elements(Institution $institution = null) {
return array();
}
/**
* Validate institution settings values.
* @param Pieform $form
* @param array $values
*/
public static function institutionprefs_validate(Pieform $form, $values) {
return;
}
/**
* Submit institution settings values.
* @param Pieform $form
* @param array $values
* @param Institution $institution
*/
public static function institutionprefs_submit(Pieform $form, $values, Institution $institution) {
return;
}
/**
* Get user preference page settings for current artefact.
* @param stdClass $prefs Saved preferences
* @return array of form elements
*/
public static function get_accountprefs_elements(stdClass $prefs) {
return array();
}
/**
* Validate account settings values.
* @param Pieform $form
* @param array $values
*/
public static function accountprefs_validate(Pieform $form, $values) {
return;
}
/**
* Submit account settings values.
* @param Pieform $form
* @param array $values
*/
public static function accountprefs_submit(Pieform $form, $values) {
return;
}
}
/**
* formats a unix timestamp to a nice date format.
*
* @param int $date unix timestamp to format
* @param string $formatkey language key to fetch the format from
* @param string $notspecifiedkey (optional) language key to fetch 'not specified string' from
* @param string $notspecifiedsection (optional) language section to fetch 'not specified string' from
* (see langconfig.php or the top of {@link get_string_location}
* for supported keys
*/
function format_date($date, $formatkey='strftimedatetime', $notspecifiedkey='strftimenotspecified', $notspecifiedsection='mahara') {
if (empty($date)) {
return get_string($notspecifiedkey, $notspecifiedsection);
}
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$fixedkey = str_replace('%e', '%#d', get_string($formatkey));
return strftime($fixedkey, $date);
}
return strftime(get_string($formatkey), $date);
}
/**
* Returns a random string suitable for registration/change password requests
*
* @param int $length The length of the key to return
* @param array $pool The pool to draw from (optional, will use A-Za-z0-9 as a default)
* @return string
*/
function get_random_key($length=16, $pool=null) {
if ($length < 1) {
throw new IllegalArgumentException('Length must be a positive number');
}
if (empty($pool)) {
$pool = array_merge(
range('A', 'Z'),
range('a', 'z'),
range(0, 9)
);
}
shuffle($pool);
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $pool[$i];
}
return $result;
}
//
// Pieform related functions
//
/**
* Configures a default form
*/
function pieform_configure() {
global $USER, $THEME;
$renderer = $THEME->formrenderer;
return array(
'method' => 'post',
'action' => '',
'language' => current_language(),
'autofocus' => true,
'renderer' => $renderer,
'requiredmarker' => true,
'elementclasses' => true,
'descriptionintwocells' => true,
'jsdirectory' => get_config('wwwroot') . 'lib/pieforms/static/core/',
'replycallback' => 'pieform_reply',
'jserrorcallback' => 'formError',
'globaljserrorcallback' => 'formGlobalError',
'jssuccesscallback' => 'formSuccess',
'presubmitcallback' => 'formStartProcessing',
'postsubmitcallback' => 'formStopProcessing',
'jserrormessage' => get_string('errorprocessingform'),
'errormessage' => get_string('errorprocessingform'),
'configdirs' => get_config('libroot') . 'form/',
'helpcallback' => 'pieform_get_help',
'elements' => array(
'sesskey' => array(
'type' => 'hidden',
'sesskey' => true,
'value' => $USER->get('sesskey')
)
)
);
}
function form_validate($sesskey) {
global $USER;
if (is_null($sesskey)) {
throw new UserException('No session key');
}
if ($USER && $USER->is_logged_in() && $USER->get('sesskey') != $sesskey) {
throw new UserException('Invalid session key');
}
// Check to make sure the user has not been suspended or deleted, so that they cannot
// perform any action
if ($USER) {
$record = get_record_sql('SELECT suspendedctime, suspendedreason, deleted
FROM {usr}
WHERE id = ?', array($USER->get('id')));
if ($record) {
if ($record->suspendedctime) {
throw new UserException(get_string('accountsuspended', 'mahara', $record->suspendedctime, $record->suspendedreason));
}
if ($record->deleted) {
$USER->logout();
throw new AccessDeniedException(get_string('accountdeleted', 'mahara'));
}
}
}
}
function pieform_validate(Pieform $form, $values) {
if (!isset($values['sesskey'])) {
throw new UserException('No session key');
}
form_validate($values['sesskey']);
}
function pieform_reply($code, $data) {
global $SESSION;
if (isset($data['message'])) {
if ($code == PIEFORM_ERR) {
$SESSION->add_error_msg($data['message']);
}
else {
$SESSION->add_ok_msg($data['message']);
}
}
if (isset($data['goto'])) {
redirect($data['goto']);
}
// NOT explicitly exiting here. Pieforms will throw an exception which will
// force the user to fix their form
}
function pieform_element_textarea_configure($element) {
if (!array_key_exists('resizable', $element)) {
$element['resizable'] = true;
}
return $element;
}
/**
* Should be used to provide the 'templatedir' directive to pieforms using a
* template for layout.
*
* @param string $file The file to be used as a pieform template, e.g.
* "admin/site/files.php". This is the value you used as
* the 'template' option for your pieform
* @param string $pluginlocation Which plugin to search for the template, e.g.
* artefact/file
*/
function pieform_template_dir($file, $pluginlocation='') {
global $THEME;
$filepath = get_config('docroot') . 'local/theme/pieforms/' . $file;
if (is_readable($filepath)) {
return dirname($filepath);
}
foreach ($THEME->inheritance as $themedir) {
// Check under the theme directory first
$filepath = get_config('docroot') . 'theme/' . $themedir . '/plugintype/' . $pluginlocation . '/pieforms/' . $file;
if (is_readable($filepath)) {
return dirname($filepath);
}
// Then check under the plugin directory
$filepath = get_config('docroot') . $pluginlocation . '/theme/' . $themedir . '/pieforms/' . $file;
if (is_readable($filepath)) {
return dirname($filepath);
}
}
throw new SystemException('No pieform template available: ' . $file);
}
/**
* Given a view id, and a user id (defaults to currently logged in user if not
* specified) will return wether this user is allowed to look at this view.
*
* @param mixed $view viewid or View to check
* @param integer $user_id User trying to look at the view (defaults to
* currently logged in user, or null if user isn't logged in)
*
* @returns boolean Wether the specified user can look at the specified view.
*/
function can_view_view($view, $user_id=null) {
global $USER, $SESSION;
if (defined('BULKEXPORT')) {
return true;
}
$now = time();
$dbnow = db_format_timestamp($now);
if ($user_id === null) {
$user = $USER;
$user_id = $USER->get('id');
}
else {
$user = new User();
if ($user_id) {
try {
$user->find_by_id($user_id);
}
catch (AuthUnknownUserException $e) {}
}
}
$publicviews = get_config('allowpublicviews');
$publicprofiles = get_config('allowpublicprofiles');
// If the user is logged out and the publicviews & publicprofiles sitewide configs are false,
// we can deny access without having to hit the database at all
if (!$user_id && !$publicviews && !$publicprofiles) {
return false;
}
require_once(get_config('libroot') . 'view.php');
if ($view instanceof View) {
$view_id = $view->get('id');
}
else {
$view = new View($view_id = $view);
}
// If the page belongs to an individual, check for individual-specific overrides
if ($view->get('owner')) {
$ownerobj = $view->get_owner_object();
// Suspended user
if ($ownerobj->suspendedctime) {
return false;
}
// Probationary user (no public pages or profiles)
// (setting these here instead of doing a return-false, so that we can do checks for
// logged-in users later)
require_once(get_config('libroot') . 'antispam.php');
$onprobation = is_probationary_user($ownerobj->id);
$publicviews = $publicviews && !$onprobation;
$publicprofiles = $publicprofiles && !$onprobation;
// Member of an institution that prohibits public pages
// (group views and logged in users are not affected by
// the institution level config for public views)
$owner = new User();
$owner->find_by_id($ownerobj->id);
$publicviews = $publicviews && $owner->institution_allows_public_views();
}
// Now that we've examined the page owner, check again for whether it can be viewed by a logged-out user
if (!$user_id && !$publicviews && !$publicprofiles) {
return false;
}
if ($user_id && $user->can_edit_view($view)) {
return true;
}
// If the view's owner is suspended, deny access to the view
if ($view->get('owner')) {
if ((!$owner = $view->get_owner_object()) || $owner->suspendedctime) {
return false;
}
}
if ($SESSION->get('mnetuser')) {
$mnettoken = get_cookie('mviewaccess:' . $view_id);
}
// If the page has been marked "objectionable" admins should be able to view
// it for review purposes.
if ($view->is_objectionable()) {
if ($owner = $view->get('owner')) {
if ($user->is_admin_for_user($owner)) {
return true;
}
}
else if ($view->get('group') && $user->get('admin')) {
return true;
}
}
// Overriding start/stop dates are set by the owner to deny access
// to users who would otherwise be allowed to see the view. However,
// for some kinds of access (e.g. objectionable content, submitted
// views), we have to override the override and let the logged in
// user see it anyway. So we can't return false now, we have to wait
// till we find out what kind of view_access record is being used.
$overridestart = $view->get('startdate');
$overridestop = $view->get('stopdate');
$allowedbyoverride = (empty($overridestart) || $overridestart < $dbnow) && (empty($overridestop) || $overridestop > $dbnow);
$access = View::user_access_records($view_id, $user_id);
if (empty($access)) {
return false;
}
foreach ($access as &$a) {
if ($a->accesstype == 'public' && $allowedbyoverride) {
if ($publicviews) {
return true;
}
else if ($publicprofiles && $view->get('type') == 'profile') {
return true;
}
}
else if ($a->token && ($allowedbyoverride || !$a->visible)) {
$usertoken = get_cookie('viewaccess:'.$view_id);
if ($a->token == $usertoken && $publicviews) {
return true;
}
if (!empty($mnettoken) && $a->token == $mnettoken) {
$mnetviewlist = $SESSION->get('mnetviewaccess');
if (empty($mnetviewlist)) {
$mnetviewlist = array();
}
$mnetviewlist[$view_id] = true;
$SESSION->set('mnetviewaccess', $mnetviewlist);
return true;
}
// Don't bother to pull the collection out unless the user actually
// has some collection access cookies.
if ($ctokens = get_cookies('caccess:')) {
$cid = $view->collection_id();
if ($cid && isset($ctokens[$cid]) && $a->token == $ctokens[$cid]) {
return true;
}
}
}
else if ($user_id) {
if ($a->accesstype == 'friends') {
$owner = $view->get('owner');
if (!get_field_sql('
SELECT COUNT(*) FROM {usr_friend} f WHERE (usr1=? AND usr2=?) OR (usr1=? AND usr2=?)',
array($owner, $user_id, $user_id, $owner)
)) {
continue;
}
}
else if ($a->institution) {
// Check if user belongs to the allowed institution
if (!in_array($a->institution, array_keys($user->get('institutions')))) {
continue;
}
}
if (!$allowedbyoverride && $a->visible) {
continue;
}
// The view must have loggedin access, user access for the user
// or group/role access for one of the user's groups
return true;
}
}
return false;
}
/**
* Return the view associated with a given token, and set the
* appropriate access cookie.
*/
function get_view_from_token($token, $visible=true) {
if (!$token) {
return false;
}
$viewids = get_column_sql('
SELECT "view"
FROM {view_access}
WHERE token = ? AND visible = ?
AND (startdate IS NULL OR startdate < current_timestamp)
AND (stopdate IS NULL OR stopdate > current_timestamp)
ORDER BY "view"
', array($token, (int)$visible)
);
if (empty($viewids)) {
return false;
}
if (count($viewids) > 1) {
// if any of the views are in collection(s), pick one of the ones
// with the lowest displayorder.
$order = get_records_sql_array('
SELECT cv.view, collection
FROM {collection_view} cv
WHERE cv.view IN (' . join(',', $viewids) . ')
ORDER BY displayorder, collection',
array()
);
if ($order) {
if ($token != get_cookie('caccess:'.$order[0]->collection)) {
set_cookie('caccess:'.$order[0]->collection, $token, 0, true);
}
return $order[0]->view;
}
}
$viewid = $viewids[0];
if (!$visible && $token != get_cookie('mviewaccess:'.$viewid)) {
set_cookie('mviewaccess:'.$viewid, $token, 0, true);
}
if ($visible && $token != get_cookie('viewaccess:'.$viewid)) {
set_cookie('viewaccess:'.$viewid, $token, 0, true);
}
return $viewid;
}
/**
* get the views that a user can see belonging
* to the given users
*
* @param array $users users to fetch views owned by
* @param int $userlooking (optional, defaults to logged in user)
* @param int $limit grab this many views. (setting this null means get all)
*
* @return array Associative array keyed by userid, of arrays of view ids
*/
function get_views($users, $userlooking=null, $limit=5, $type=null) {
$userlooking = optional_userid($userlooking);
if (is_int($users)) {
$users = array($users);
}
$list = array();
if(count($users) == 0) {
return $list;
}
$users = array_flip($users);
$dbnow = db_format_timestamp(time());
if ($friends = get_records_sql_array(
'SELECT
CASE WHEN usr1=? THEN usr2 ELSE usr1 END AS id
FROM
{usr_friend} f
WHERE
( usr1=? AND usr2 IN (' . join(',',array_map('db_quote', array_keys($users))) . ') )
OR
( usr2=? AND usr1 IN (' . join(',',array_map('db_quote', array_keys($users))) . ') )
',
array($userlooking,$userlooking,$userlooking)
)) {
foreach ( $friends as $user_id ) {
$users[$user_id->id] = 'friend';
}
}
if (is_null($type)) {
$typesql = "AND v.type != 'profile'";
}
else {
$typesql = 'AND v.type = ' . db_quote($type);
}
$data = array();
$done = false;
// public, logged in, or friends' views
if ($results = get_records_sql_assoc(
'SELECT
v.*,
' . db_format_tsfield('atime') . ',
' . db_format_tsfield('mtime') . ',
' . db_format_tsfield('v.ctime', 'ctime') . '
FROM
{view} v
INNER JOIN {view_access} a ON
v.id=a.view
AND (
accesstype IN (\'public\',\'loggedin\')
' . (
count(preg_grep('/^friend$/', $users)) > 0
? 'OR (
accesstype = \'friends\'
AND v.owner IN (' . join(',',array_map('db_quote', array_keys(preg_grep('/^friend$/', $users)))) . ')
)'
: ''
)
. '
)
WHERE
v.owner IN (' . join(',',array_map('db_quote', array_keys($users))) . ')
AND ( v.startdate IS NULL OR v.startdate < ? )
AND ( v.stopdate IS NULL OR v.stopdate > ? )
' . $typesql,
array( $dbnow, $dbnow )
)
) {
foreach ($results as $row) {
$list[$row->owner][$row->id] = $row->id;
}
$data = $results;
// bail if we've filled all users to the limit
$done = _get_views_trim_list($list, $users, $limit, $data);
}
// check individual user access
if (!$done && $results = get_records_sql_assoc(
'SELECT
v.*,
' . db_format_tsfield('atime') . ',
' . db_format_tsfield('mtime') . ',
' . db_format_tsfield('v.ctime', 'ctime') . '
FROM
{view} v
INNER JOIN {view_access} a ON v.id=a.view AND a.usr=?
WHERE
v.owner IN (' . join(',',array_map('db_quote', array_keys($users))) . ')
AND ( v.startdate IS NULL OR v.startdate < ? )
AND ( v.stopdate IS NULL OR v.stopdate > ? )
' . $typesql,
array($userlooking, $dbnow, $dbnow)
)
) {
foreach ($results as &$row) {
$list[$row->owner][$row->id] = $row->id;
}
$data = array_merge($data, $results);
// bail if we've filled all users to the limit
$done = $done && _get_views_trim_list($list, $users, $limit, $data);
}
// check group access
if (!$done && $results = get_records_sql_assoc(
'SELECT
v.*,
' . db_format_tsfield('v.atime','atime') . ',
' . db_format_tsfield('v.mtime','mtime') . ',
' . db_format_tsfield('v.ctime','ctime') . '
FROM
{view} v
INNER JOIN {view_access} a ON v.id=a.view
INNER JOIN {group_member} m ON m.group=a.group AND m.member=?
INNER JOIN {group} g ON (g.id = a.group AND g.deleted = ?)
WHERE
v.owner IN (' . join(',',array_map('db_quote', array_keys($users))) . ')
AND ( v.startdate IS NULL OR v.startdate < ? )
AND ( v.stopdate IS NULL OR v.stopdate > ? )
' . $typesql,
array($userlooking, 0, $dbnow, $dbnow)
)
) {
foreach ($results as &$row) {
$list[$row->owner][$row->id] = $row->id;
}
$data = array_merge($data, $results);
// bail if we've filled all users to the limit
$done = $done && _get_views_trim_list($list, $users, $limit, $data);
}
require_once('view.php');
View::get_extra_view_info($data, false, false);
$list = array();
foreach ($data as $d) {
$list[$d['owner']][$d['id']] = (object)$d;
}
return $list;
}
function _get_views_trim_list(&$list, &$users, $limit, &$results) {
if ($limit === null) {
return;
}
foreach ($list as $user_id => &$views) {
if($limit and count($views) > $limit) {
foreach (array_slice($views, $limit) as $v) {
unset($results[$v]);
}
$views = array_slice($views, 0, $limit);
}
if($limit and count($views) == $limit) {
unset($users[$user_id]);
}
}
if (count($users) == 0) {
return true;
}
return false;
}
/**
* Checks if artefact or at least one of its ancestors is in view
*
* @param int|object $artefact ID of an artefact or object itself.
* Will load object if ID is supplied.
* @param int $view ID of a page that contains artefact.
*
* @return boolean True if artefact is in view, False otherwise.
*/
function artefact_in_view($artefact, $view) {
if (!is_object($artefact)) {
$artefact = artefact_instance_from_id($artefact);
}
$ancestors = $artefact->get_item_ancestors();
$params = array($view, $artefact->get('id'), $artefact->get('id'));
$extrasql = '';
if ($ancestors) {
$extrasql = "SELECT a.parent
FROM {view_artefact} top JOIN {artefact} a
ON a.parent = top.artefact
WHERE top.view = ? AND top.artefact IN (" . implode(',', $ancestors) . ")
UNION";
$params[] = $view;
}
$sql = "SELECT a.id
FROM {view_artefact} a WHERE \"view\" = ? AND artefact = ?
UNION
SELECT aa.artefact
FROM {artefact} a INNER JOIN {artefact_attachment} aa
ON a.id = aa.artefact
WHERE aa.attachment = ?
UNION
$extrasql
SELECT s.id
FROM {view} v INNER JOIN {skin} s
ON v.skin = s.id
WHERE v.id = ? AND ? in (s.bodybgimg, s.viewbgimg)
";
$params = array_merge($params, array($view, $artefact->get('id')));
return record_exists_sql($sql, $params);
}
function get_dir_contents($directory) {
$contents = array();
$dirhandle = opendir($directory);
while (false !== ($dir = readdir($dirhandle))) {
if (strpos($dir, '.') === 0) {
continue;
}
$contents[] = $dir;
}
return $contents;
}
/**
* Returns the subdirectory where mahara is installed, normally / but could
* be something different on a shared host. Useful for setting cookie paths.
*
* @return string
*/
function get_mahara_install_subdirectory() {
$wwwroot = get_config('wwwroot');
$wwwroot = preg_replace('#^https?://#', '', $wwwroot);
return substr($wwwroot, strpos($wwwroot, '/'));
}
/**
*** get_performance_info() pairs up with init_performance_info()
*** loaded in init.php. Returns an array with 'html' and 'txt'
*** values ready for use, and each of the individual stats provided
*** separately as well.
***
**/
function get_performance_info() {
if (!get_config('perftofoot') && !get_config('perftolog')) {
return array();
}
global $PERF;
$info = array();
$info['realtime'] = microtime_diff($PERF->starttime, microtime());
if (function_exists('memory_get_usage')) {
$info['memory_total'] = memory_get_usage();
$info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
}
$inc = get_included_files();
$info['includecount'] = count($inc);
$info['dbreads'] = $PERF->dbreads;
$info['dbwrites'] = $PERF->dbwrites;
$info['dbcached'] = $PERF->dbcached;
if (function_exists('posix_times')) {
$ptimes = posix_times();
if (is_array($ptimes)) {
foreach ($ptimes as $key => $val) {
$info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
}
}
}
// Grab the load average for the last minute
// /proc will only work under some linux configurations
// while uptime is there under MacOSX/Darwin and other unices
if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
list($server_load) = explode(' ', $loadavg[0]);
unset($loadavg);
} else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
$server_load = $matches[1];
} else {
log_debug('PERF: Could not parse uptime output!');
}
}
if (!empty($server_load)) {
$info['serverload'] = $server_load;
}
else {
$info['serverload'] = 'unknown';
}
return $info;
}
function perf_to_log($info=null) {
if (!get_config('perftolog')) {
return true;
}
if (empty($info)) {
$info = get_performance_info();
}
$logstring = 'PERF: ' . strip_querystring(get_script_path()). ': ';
$logstring .= ' memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).')';
$logstring .= ' time: '.$info['realtime'].'s';
$logstring .= ' includecount: '.$info['includecount'];
$logstring .= ' dbqueries: '.$info['dbreads'] . ' reads, ' . $info['dbwrites'] . ' writes, ' . $info['dbcached'] . ' cached';
$logstring .= ' ticks: ' . $info['ticks'] . ' user: ' . $info['utime'] . ' sys: ' . $info['stime'] .' cuser: ' . $info['cutime'] . ' csys: ' . $info['cstime'];
$logstring .= ' serverload: ' . $info['serverload'];
log_debug($logstring);
}
/**
* microtime_diff
*
* @param string $a ?
* @param string $b ?
* @return string
* @todo Finish documenting this function
*/
function microtime_diff($a, $b) {
list($a_dec, $a_sec) = explode(' ', $a);
list($b_dec, $b_sec) = explode(' ', $b);
return $b_sec - $a_sec + $b_dec - $a_dec;
}
/**
* Function to raise the memory limit to a new value.
* Will respect the memory limit if it is higher, thus allowing
* settings in php.ini, apache conf or command line switches
* to override it
*
* The memory limit should be expressed with a string (eg:'64M')
*
* @param string $newlimit the new memory limit
* @return bool Whether we were able to raise the limit or not
*/
function raise_memory_limit ($newlimit) {
if (empty($newlimit)) {
return false;
}
$cur = @ini_get('memory_limit');
if (empty($cur)) {
// If php is compiled without --enable-memory-limits
// apparently memory_limit is set to ''
$cur=0;
}
else {
if ($cur == -1){
return true; // unlimited mem!
}
$cur = get_real_size($cur);
}
$new = get_real_size($newlimit);
if ($new > $cur) {
ini_set('memory_limit', $newlimit);
return true;
}
return false;
}
/**
* Function to raise the max execution time to a new value.
* Will respect the time limit if it is higher, thus allowing
* settings in php.ini, apache conf or command line switches
* to override it
*
* @param int $newlimit the new max execution time limit (in seconds)
* @return bool Whether we were able to raise the limit or not
*/
function raise_time_limit($newlimit) {
if (empty($newlimit)) {
return false;
}
$newlimit = intval($newlimit);
$cur = @ini_get('max_execution_time');
if (empty($cur)) {
$cur = 0;
}
// Currently set as umlimited so don't change
if ($cur == '0') {
return false;
}
if ($newlimit > $cur) {
// this won't work in safe mode - but we shouldn't be in safe mode
// as that has been checked for already
ini_set('max_execution_time', $newlimit);
return true;
}
return false;
}
/**
* Converts numbers like 10M into bytes.
*
* @param string $size The size to be converted
* @return integer
* @throws SystemException if the string does not have a valid suffix.
* See the function definition for allowed suffixes.
*/
function get_real_size($size=0) {
if (!$size) {
return 0;
}
// If there is no suffix then assume bytes
else if (is_numeric($size)) return (int)$size;
$scan = array(
'GB' => 1073741824,
'Gb' => 1073741824,
'G' => 1073741824,
'g' => 1073741824,
'MB' => 1048576,
'Mb' => 1048576,
'M' => 1048576,
'm' => 1048576,
'KB' => 1024,
'Kb' => 1024,
'K' => 1024,
'k' => 1024,
);
while (list($key) = each($scan)) {
if (strlen($size) > strlen($key) && substr($size, -strlen($key)) == $key) {
$size = substr($size, 0, -strlen($key)) * $scan[$key];
return $size;
}
}
throw new SystemException('get_real_size called without valid size');
}
/**
* Determines maximum upload size based on quota and PHP settings.
*
* @param bool $is_user whether upload size should be evaluated for user (quota is considered)
* @return integer
*/
function get_max_upload_size($is_user) {
global $USER;
if (!$postmaxsize = get_real_size(ini_get('post_max_size'))) {
$maxuploadsize = get_real_size(ini_get('upload_max_filesize'));
}
else {
$maxuploadsize = max(1024, min($postmaxsize - 4096, get_real_size(ini_get('upload_max_filesize'))));
}
if ($is_user) {
$userquotaremaining = $USER->get('quota') - $USER->get('quotaused');
$maxuploadsize = min($maxuploadsize, $userquotaremaining);
}
return $maxuploadsize;
}
/**
* Converts bytes into display form
*
* @param string $size ?
* @return string
* @staticvar string $gb Localized string for size in gigabytes
* @staticvar string $mb Localized string for size in megabytes
* @staticvar string $kb Localized string for size in kilobytes
* @staticvar string $b Localized string for size in bytes
* @todo Finish documenting this function. Verify return type.
*/
function display_size($size) {
static $gb, $mb, $kb, $b;
if (empty($gb)) {
$gb = get_string('sizegb');
$mb = get_string('sizemb');
$kb = get_string('sizekb');
$b = get_string('sizeb');
}
if ($size >= 1073741824) {
$size = round($size / 1073741824 * 10) / 10 . $gb;
} else if ($size >= 1048576) {
$size = round($size / 1048576 * 10) / 10 . $mb;
} else if ($size >= 1024) {
$size = round($size / 1024 * 10) / 10 . $kb;
} else {
$size = $size .' '. $b;
}
return $size;
}
/**
* creates the profile sideblock
*/
function profile_sideblock() {
global $USER, $SESSION;
safe_require('notification', 'internal');
require_once('group.php');
require_once('institution.php');
$data = array(
'id' => $USER->get('id'),
'myname' => display_name($USER, null, true),
'username' => $USER->get('username'),
'url' => profile_url($USER),
'profileiconurl' => get_config('wwwroot') . 'artefact/file/profileicons.php',
);
$authinstance = $SESSION->get('mnetuser') ? $SESSION->get('authinstance') : $USER->get('authinstance');
if ($authinstance) {
$authobj = AuthFactory::create($authinstance);
if ($authobj->authname == 'xmlrpc') {
$peer = get_peer($authobj->wwwroot);
if ($SESSION->get('mnetuser')) {
$data['mnetloggedinfrom'] = get_string('youhaveloggedinfrom1', 'auth.xmlrpc', $authobj->wwwroot, $peer->name);
}
else {
$data['peer'] = array('name' => $peer->name, 'wwwroot' => $peer->wwwroot);
}
}
}
$invitedgroups = get_records_sql_array('SELECT g.*, gmi.ctime, gmi.reason
FROM {group} g
JOIN {group_member_invite} gmi ON gmi.group = g.id
WHERE gmi.member = ? AND g.deleted = ?', array($USER->get('id'), 0));
$data['invitedgroups'] = $invitedgroups ? count($invitedgroups) : 0;
$data['invitedgroupsmessage'] = $data['invitedgroups'] == 1 ? get_string('invitedgroup') : get_string('invitedgroups');
$data['pendingfriends'] = count_records('usr_friend_request', 'owner', $USER->get('id'));
$data['pendingfriendsmessage'] = $data['pendingfriends'] == 1 ? get_string('pendingfriend') : get_string('pendingfriends');
// Check if we want to limit the displayed groups by the account setting
$limitto = null;
$limit = $USER->get_account_preference('groupsideblockmaxgroups');
if (isset($limit) && is_numeric($limit)) {
$limitto = intval($limit);
}
$sort = null;
if ($sortorder = $USER->get_account_preference('groupsideblocksortby')) {
$sort = $sortorder;
}
if ($limitto === null) {
$data['groups'] = group_get_user_groups($USER->get('id'), null, $sort);
$total = count($data['groups']);
}
else if ($limitto === 0) {
$data['groups'] = null;
}
else {
list($data['groups'], $total) = group_get_user_groups($USER->get('id'), null, $sort, $limitto);
}
$limitstr = '';
if (!empty($limitto) && $limitto < $total) {
switch ($sort) {
case 'earliest':
$limitstr = get_string('numberofmygroupsshowingearliest', 'blocktype.mygroups', $limitto, $total);
break;
case 'latest':
$limitstr = get_string('numberofmygroupsshowinglatest', 'blocktype.mygroups', $limitto, $total);
break;
default:
$limitstr = get_string('numberofmygroupsshowing', 'blocktype.mygroups', $limitto, $total);
break;
}
}
$data['grouplimitstr'] = $limitstr;
$data['views'] = get_records_sql_array(
'SELECT v.id, v.title, v.urlid, v.owner
FROM {view} v
INNER JOIN {view_tag} vt ON (vt.tag = ? AND vt.view = v.id)
WHERE v.owner = ?
ORDER BY v.title',
array(get_string('profile'), $USER->get('id'))
);
if ($data['views']) {
require_once('view.php');
foreach($data['views'] as $v) {
$view = new View(0, (array)$v);
$view->set('dirty', false);
$v->fullurl = $view->get_url();
}
}
$data['artefacts'] = get_records_sql_array(
'SELECT a.id, a.artefacttype, a.title
FROM {artefact} a
INNER JOIN {artefact_tag} at ON (a.id = at.artefact AND tag = ?)
WHERE a.owner = ?
ORDER BY a.title',
array(get_string('profile'), $USER->get('id'))
);
if (!empty($data['artefacts'])) {
// check if we have any blogposts and fetch their blog id if we do
foreach ($data['artefacts'] as $key => $value) {
if ($value->artefacttype == 'blogpost') {
$value->blogid = get_field('artefact', 'parent', 'id', $value->id);
}
}
}
return $data;
}
/**
* Gets data about users who have been online in the last while.
*
* The time is configured by setting the 'accessidletimeout' configuration
* option.
*
* Limits the number of users to display based on the 'onlineuserssideblockmaxusers'
* site configuration option and the Institution specific 'showonlineusers' setting.
* If the user belongs to no institution (other than the standard 'mahara' one) then
* the decision will be to show ALL users by default.
*
*/
function onlineusers_sideblock() {
global $USER;
// Determine what level of users to show
// 0 = none, 1 = institution/s only, 2 = all users
$showusers = 2;
$institutions = $USER->institutions;
if (!empty($institutions)) {
$showusers = 0;
foreach ($institutions as $i) {
if ($i->showonlineusers == 2) {
$showusers = 2;
break;
}
if ($i->showonlineusers == 1) {
$showusers = 1;
}
}
}
$maxonlineusers = get_config('onlineuserssideblockmaxusers');
switch ($showusers) {
case 0: // show none
return array(
'users' => array(),
'count' => 0,
'lastminutes' => floor(get_config('accessidletimeout') / 60),
);
case 1: // show institution only
$sql = 'SELECT DISTINCT u.* FROM {usr} u JOIN {usr_institution} i ON u.id = i.usr
WHERE i.institution IN ('.join(',', array_map('db_quote', array_keys($institutions))).')
AND lastaccess > ? AND deleted = 0 ORDER BY lastaccess DESC';
break;
case 2: // show all
$sql = 'SELECT * FROM {usr} WHERE lastaccess > ? AND deleted = 0 ORDER BY lastaccess DESC';
break;
}
$onlineusers = get_records_sql_array($sql, array(db_format_timestamp(time() - get_config('accessidletimeout'))), 0, $maxonlineusers);
if ($onlineusers) {
foreach ($onlineusers as &$user) {
$user->profileiconurl = profile_icon_url($user, 20, 20);
// If the user is an MNET user, show where they've come from
$authobj = AuthFactory::create($user->authinstance);
if ($authobj->authname == 'xmlrpc') {
$peer = get_peer($authobj->wwwroot);
$user->loggedinfrom = $peer->name;
}
}
}
else {
$onlineusers = array();
}
return array(
'users' => $onlineusers,
'count' => count($onlineusers),
'lastminutes' => floor(get_config('accessidletimeout') / 60),
);
}
function tag_weight($freq) {
return pow($freq, 2);
// return log10($freq);
}
function get_my_tags($limit=null, $cloud=true, $sort='freq') {
global $USER;
$id = $USER->get('id');
if ($limit || $sort != 'alpha') {
$sort = 'COUNT(t.tag) DESC';
}
else {
$sort = 't.tag ASC';
}
$tagrecords = get_records_sql_array("
SELECT
t.tag, COUNT(t.tag) AS count
FROM (
(SELECT at.tag, a.id, 'artefact' AS type
FROM {artefact_tag} at JOIN {artefact} a ON a.id = at.artefact
WHERE a.owner = ?)
UNION
(SELECT vt.tag, v.id, 'view' AS type
FROM {view_tag} vt JOIN {view} v ON v.id = vt.view
WHERE v.owner = ?)
UNION
(SELECT ct.tag, c.id, 'collection' AS type
FROM {collection_tag} ct JOIN {collection} c ON c.id = ct.collection
WHERE c.owner = ?)
) t
GROUP BY t.tag
ORDER BY " . $sort . (is_null($limit) ? '' : " LIMIT $limit"),
array($id, $id, $id)
);
if (!$tagrecords) {
return false;
}
if ($cloud) {
$minfreq = $tagrecords[count($tagrecords) - 1]->count;
$maxfreq = $tagrecords[0]->count;
if ($minfreq != $maxfreq) {
$minweight = tag_weight($minfreq);
$maxweight = tag_weight($maxfreq);
$minsize = 0.8;
$maxsize = 2.5;
foreach ($tagrecords as &$t) {
$weight = (tag_weight($t->count) - $minweight) / ($maxweight - $minweight);
$t->size = sprintf("%0.1f", $minsize + ($maxsize - $minsize) * $weight);
}
}
usort($tagrecords, create_function('$a,$b', 'return strnatcasecmp($a->tag, $b->tag);'));
}
else {
foreach ($tagrecords as &$t) {
$t->tagurl = urlencode($t->tag);
}
}
return $tagrecords;
}
function tags_sideblock() {
global $USER;
$maxtags = $USER->get_account_preference('tagssideblockmaxtags');
$maxtags = is_null($maxtags) ? get_config('tagssideblockmaxtags') : $maxtags;
if ($tagrecords = get_my_tags($maxtags)) {
return array('tags' => $tagrecords);
}
return null;
}
/**
* Get the string to display for a given progress bar item (in the sideblock).
* eg: Upload 2 files
* @param string $pluginname
* @param string $artefacttype
* @param int $target How many items need to be created
* @param int $completed How many items have been created
*/
function progressbar_artefact_task_label($pluginname, $artefacttype, $target, $completed) {
return call_user_func(generate_class_name('artefact', $pluginname) . '::progressbar_task_label', $artefacttype, $target, $completed);
}
/**
* Get the link to link on a given progress bar item (in the sideblock)
* @param string $pluginname
* @param string $artefacttype
*/
function progressbar_artefact_link($pluginname, $artefacttype) {
return call_user_func(generate_class_name('artefact', $pluginname) . '::progressbar_link', $artefacttype);
}
function progressbar_sideblock($preview=false) {
global $USER;
// TODO: Remove this URL param from here, and when previewing pass institution
// by function param instead
$institution = param_alphanum('i', null);
if (is_array($USER->institutions) && count($USER->institutions) > 0) {
// Get all institutions where user is member
$institutions = array();
foreach ($USER->institutions as $inst) {
if (empty($inst->suspended)) {
$institutions = array_merge($institutions, array($inst->institution => $inst->displayname));
}
}
// Set user's first institution in case that institution isn't
// set yet or user is not member of currently set institution.
if (!$institution || !array_key_exists($institution, $institutions)) {
$institution = key(array_slice($institutions, 0, 1));
}
}
else {
$institutions = array();
$institution = 'mahara';
}
// Set appropriate preview according to institution, if the institutio is selected
// If the institution isn't selected then show preview for first institution, which
// is also selected as a default value in institution selection box
if ($preview) {
$default = get_column('institution', 'name');
// TODO: Remove this URL param from here, and when previewing pass institution
// by function param instead
$institution = param_alphanum('institution', $default[0]);
}
// We need to check to see if any of the institutions have profile completeness to allow
// the select box to work correctly for users with more than one institution
$multiinstitutionprogress = false;
$counting = null;
if (!empty($institutions)) {
foreach ($institutions as $key => $value) {
if ($result = get_records_select_assoc('institution_config', 'institution=? and field like \'progressbaritem_%\'', array($key), 'field', 'field, value')) {
$multiinstitutionprogress = true;
if ($key == $institution) {
$counting = $result;
break;
}
}
}
}
else {
$counting = get_records_select_assoc('institution_config', 'institution=? and field like \'progressbaritem_%\'', array($institution), 'field', 'field, value');
}
// Get artefacts that count towards profile completeness
if ($counting) {
// Without locked ones (site locked and institution locked)
$sitelocked = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', 'mahara');
$instlocked = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', $institution);
$locked = $sitelocked + $instlocked;
foreach ($locked as $l) {
unset($counting["progressbaritem_internal_{$l}"]);
}
$totalcounting = 0;
foreach ($counting as $c) {
$totalcounting = $totalcounting + $c->value;
}
// Get all artefacts for progressbar and create data structure
$data = array();
// For the artefact_get_progressbar_items function, we want them indexed by plugin
// and then subindexed by artefact. For most other purposes, having them indexed
// by config name is sufficient
$onlytheseplugins = array();
foreach($counting as $key => $obj) {
// This one has no value. So remove it from the list.
if (!($obj->value)) {
unset($counting[$key]);
continue;
}
$parts = explode('_', $obj->field);
$plugin = $parts[1];
$item = $parts[2];
if (empty($onlytheseplugins[$plugin])) {
$onlytheseplugins[$plugin] = array();
}
$onlytheseplugins[$plugin][$item] = $item;
}
$progressbaritems = artefact_get_progressbar_items($onlytheseplugins);
// Get the data link about every item
foreach ($progressbaritems as $pluginname => $itemlist) {
foreach ($itemlist as $artefactname => $item) {
$itemname = "progressbaritem_{$pluginname}_{$artefactname}";
$c = $counting[$itemname];
$target = $c->value;
$completed = 0;
$data[$itemname] = array(
'artefact' => $artefactname,
'link' => progressbar_artefact_link($pluginname, $artefactname),
'counting' => $target,
'completed' => $completed,
'display' => ((bool) $c->value),
'label' => progressbar_artefact_task_label($pluginname, $artefactname, $target, $completed),
);
}
}
if ($preview) {
$percent = 0;
}
else {
// Since this is not a preview, gather data about the users' actual progress,
// and update the records we placed in $data.
// Get a list of all the basic artefact types in this progress bar.
$nonmeta = array();
foreach($progressbaritems as $plugin=>$pluginitems) {
foreach($pluginitems as $itemname=>$item) {
if (!$item->ismeta) {
$nonmeta[] = $itemname;
}
}
}
if ($nonmeta) {
// To reduce the number of queries, we gather data about all the user's artefacts
// at once. (Metaartefacts are handled separately, below)
$insql = "'" . implode("','", $nonmeta) . "'";
$sql = "SELECT artefacttype, (select plugin from {artefact_installed_type} ait where ait.name=a.artefacttype) as plugin, COUNT(*) AS completed
FROM {artefact} a
WHERE owner = ?
AND artefacttype in ({$insql})
GROUP BY artefacttype";
$normalartefacts = get_records_sql_array($sql, array($USER->get('id')));
if (!$normalartefacts) {
$normalartefacts = array();
}
}
else {
// No basic artefacts in this one, so we just use an empty array for this.
$normalartefacts = array();
}
$totalcompleted = 0;
$metaartefacts = array();
foreach ($progressbaritems as $plugin => $pluginitems) {
if (is_array($records = artefact_get_progressbar_metaartefacts($plugin, $pluginitems))) {
foreach ($records as $record) {
$record->plugin = $plugin;
array_push($metaartefacts, $record);
}
}
}
foreach (array_merge($normalartefacts, $metaartefacts) as $record) {
$itemname = "progressbaritem_{$record->plugin}_{$record->artefacttype}";
// It's not an item we're tracking, so skip it.
if (!array_key_exists($itemname, $counting)) {
continue;
}
$target = $counting[$itemname]->value;
$remaining = max(0, $target - $record->completed);
// Override the data for this item
$data[$itemname]['completed'] = $record->completed;
$data[$itemname]['display'] = ($remaining > 0);
$data[$itemname]['label'] = $label = get_string('progress_' . $record->artefacttype, 'artefact.' . $record->plugin, $remaining);
if ($target > 0) {
$totalcompleted = $totalcompleted + min($target, $record->completed);
}
}
$percent = round(($totalcompleted/$totalcounting)*100);
if ($percent > 100) {
$percent = 100;
}
}
return array(
'data' => $data,
'percent' => $percent,
'preview' => $preview,
'count' => ($preview ? 1 : count($institutions)),
// This is important if user is member
// of more than one institution ...
'institutions' => $institutions,
'institution' => $institution,
'totalcompleted' => !empty($totalcompleted) ? $totalcompleted : 0,
'totalcounting' => $totalcounting,
);
}
else if ($multiinstitutionprogress) {
return array(
'data' => null,
'percent' => 0,
'preview' => $preview,
'count' => ($preview ? 1 : count($institutions)),
// This is important if user is member
// of more than one institution ...
'institutions' => $institutions,
'institution' => $institution,
'totalcompleted' => 0,
'totalcounting' => 0,
);
}
return array(
'data' => null,
'percent' => 0,
'preview' => $preview,
'count' => 1,
'institutions' => null,
'institution' => 'mahara',
);
}
/**
* Cronjob to recalculate how much quota each user is using and update it as
* appropriate.
*
* This gives a backstop for the possibility that there is a bug elsewhere that
* has caused the quota count to get out of sync
*/
function recalculate_quota() {
$plugins = plugins_installed('artefact', true);
$userquotas = array();
$groupquotas = array();
foreach ($plugins as $plugin) {
safe_require('artefact', $plugin->name);
$classname = generate_class_name('artefact', $plugin->name);
if (is_callable($classname . '::recalculate_quota')) {
$pluginuserquotas = call_static_method($classname, 'recalculate_quota');
foreach ($pluginuserquotas as $userid => $usage) {
if (!isset($userquotas[$userid])) {
$userquotas[$userid] = $usage;
}
else {
$userquotas[$userid] += $usage;
}
}
}
if (is_callable($classname . '::recalculate_group_quota')) {
$plugingroupquotas = call_static_method($classname, 'recalculate_group_quota');
foreach ($plugingroupquotas as $groupid => $usage) {
if (!isset($groupquotas[$groupid])) {
$groupquotas[$groupid] = $usage;
}
else {
$groupquotas[$groupid] += $usage;
}
}
}
}
foreach ($userquotas as $user => $quota) {
$data = (object) array(
'quotaused' => $quota
);
$where = (object) array(
'id' => $user
);
update_record('usr', $data, $where);
}
foreach ($groupquotas as $group => $quota) {
$data = (object) array(
'quotaused' => $quota
);
$where = (object) array(
'id' => $group
);
update_record('group', $data, $where);
}
}
/**
* A cronjob to clean general internal activity notifications
*/
function cron_clean_internal_activity_notifications() {
safe_require('notification', 'internal');
PluginNotificationInternal::clean_notifications(array('viewaccess', 'watchlist', 'institutionmessage'));
}
/**
* Cronjob to check Launchpad for the latest Mahara version
*/
function cron_check_for_updates() {
$request = array(
CURLOPT_URL => 'https://launchpad.net/mahara/+download',
);
$result = mahara_http_request($request);
if (!empty($result->errno)) {
log_debug('Could not retrieve launchpad download page');
return;
}
$page = new DOMDocument();
libxml_use_internal_errors(true);
$success = $page->loadHTML($result->data);
libxml_use_internal_errors(false);
if (!$success) {
log_debug('Error parsing launchpad download page');
return;
}
$xpath = new DOMXPath($page);
$query = '//div[starts-with(@id,"release-information-")]';
$elements = $xpath->query($query);
$versions = array();
foreach ($elements as $e) {
if (preg_match('/^release-information-(\d+)-(\d+)-(\d+)$/', $e->getAttribute('id'), $match)) {
$versions[] = "$match[1].$match[2].$match[3]";
}
}
if (!empty($versions)) {
usort($versions, 'strnatcmp');
set_config('latest_version', end($versions));
}
}
/**
* Cronjob to send an update of site statistics to mahara.org
*/
function cron_send_registration_data() {
require_once(get_config('libroot') . 'registration.php');
registration_store_data();
if (!get_config('registration_sendweeklyupdates')) {
return;
}
$result = registration_send_data();
$data = json_decode($result->data);
if ($data->status != 1) {
log_info($result);
}
else {
set_config('registration_lastsent', time());
}
}
/**
* Cronjob to store the institution statistics
*/
function cron_institution_registration_data() {
require_once(get_config('libroot') . 'registration.php');
institution_registration_store_data();
}
/**
* Cronjob to save weekly site data locally
*/
function cron_site_data_weekly() {
require_once(get_config('libroot') . 'registration.php');
$current = site_data_current();
$time = db_format_timestamp(time());
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'user-count',
'value' => $current['users'],
));
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'group-count',
'value' => $current['groups'],
));
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'view-count',
'value' => $current['views'],
));
}
function cron_site_data_daily() {
require_once(get_config('libroot') . 'registration.php');
$current = site_data_current();
$time = db_format_timestamp(time());
// Total users
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'user-count-daily',
'value' => $current['users'],
));
// Logged-in users
$interval = is_postgres() ? "'1 day'" : '1 day';
$where = "lastaccess >= DATE(?) AND lastaccess < DATE(?)+ INTERVAL $interval";
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'loggedin-users-daily',
'value' => count_records_select('usr', $where, array($time, $time)),
));
// Process log file containing view visits
$viewlog = get_config('dataroot') . 'log/views.log';
if (@rename($viewlog, $viewlog . '.temp') and $fh = @fopen($viewlog . '.temp', 'r')) {
// Read the new stuff out of the file
$latest = get_config('viewloglatest');
$visits = array();
while (!feof($fh)) {
$line = fgets($fh, 1024);
if (preg_match('/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (\d+)$/', $line, $m) && $m[1] > $latest) {
$visits[] = (object) array('ctime' => $m[1], 'view' => $m[2]);
}
}
fclose($fh);
// Get per-view counts for the view table.
$visitcounts = array();
foreach ($visits as &$v) {
if (!isset($visitcounts[$v->view])) {
$visitcounts[$v->view] = 0;
}
$visitcounts[$v->view]++;
}
// Add visit records to view_visit
foreach ($visits as &$v) {
if (record_exists('view', 'id', $v->view)) {
insert_record('view_visit', $v);
}
}
// Delete view_visit records > 1 week old
delete_records_select(
'view_visit',
'ctime < CURRENT_DATE - INTERVAL ' . (is_postgres() ? "'1 week'" : '1 WEEK')
);
// Update view counts
foreach ($visitcounts as $viewid => $newvisits) {
execute_sql("UPDATE {view} SET visits = visits + ? WHERE id = ?", array($newvisits, $viewid));
}
set_config('viewloglatest', $time);
unlink($viewlog . '.temp');
}
require_once('function.dirsize.php');
if ($diskusage = dirsize(get_config('dataroot'))) {
// Currently there is no need to track disk usage
// over time, so delete old records first.
delete_records('site_data', 'type', 'disk-usage');
insert_record('site_data', (object) array(
'ctime' => $time,
'type' => 'disk-usage',
'value' => $diskusage,
));
}
graph_site_data_daily();
}
function cron_institution_data_weekly() {
require_once(get_config('libroot') . 'registration.php');
foreach (get_column('institution', 'name') as $institution) {
$current = institution_data_current($institution);
$time = db_format_timestamp(time());
insert_record('institution_data', (object) array(
'ctime' => $time,
'institution' => $institution,
'type' => 'user-count',
'value' => $current['users'],
));
insert_record('institution_data', (object) array(
'ctime' => $time,
'institution' => $institution,
'type' => 'view-count',
'value' => $current['views'],
));
$current['name'] = $institution;
}
}
function cron_institution_data_daily() {
require_once(get_config('libroot') . 'registration.php');
foreach (get_column('institution', 'name') as $institution) {
$current = institution_data_current($institution);
$time = db_format_timestamp(time());
// Total users
insert_record('institution_data', (object) array(
'ctime' => $time,
'institution' => $institution,
'type' => 'user-count-daily',
'value' => $current['users'],
));
// Logged-in users
$interval = is_postgres() ? "'1 day'" : '1 day';
if ($current['users'] != 0) {
$where = "lastaccess >= DATE(?) AND lastaccess < DATE(?)+ INTERVAL $interval";
$where .= " AND id IN (" . join(',', array_fill(0, $current['users'], '?')) . ")";
$loggedin = count_records_select('usr', $where, array_merge(array($time, $time), $current['members']));
}
else {
$loggedin = 0;
}
insert_record('institution_data', (object) array(
'ctime' => $time,
'institution' => $institution,
'type' => 'loggedin-users-daily',
'value' => $loggedin,
));
$current['name'] = $institution;
graph_institution_data_daily($current);
}
}
/**
* A cronjob to generate a sitemap
*/
function cron_sitemap_daily() {
if (!get_config('generatesitemap')) {
return;
}
require_once(get_config('libroot') . 'searchlib.php');
require_once(get_config('libroot') . 'group.php');
require_once(get_config('libroot') . 'view.php');
require_once(get_config('libroot') . 'sitemap.php');
safe_require('interaction', 'forum');
$sitemap = new Sitemap();
$sitemap->generate();
}
/**
* Cronjob to expire the event_log table.
*/
function cron_event_log_expire() {
if ($expiry = get_config('eventlogexpiry')) {
delete_records_select(
'event_log',
'time < CURRENT_DATE - INTERVAL ' .
(is_postgres() ? "'" . $expiry . " seconds'" : $expiry . ' SECOND')
);
}
}
function build_portfolio_search_html(&$data) {
global $THEME;
$artefacttypes = get_records_assoc('artefact_installed_type');
require_once('view.php');
require_once('collection.php');
foreach ($data->data as &$item) {
$item->ctime = format_date($item->ctime);
if ($item->type == 'view') {
$item->typestr = get_string('view');
$item->icon = $THEME->get_image_url('page');
$v = new View(0, (array)$item);
$v->set('dirty', false);
$item->url = $v->get_url();
}
else if ($item->type == 'collection') {
$item->typestr = get_string('Collection', 'collection');
$item->icon = $THEME->get_image_url('collection');
$c = new Collection(0, (array)$item);
$item->url = $c->get_url();
}
else { // artefact
safe_require('artefact', $artefacttypes[$item->artefacttype]->plugin);
$links = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_links', $item->id);
$item->url = $links['_default'];
$item->icon = call_static_method(generate_artefact_class_name($item->artefacttype), 'get_icon', array('id' => $item->id));
if ($item->artefacttype == 'task') {
$item->typestr = get_string('Task', 'artefact.plans');
}
else {
$item->typestr = get_string($item->artefacttype, 'artefact.' . $artefacttypes[$item->artefacttype]->plugin);
}
}
}
$data->baseurl = get_config('wwwroot') . 'tags.php' . (is_null($data->tag) ? '' : '?tag=' . urlencode($data->tag));
$data->sortcols = array('name', 'date');
$data->filtercols = array(
'all' => get_string('tagfilter_all'),
'file' => get_string('tagfilter_file'),
'image' => get_string('tagfilter_image'),
'text' => get_string('tagfilter_text'),
'view' => get_string('tagfilter_view'),
'collection' => get_string('tagfilter_collection'),
);
$smarty = smarty_core();
$smarty->assign_by_ref('data', $data->data);
$smarty->assign('owner', $data->owner->id);
$data->tablerows = $smarty->fetch('portfoliosearchresults.tpl');
$pagination = build_pagination(array(
'id' => 'results_pagination',
'class' => 'center',
'url' => $data->baseurl . ($data->sort == 'name' ? '' : '&sort=' . $data->sort) . ($data->filter == 'all' ? '' : '&type=' . $data->filter),
'jsonscript' => 'json/tagsearch.php',
'datatable' => 'results',
'count' => $data->count,
'limit' => $data->limit,
'offset' => $data->offset,
'jumplinks' => 6,
'numbersincludeprevnext' => 2,
'numbersincludefirstlast' => false,
'resultcounttextsingular' => get_string('result'),
'resultcounttextplural' => get_string('results'),
));
$data->pagination = $pagination['html'];
$data->pagination_js = $pagination['javascript'];
}
function mahara_log($logname, $string) {
error_log('[' . date("Y-m-d h:i:s") . "] $string\n", 3, get_config('dataroot') . 'log/' . $logname . '.log');
}
/**
* Check whether HTML editor can be used.
*
* @return bool
*/
function is_html_editor_enabled () {
global $USER, $SESSION;
return (
(!get_config('wysiwyg') && $USER->get_account_preference('wysiwyg')) ||
(get_config('wysiwyg') == 'enable' && $USER->is_logged_in())
) && $SESSION->get('handheld_device') == false;
}
/**
* Determine if site is running with https
*
* @return bool
*/
function is_https() {
return stripos(get_config('wwwroot'), 'https://') !== false;
}
function sanitize_email($value) {
if (filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
return '';
}
return $value;
}
function sanitize_firstname($value) {
if (!preg_match('/\S/', $value)) {
return '';
}
return $value;
}
function sanitize_lastname($value) {
if (!preg_match('/\S/', $value)) {
return '';
}
return $value;
}
function sanitize_studentid($value) {
if (!preg_match('/\S/', $value)) {
return '';
}
return $value;
}
function sanitize_preferredname($value) {
if (!preg_match('/\S/', $value)) {
return '';
}
return $value;
}
function generate_csv($data, $csvfields) {
$csv = join(',', $csvfields) . "\n";
foreach ($data as $row) {
if (is_object($row)) {
$row = (array) $row;
}
$u = array();
foreach ($csvfields as $f) {
$u[] = str_replace('"', '""', (isset($row[$f]) ? $row[$f] : 0));
}
$csv .= '"' . join('","', $u) . '"' . "\n";
}
return $csv;
}
/**
* Check to make sure table is case sensitive (currently only for MySql)
* If it is not then reduce supplied array to a case insensitive version
* Preserving the first occurance of any duplicates.
* E.g. 'Test,test,cat,TEST,CAT,Cat' will return 'Test,cat'
*
* @param array Array of case senstive strings
* @param string Name of table
*
* @return array Array of strings
*/
function check_case_sensitive($a, $table) {
if (is_mysql()) {
$db = get_config('dbname');
$table = get_config('dbprefix') . $table;
$result = get_records_sql_array("SHOW TABLE STATUS IN `$db` WHERE Name = ?", array($table));
if (is_array($result) && count($result) === 1) {
if (preg_match('/_ci/', $result[0]->Collation)) {
$b = array_unique(array_map('strtolower', $a));
$a = array_intersect_key($a, array_flip(array_keys($b)));
}
}
else {
throw new SQLException($table . " is not found or can not be accessed, check log for errors.");
}
}
return $a;
}
/**
* Check one array of associative arrays against another to see if
* there are any differences and return a merged array based on the order
* of the $first array with the differences of $second appended on
*
* @param array $first contains associative arrays
* @param array $second contains associative arrays
*
* @return array all the different associative arrays
*/
function combine_arrays($first, $second) {
foreach ($first as $k => $v) {
foreach ($second as $sk => $sv) {
$diff = array_diff($v, $sv);
if (empty($diff)) {
// arrays are the same
unset($second[$sk]);
}
}
}
$merged = array_merge($first, $second);
return $merged;
}
/**
* Returns the number of available CPU cores
*
* Should work for Linux, Windows, Mac & BSD
*
* @return integer
*
* Copyright © 2011 Erin Millard
* https://gist.github.com/ezzatron/1321581
*/
function num_cpus() {
$numCpus = 1;
if (is_file('/proc/cpuinfo')) {
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$numCpus = count($matches[0]);
}
// For Windows server users you can uncomment the following to try and access server load (experimental - use at own risk)
// else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) {
// $process = @popen('wmic cpu get NumberOfCores', 'rb');
//
// if (false !== $process) {
// fgets($process);
// $numCpus = intval(fgets($process));
// pclose($process);
// }
// }
else {
$process = @popen('sysctl -a', 'rb');
if (false !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) {
$numCpus = intval($matches[1][0]);
}
pclose($process);
}
}
return $numCpus;
}
/**
* Perform checks to see if there is enough server capacity to run a task.
*
* @param $threshold Pass in a threshold to test against - optional
* The threshold value must be in [0..1]
* 0: the server is completely idle
* 1: is fully loaded
* @return bool
* If the server is Windows, return false (bypass this feature)
*/
function server_busy($threshold = false) {
// Get current server load information - code from:
// http://www.php.net//manual/en/function.sys-getloadavg.php#107243
// For Windows server users you can uncomment the following to try and access server load (experimental - use at own risk)
if (stristr(PHP_OS, 'win')) {
// $wmi = new COM("Winmgmts://");
// $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");
// $cpu_num = 0;
// $load_total = 0;
// foreach ($server as $cpu) {
// $cpu_num++;
// $load_total += $cpu->loadpercentage;
// }
// $load = round(($load_total / $cpu_num), 2);
return false;
}
else {
$sys_load = sys_getloadavg();
$load = $sys_load[0] / num_cpus();
}
$threshold = ($threshold) ? $threshold : '0.5'; // TODO: find out a good base number
if ($load > $threshold) {
return true;
}
return false;
}
/**
* Find out a user's institution sort order for comments on artefacts within view page.
* If they belong to one institution that has specified a sort order, then this will
* be that institution's comment sort.
* If they belong to multiple institutions then the arbitrarily "first" institution's
* sort order will be used.
*
* @param int $userid Which user to check (defaults to $USER)
* @return string Sort order - either 'earliest', 'latest'.
*/
function get_user_institution_comment_sort_order($userid = null) {
$instsorts = get_configs_user_institutions('commentsortorder', $userid);
$sortorder = null;
// Every user belongs to at least one institution
foreach ($instsorts as $sort) {
// If the user belongs to multiple institutions, arbitrarily use the sort
// from the first one that has specified a sort.
if (!empty($sort)) {
$sortorder = $sort;
break;
}
}
return $sortorder;
}
/**
* Returns all directories of installed plugins except for local
* from the current codebase.
*
* This is relatively slow and not fully cached, use with care!
*
* @return array ('plugintkey' => path, ...)
* For example, array (
* 'artefact.blog' => $CFG->docroot . 'artefact/blog',
* 'blocktype.blog' => $CFG->docroot . 'artefact/blog/blocktype/blog',
* ...
* )
*/
function get_installed_plugins_paths() {
$versions = array();
// All installed plugins
$plugins = array();
foreach (plugin_types_installed() as $plugin) {
$dirhandle = opendir(get_config('docroot') . $plugin);
while (false !== ($dir = readdir($dirhandle))) {
if (strpos($dir, '.') === 0 || 'CVS' == $dir) {
continue;
}
if (!is_dir(get_config('docroot') . $plugin . '/' . $dir)) {
continue;
}
try {
validate_plugin($plugin, $dir);
$plugins[] = array($plugin, $dir);
}
catch (InstallationException $_e) {
log_warn("Plugin $plugin $dir is not installable: " . $_e->GetMessage());
}
if ($plugin === 'artefact') { // go check it for blocks as well
$btlocation = get_config('docroot') . $plugin . '/' . $dir . '/blocktype';
if (!is_dir($btlocation)) {
continue;
}
$btdirhandle = opendir($btlocation);
while (false !== ($btdir = readdir($btdirhandle))) {
if (strpos($btdir, '.') === 0 || 'CVS' == $btdir) {
continue;
}
if (!is_dir(get_config('docroot') . $plugin . '/' . $dir . '/blocktype/' . $btdir)) {
continue;
}
$plugins[] = array('blocktype', $dir . '/' . $btdir);
}
}
}
}
$pluginpaths = array();
foreach ($plugins as $plugin) {
$plugintype = $plugin[0];
$pluginname = $plugin[1];
$pluginpath = "$plugin[0]/$plugin[1]";
$pluginkey = "$plugin[0].$plugin[1]";
if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
$bits = explode('/', $pluginname);
$pluginpath = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1];
}
$pluginpaths[$pluginkey] = get_config('docroot') . $pluginpath;
}
return $pluginpaths;
}
/**
* Returns hash of all versions including core and all installed plugins except for local
* from the current codebase.
*
* This is relatively slow and not fully cached, use with care!
*
* @return string sha1 hash
*/
function get_all_versions_hash() {
$versions = array();
// Get core version
require(get_config('libroot') . 'version.php');
$versions['core'] = $config->version;
// All installed plugins
$pluginpaths = get_installed_plugins_paths();
foreach ($pluginpaths as $pluginkey => $pluginpath) {
require($pluginpath . '/version.php');
$versions[$pluginkey] = $config->version;
}
return sha1(serialize($versions));
}
/*
* Update the information on our progress so the browser can access it via
* json/progress.php.
*
* @param token (Alphanumeric) An identifier unique to the page. This
* allows multiple progress meters on different tabs of a
* browser at the same time.
* @param numerator (Int) The top number in the fraction of work done so far.
* @param denominator (Int) The bottom number in the fraction of work done so
* far. If 0, no percentage will be displayed.
* @param message A message to be displayed in the progress bar prior to the
* percentage.
*/
function set_progress_info($token, $numerator = 0, $denominator = 1, $message = '') {
global $SESSION;
$SESSION->set_progress($token, array(
'finished' => FALSE,
'numerator' => $numerator,
'denominator' => $denominator,
'message' => $message
));
}
/**
* Update the information on our progress so the browser can access it via
* json/progress.php.
*
* @param token (Alphanumeric) An identifier unique to the page. This
* allows multiple progress meters on different tabs of a
* browser at the same time.
* @param data Any data to be passed back to the browser (instructions
* for meter_update() in js/mahara.js.
*/
function set_progress_done($token, $data = array()) {
global $SESSION;
$data['finished'] = TRUE;
$SESSION->set_progress($token, $data);
}
| gpl-3.0 |
OpenGraphtheory/OpenGraphtheory | opengt.so/Sources/algorithms/directedtreewidth/directedtreewidth.cpp | 9684 |
#include "../../../Headers/algorithms/directedtreewidth/directedtreewidth.h"
//#define VERBOSEOUTPUT
// see page 8 and 9 of
// http://www.math2.rwth-aachen.de/~koster/paper/boko09a.pdf
using namespace std;
using namespace OpenGraphtheory;
using namespace OpenGraphtheory::Algorithms;
namespace OpenGraphtheory
{
namespace Algorithms
{
namespace DirectedTreewidth
{
MultiFactoryRegistrator<Algorithm> AlgorithmDIRECTEDTREEDECOMPOSITION::AlgorithmDirectedTreeDecompositionRegistrator(
&Algorithm::AlgorithmFactory, "directedtreedecomposition", new DefaultInstantiator<Algorithm, AlgorithmDIRECTEDTREEDECOMPOSITION>(
"directedtreedecomposition", "returns a directed tree-decomposition of the graph", "http://dx.doi.org/10.1006/jctb.2000.2031"));
DirectedTreeDecomposition::DirectedTreeDecomposition()
{
}
DirectedTreeDecomposition::~DirectedTreeDecomposition()
{
for(std::vector<DirectedTreeDecomposition*>::iterator i = Children.begin(); i != Children.end(); i++)
delete *i;
Children.clear();
}
bool AlgorithmDIRECTEDTREEDECOMPOSITION::FindWeaklyBalancedWSeparation(Graph& G, VertexSet& W, VertexIterator WIt,
VertexSet& X, VertexSet& S, VertexSet& Y, size_t k)
{
if(S.size() > k)
return false;
if(X.size()*4 > W.size()*3) // not balanced
return false;
if(Y.size()*4 > W.size()*3) // not balanced
return false;
if(WIt == W.end()) // all vertices are distributed
{
VertexSet Separator;
AllowedVerticesFilter VMinusS;
for(VertexIterator v = G.BeginVertices(); v != G.EndVertices(); v++)
if(S.find(*v) == S.end())
VMinusS.AllowVertex(*v);
AlgorithmVERTEXSEPARATOR separatoralgorithm;
if(!separatoralgorithm.FindMinimumVertexSeparator(G, X, Y, Separator, &VMinusS))
return false;
if(S.size() + Separator.size() > k)
return false;
SetHelper::DestructiveUnion(S,Separator);
return true;
}
VertexIterator WItNext = WIt;
WItNext++;
Vertex* pWIt = *WIt;
X.insert(pWIt); // Put WIt into X
if(FindWeaklyBalancedWSeparation(G,W,WItNext, X,S,Y, k))
return true;
X.erase(pWIt);
Y.insert(pWIt); // Put WIt into Y
if(FindWeaklyBalancedWSeparation(G,W,WItNext, X,S,Y, k))
return true;
Y.erase(pWIt);
S.insert(pWIt); // Put WIt into S
if(FindWeaklyBalancedWSeparation(G,W,WItNext, X,S,Y, k))
return true;
S.erase(pWIt);
return false;
}
DirectedTreeDecomposition* AlgorithmDIRECTEDTREEDECOMPOSITION::FindDirectedTreeDecomposition(Graph& G, VertexSet& V, VertexSet& W, size_t k)
{
#ifdef VERBOSEOUTPUT
cerr << "FindDirectedTreeDecomposition k = " << k << " V = {"; cerr.flush();
for(VertexIterator v = V.begin(); v != V.end(); v++)
cerr << (*v)->GetLabel() << " ";
cerr << "} ";
cerr << "W = {"; cerr.flush();
for(VertexIterator v = W.begin(); v != W.end(); v++)
cerr << (*v)->GetLabel() << " ";
cerr << "}\n";
#endif
cerr << "A"; cerr.flush();
DirectedTreeDecomposition* result = NULL;
// (the remnant of) V is small enough to return a single bag containing all of V
if(SetHelper::SetsEqual(V,W))
{
result = new DirectedTreeDecomposition;
result->Bag = V;
return result;
}
// find weakly balanced W separation (X,S,Y)
VertexSet X, S, Y;
if(!FindWeaklyBalancedWSeparation(G, W, W.begin(), X,S,Y, k)) // treewidth is larger than k
return NULL;
cerr << "B"; cerr.flush();
#ifdef VERBOSEOUTPUT
cerr << " Weakly Balanced W Separation: X = {"; cerr.flush();
for(VertexIterator v = X.begin(); v != X.end(); v++)
cerr << (*v)->GetLabel() << " ";
cerr << "} ";
cerr << "S = {"; cerr.flush();
for(VertexIterator v = S.begin(); v != S.end(); v++)
cerr << (*v)->GetLabel() << " ";
cerr << "} ";
cerr << "Y = {"; cerr.flush();
for(VertexIterator v = Y.begin(); v != Y.end(); v++)
cerr << (*v)->GetLabel() << " ";
cerr << "}\n";
#endif
// this only enforces termination of the algorithm (without it, the
// algorithm might alternate infinitely between two components)
if((X.empty() || Y.empty()) && SetHelper::IsSubset(S,W))
for(VertexIterator v = V.begin(); v != V.end(); v++)
if(W.find(*v) == W.end())
{
S.insert(*v);
break;
}
cerr << "C"; cerr.flush();
// determine the strong components of G[V]-S
// TODO: verify that you dont have to use all of G instead of only the local G[V]
AlgorithmSTRONGCOMPONENTS strongcomponentalgorithm;
AllowedVerticesFilter VMinusS;
for(VertexIterator v = V.begin(); v != V.end(); v++)
if(S.find(*v) == S.end())
VMinusS.AllowVertex(*v);
map<Vertex*, int> ComponentOfVertex;
vector<vector<Vertex*> > VerticesInComponent;
strongcomponentalgorithm.FindStrongComponents(G, ComponentOfVertex, VerticesInComponent, &VMinusS);
cerr << VerticesInComponent.size() << " strong components on " << W.size() << " vertices\n"; cerr.flush();
cerr << (VerticesInComponent.size() == W.size() ? "acyclic" : "cyclic") << "\n"; cerr.flush();
cerr << "D\n"; cerr.flush();
// Recurse on V' = S union C, W' = S union (W cap C) for the strong components C of G[V]-S
result = new DirectedTreeDecomposition;
for(vector<vector<Vertex*> >::iterator C = VerticesInComponent.begin(); C != VerticesInComponent.end(); C++)
{
VertexSet CSet;
for(vector<Vertex*>::iterator v = C->begin(); v != C->end(); v++)
CSet.insert(*v);
VertexSet SoC = SetHelper::Union(S, CSet);
VertexSet SoWaC = SetHelper::Union(S, SetHelper::Intersection(W,CSet));
DirectedTreeDecomposition* d = FindDirectedTreeDecomposition(G, SoC, SoWaC, k);
if(d == NULL) // treewidth is larger than k
{
delete result;
return NULL;
}
result->Children.push_back(d);
}
result->Bag = SetHelper::Union(W,S);
return result;
}
DirectedTreeDecomposition* AlgorithmDIRECTEDTREEDECOMPOSITION::FindDirectedTreeDecomposition(Graph& G, size_t k)
{
VertexIterator v = G.BeginVertices();
VertexSet W;
for(size_t i = 0; i < 2*k+2 && v != G.EndVertices(); i++, v++)
W.insert(*v);
VertexSet V;
for(v = G.BeginVertices(); v != G.EndVertices(); v++)
V.insert(*v);
return FindDirectedTreeDecomposition(G,V,W,k);
}
DirectedTreeDecomposition* AlgorithmDIRECTEDTREEDECOMPOSITION::FindDirectedTreeDecomposition(Graph& G)
{
for(size_t k = 1; ; k++)
{
cerr << "k = " << k << endl; cerr.flush();
DirectedTreeDecomposition* d = FindDirectedTreeDecomposition(G, k);
if(d != NULL)
return d;
}
}
void AlgorithmDIRECTEDTREEDECOMPOSITION::PrintDirectedTreeDecomposition(DirectedTreeDecomposition* d, size_t indent)
{
for(size_t i = 0; i < indent; i++)
cout << " ";
for(VertexIterator v = d->Bag.begin(); v != d->Bag.end(); v++)
cout << (*v)->GetLabel() << " ";
cout << "\n";
for(vector<DirectedTreeDecomposition*>::iterator c = d->Children.begin(); c != d->Children.end(); c++)
PrintDirectedTreeDecomposition(*c, indent+1);
}
void AlgorithmDIRECTEDTREEDECOMPOSITION::Run(Graph& G, std::vector<std::string> parameters)
{
if(parameters.size() < 1)
throw "directed treewidth algorithm needs 1 parameter (result name)";
string ResultName = parameters[0];
DirectedTreeDecomposition* d = FindDirectedTreeDecomposition(G);
if(d != NULL)
{
PrintDirectedTreeDecomposition(d, 0);
delete d;
}
}
}
}
}
| gpl-3.0 |
SZitzelsberger/Spreadsheet-Inspection-Framework | src/sif/frontOffice/PolicyManager.java | 7809 | package sif.frontOffice;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.TreeMap;
import sif.model.policy.Policy;
import sif.model.policy.policyrule.AbstractPolicyRule;
import sif.model.policy.policyrule.CompositePolicyRule;
import sif.model.policy.policyrule.MonolithicPolicyRule;
import sif.model.policy.policyrule.configuration.ConfigurableParameter;
import sif.model.policy.policyrule.configuration.ParameterConfiguration;
import sif.model.policy.policyrule.configuration.PolicyRuleConfiguration;
import sif.model.policy.policyrule.implementations.FormulaComplexityPolicyRule;
import sif.model.policy.policyrule.implementations.NoConstantsInFormulasPolicyRule;
import sif.model.policy.policyrule.implementations.ReadingDirectionPolicyRule;
import sif.technicalDepartment.equipment.testing.facilities.implementations.FormulaComplexityTestFacility;
import sif.technicalDepartment.equipment.testing.facilities.implementations.NoConstantsInFormulasTestFacilitiy;
import sif.technicalDepartment.equipment.testing.facilities.implementations.ReadingDirectionTestFacility;
import sif.technicalDepartment.equipment.testing.facilities.types.MonolithicTestFacility;
import sif.technicalDepartment.management.TechnicalManager;
/***
* The PolicyManager handles the management of the policies and policy rules
* that are offered by SIF. It is responsible for the registration of new
* policies and policy rules as well as their configuration. Currently available
* policies and policy rules must be hardcoded as the registered list will not
* be persisted.
*
* @author Sebastian Zitzelsberger
*
*/
public class PolicyManager {
private TreeMap<String, Class<? extends AbstractPolicyRule>> availablePolicyRules;
private TreeMap<String, Policy> availablePolicies;
protected PolicyManager() {
this.availablePolicies = new TreeMap<String, Policy>();
this.availablePolicyRules = new TreeMap<String, Class<? extends AbstractPolicyRule>>();
// Register available policy rules.
register(NoConstantsInFormulasPolicyRule.class,
NoConstantsInFormulasTestFacilitiy.class);
register(ReadingDirectionPolicyRule.class,
ReadingDirectionTestFacility.class);
register(FormulaComplexityPolicyRule.class,
FormulaComplexityTestFacility.class);
// Create and register available policy.
Policy policy = new Policy();
policy.setName("Basic Policy");
policy.setAuthor("Sebastian Zitzelsberger");
policy.setDescription("A basic policy that checks the spreadsheet for its"
+ "reading direction, constants in formulas and the complexity of formulas.");
policy.add(new NoConstantsInFormulasPolicyRule());
policy.add(new ReadingDirectionPolicyRule());
policy.add(new FormulaComplexityPolicyRule());
register(policy);
}
/**
* Checks if the given policy contains only policy rules that are registered
* with the PolicyManager.
*
* @param policy
* The given policy.
* @return Whether the given policy contains only registered policy rules.
*/
private Boolean containsOnlyRegisteredPolicyRules(Policy policy) {
Boolean result = true;
for (AbstractPolicyRule policyRule : policy.getPolicyRules().values()) {
if (!availablePolicyRules.values().contains(policyRule.getClass())) {
result = false;
break;
}
}
return result;
}
/**
* Creates the default configuration for the given policy rule.
*
* @param policyRule
* The given policy rule
* @throws Exception
*/
private void createDefaultConfigurationFor(AbstractPolicyRule policyRule) {
PolicyRuleConfiguration ruleConfiguration = new PolicyRuleConfiguration();
// Create a ParameterConfiguration for each field with an
// ConfigurableParameter annotation.
for (Field field : policyRule.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(ConfigurableParameter.class)) {
ConfigurableParameter parameter = field
.getAnnotation(ConfigurableParameter.class);
ParameterConfiguration<?> parameterConfiguration = null;
String pattern = parameter.pattern();
String name = parameter.displayedName();
String description = parameter.description();
Class<?> parameterClass = parameter.parameterClass();
field.setAccessible(true);
Object value;
try {
value = field.get(policyRule);
parameterConfiguration = ParameterConfiguration
.createParameterConfiguationFor(parameterClass,
pattern);
parameterConfiguration.setDefaultValue(value);
parameterConfiguration.setParamaterName(name);
parameterConfiguration.setDescription(description);
parameterConfiguration.setFieldName(field.getName());
ruleConfiguration.add(parameterConfiguration);
field.setAccessible(false);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
policyRule.setConfiguration(ruleConfiguration);
}
/**
* Gets the available policies that have been registered with the
* PolicyManager.
*
* @return The available policies.
*/
protected TreeMap<String, Policy> getAvailablePolicies() {
return this.availablePolicies;
}
/**
* Gets the available policy rules that haven been registered with the
* PolicyManager. Each policy rule has a default configuration.
*
* @return The available policy rules.
*/
protected ArrayList<AbstractPolicyRule> getAvailablePolicyRules() {
ArrayList<AbstractPolicyRule> rules = new ArrayList<AbstractPolicyRule>();
for (Class<? extends AbstractPolicyRule> abstractPolicyRuleClass : availablePolicyRules
.values()) {
AbstractPolicyRule rule = null;
try {
// Create a new instance from the policy rule and create a
// default configuration for it.
rule = abstractPolicyRuleClass.newInstance();
createDefaultConfigurationFor(rule);
rules.add(rule);
} catch (Exception e) {
e.printStackTrace();
}
}
return rules;
}
/***
* Register the given policy rule class.
*
* @param compositeRule
* the given policy rule class.
*/
protected void register(Class<? extends CompositePolicyRule> compositeRule) {
this.availablePolicyRules.put(compositeRule.getCanonicalName(),
compositeRule);
}
/***
* Registers the given policy rule class and associates it with the given
* test facility class.
*
* @param policyRuleClass
* The given policy rule class.
* @param testFacilityClass
* The given test facility class.
*/
protected void register(
Class<? extends MonolithicPolicyRule> policyRuleClass,
Class<? extends MonolithicTestFacility> testFacilityClass) {
TechnicalManager.getInstance().register(policyRuleClass,
testFacilityClass);
this.availablePolicyRules.put(policyRuleClass.getCanonicalName(),
policyRuleClass);
}
/***
* Registers the given policy with the PolicyManager.
*
* @param policy
* The given policy.
*/
protected void register(Policy policy) {
if (containsOnlyRegisteredPolicyRules(policy)) {
for (AbstractPolicyRule policyRule : policy.getPolicyRules()
.values()) {
if (policyRule.getConfiguration() == null) {
try {
this.createDefaultConfigurationFor(policyRule);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this.availablePolicies.put(policy.getName(), policy);
}
}
} | gpl-3.0 |
fanruan/finereport-design | designer_base/src/com/fr/design/gui/frpane/JTreeAutoBuildPane.java | 10054 | package com.fr.design.gui.frpane;
import com.fr.base.BaseFormula;
import com.fr.data.impl.NameTableData;
import com.fr.data.impl.RecursionTableData;
import com.fr.data.impl.TableDataDictionary;
import com.fr.design.DesignModelAdapter;
import com.fr.design.data.BasicTableDataTreePane;
import com.fr.design.data.DesignTableDataManager;
import com.fr.design.data.datapane.EditOrNewLabel;
import com.fr.design.data.datapane.TableDataTreePane;
import com.fr.design.data.datapane.TreeTableDataComboBox;
import com.fr.design.data.datapane.preview.PreviewLabel;
import com.fr.design.data.tabledata.wrapper.AbstractTableDataWrapper;
import com.fr.design.data.tabledata.wrapper.TableDataWrapper;
import com.fr.design.data.tabledata.wrapper.TemplateTableDataWrapper;
import com.fr.design.dialog.BasicPane;
import com.fr.design.editor.ValueEditorPane;
import com.fr.design.editor.ValueEditorPaneFactory;
import com.fr.design.editor.editor.ColumnIndexEditor;
import com.fr.design.editor.editor.ColumnNameEditor;
import com.fr.design.editor.editor.Editor;
import com.fr.design.editor.editor.FormulaEditor;
import com.fr.design.editor.editor.OldColumnIndexEditor;
import com.fr.design.gui.ilable.UILabel;
import com.fr.design.layout.FRGUIPaneFactory;
import com.fr.design.layout.TableLayout;
import com.fr.design.layout.TableLayoutHelper;
import com.fr.general.Inter;
import com.fr.stable.StringUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
public class JTreeAutoBuildPane extends BasicPane implements PreviewLabel.Previewable, EditOrNewLabel.Editable {
private TreeTableDataComboBox treeTableDataComboBox;
private ValueEditorPane valuePane;
private ValueEditorPane textPane;
private JPanel centerPane;
private JPanel selectTreeDataPanel;
public JTreeAutoBuildPane() {
this.initComponent();
}
/**
* 初始化
*/
public void initComponent() {
this.setLayout(FRGUIPaneFactory.createM_BorderLayout());
UILabel selectTreeDataLabel = new UILabel(Inter.getLocText("Select_A_Tree_DataSource_To_Build") + ": ");
treeTableDataComboBox = new TreeTableDataComboBox(DesignTableDataManager.getEditingTableDataSource());
treeTableDataComboBox.setPreferredSize(new Dimension(180, 20));
selectTreeDataPanel = FRGUIPaneFactory.createBoxFlowInnerContainer_S_Pane();
selectTreeDataPanel.add(selectTreeDataLabel);
treeTableDataComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
tdChange();
}
});
selectTreeDataPanel.add(treeTableDataComboBox);
treeTableDataComboBox.setPreferredSize(new Dimension(200, 25));
treeTableDataComboBox.setSelectedIndex(-1);
PreviewLabel pl = new PreviewLabel(this);
pl.setPreferredSize(new Dimension(25, 25));
EditOrNewLabel enl = new EditOrNewLabel(this, this);
enl.setPreferredSize(new Dimension(25, 25));
selectTreeDataPanel.add(pl);
selectTreeDataPanel.add(enl);
this.add(selectTreeDataPanel, BorderLayout.NORTH);
valuePane = ValueEditorPaneFactory.createValueEditorPane(new Editor[]{new ColumnNameEditor(), new ColumnIndexEditor()});
FormulaEditor formulaEditor = new FormulaEditor(Inter.getLocText("Parameter-Formula"));
formulaEditor.setEnabled(true);
textPane = ValueEditorPaneFactory.createValueEditorPane(new Editor[]{new ColumnNameEditor(), new ColumnIndexEditor(), formulaEditor});
Component[][] coms = {
{new UILabel(Inter.getLocText("Actual_Value") + ":"),
valuePane},
{new UILabel(Inter.getLocText("Display_Value") + ":"),
textPane}};
double p = TableLayout.PREFERRED;
double[] rowSize = {p, p, p};
double[] columnSize = {p, p};
centerPane = TableLayoutHelper.createTableLayoutPane(coms, rowSize,
columnSize);
this.add(centerPane, BorderLayout.CENTER);
tdChange();
}
private void tdChange() {
TableDataWrapper tableDataWrappe = this.treeTableDataComboBox.getSelectedItem();
if (tableDataWrappe == null) {
return;
}
try {
List<String> namelist = tableDataWrappe.calculateColumnNameList();
String[] columnNames = new String[namelist.size()];
namelist.toArray(columnNames);
valuePane.setEditors(new Editor[]{new ColumnNameEditor(columnNames), new ColumnIndexEditor(columnNames.length)}, columnNames[0]);
FormulaEditor formulaEditor = new FormulaEditor(Inter.getLocText("Parameter-Formula"));
formulaEditor.setEnabled(true);
textPane.setEditors(new Editor[]{new ColumnNameEditor(columnNames), new ColumnIndexEditor(columnNames.length), formulaEditor}, columnNames[0]);
} catch (Exception e) {
valuePane.setEditors(new Editor[]{new OldColumnIndexEditor(100, Inter.getLocText("ColumnName"))}, 1);
FormulaEditor formulaEditor = new FormulaEditor(Inter.getLocText("Parameter-Formula"));
formulaEditor.setEnabled(true);
textPane.setEditors(new Editor[]{new OldColumnIndexEditor(100, Inter.getLocText("ColumnName")), formulaEditor}, 1);
}
}
public void populate(TableDataDictionary tableDataDict) {
if (tableDataDict == null) {
this.treeTableDataComboBox.setSelectedItem("");
this.textPane.populate(1);
this.valuePane.populate(1);
return;
} else {
String _name = "";
if (tableDataDict.getTableData() instanceof NameTableData) {
_name = ((NameTableData) tableDataDict.getTableData()).getName();
}
this.treeTableDataComboBox.setSelectedTableDataByName(_name);
tdChange();
// alex:因为显示到界面上的index是以1为始的,所以要加1
if (!StringUtils.isEmpty(tableDataDict.getKeyColumnName())) {
this.valuePane.populate(tableDataDict.getKeyColumnName());
} else {
this.valuePane.populate(tableDataDict.getKeyColumnIndex() + 1);
}
Object value = null;
if ((tableDataDict).getFormula() != null) {
value = (tableDataDict).getFormula();
} else {
if (!StringUtils.isEmpty(tableDataDict.getValueColumnName())) {
value = tableDataDict.getValueColumnName();
} else {
value = tableDataDict.getValueColumnIndex() + 1;
}
}
this.textPane.populate(value);
}
}
public TableDataDictionary update() {
TableDataDictionary tableDataDict = new TableDataDictionary();
Object object = this.valuePane.update(StringUtils.EMPTY);
// alex:因为显示到界面上的index是以1为始的,所以要减1
// carl:假如这里的序号要变,请考虑6.2的兼容
if (object instanceof Object[]) {
Object[] temp = (Object[]) object;
tableDataDict.setKeyColumnIndex(((Integer) temp[0]).intValue() - 1);
tableDataDict.setKeyColumnName((String) temp[1]);
} else if (object instanceof Integer) {
tableDataDict.setKeyColumnIndex((Integer) object - 1);
} else if (object instanceof String) {
tableDataDict.setKeyColumnName((String) object);
}
Object object_text = this.textPane.update(StringUtils.EMPTY);
if (object_text instanceof Object[]) {
Object[] temp = (Object[]) object_text;
if (temp[0] instanceof BaseFormula) {
tableDataDict.setFormula((BaseFormula) temp[0]);
} else {
tableDataDict.setValueColumnIndex(((Integer) temp[0]).intValue() - 1);
tableDataDict.setValueColumnName((String) temp[1]);
}
} else if (object_text instanceof Integer) {
tableDataDict.setValueColumnIndex((Integer) this.textPane.update() - 1);
} else if (object_text instanceof String) {
tableDataDict.setValueColumnName((String) object_text);
} else {
tableDataDict.setFormula(((BaseFormula) object));
}
TableDataWrapper tableDataWrappe = this.treeTableDataComboBox.getSelectedItem();
if (tableDataWrappe != null) {
tableDataDict.setTableData(new NameTableData(tableDataWrappe.getTableDataName()));
}
return tableDataDict;
}
@Override
protected String title4PopupWindow() {
return "Auto Build Tree";
}
/**
* 预览
*/
public void preview() {
TableDataWrapper tableDataWrappe = treeTableDataComboBox.getSelectedItem();
if (tableDataWrappe == null) {
return;
}
tableDataWrappe.previewData();
}
/**
* 编辑
* @param jPanel 面板
*/
public void edit(JPanel jPanel) {
RecursionTableData rtd = null;
String name = "";
BasicTableDataTreePane tdtp = TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter());
if (treeTableDataComboBox.getSelectedItem() == null) {
//新建
rtd = new RecursionTableData();
name = TableDataTreePane.createUnrepeatedName(tdtp.getDataTree(), "Tree");
} else {
//编辑
rtd = treeTableDataComboBox.getSelcetedTableData();
name = treeTableDataComboBox.getSelectedItem().getTableDataName();
}
AbstractTableDataWrapper atdw = new TemplateTableDataWrapper(rtd, "");
tdtp.dgEdit(atdw.creatTableDataPane(), name);
treeTableDataComboBox.refresh();
treeTableDataComboBox.setSelectedTableDataByName(name);
textPane.populate(1);
valuePane.populate(1);
}
} | gpl-3.0 |
snlpatel001213/algorithmia | graph_based_segmentation/test.py | 52 | # from graph import *
#
# print(get_lattice(45,7,6)) | gpl-3.0 |
sacloud/sackerel | vendor/github.com/mackerelio/mackerel-client-go/metrics.go | 3657 | package mackerel
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
)
// MetricValue metric value
type MetricValue struct {
Name string `json:"name,omitempty"`
Time int64 `json:"time,omitempty"`
Value interface{} `json:"value,omitempty"`
}
// HostMetricValue host metric value
type HostMetricValue struct {
HostID string `json:"hostId,omitempty"`
*MetricValue
}
// LatestMetricValues latest metric value
type LatestMetricValues map[string]map[string]*MetricValue
// PostHostMetricValues post host metrics
func (c *Client) PostHostMetricValues(metricValues [](*HostMetricValue)) error {
resp, err := c.PostJSON("/api/v0/tsdb", metricValues)
defer closeResponse(resp)
return err
}
// PostHostMetricValuesByHostID post host metrics
func (c *Client) PostHostMetricValuesByHostID(hostID string, metricValues [](*MetricValue)) error {
var hostMetricValues []*HostMetricValue
for _, metricValue := range metricValues {
hostMetricValues = append(hostMetricValues, &HostMetricValue{
HostID: hostID,
MetricValue: metricValue,
})
}
return c.PostHostMetricValues(hostMetricValues)
}
// PostServiceMetricValues post service metrics
func (c *Client) PostServiceMetricValues(serviceName string, metricValues [](*MetricValue)) error {
resp, err := c.PostJSON(fmt.Sprintf("/api/v0/services/%s/tsdb", serviceName), metricValues)
defer closeResponse(resp)
return err
}
// FetchLatestMetricValues fetch latest metrics
func (c *Client) FetchLatestMetricValues(hostIDs []string, metricNames []string) (LatestMetricValues, error) {
v := url.Values{}
for _, hostID := range hostIDs {
v.Add("hostId", hostID)
}
for _, metricName := range metricNames {
v.Add("name", metricName)
}
req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", c.urlFor("/api/v0/tsdb/latest").String(), v.Encode()), nil)
if err != nil {
return nil, err
}
resp, err := c.Request(req)
defer closeResponse(resp)
if err != nil {
return nil, err
}
var data struct {
LatestMetricValues *LatestMetricValues `json:"tsdbLatest"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, err
}
return *(data.LatestMetricValues), err
}
// FetchHostMetricValues retrieves the metric values for a Host
func (c *Client) FetchHostMetricValues(hostID string, metricName string, from int64, to int64) ([]MetricValue, error) {
return c.fetchMetricValues(&hostID, nil, metricName, from, to)
}
// FetchServiceMetricValues retrieves the metric values for a Service
func (c *Client) FetchServiceMetricValues(serviceName string, metricName string, from int64, to int64) ([]MetricValue, error) {
return c.fetchMetricValues(nil, &serviceName, metricName, from, to)
}
func (c *Client) fetchMetricValues(hostID *string, serviceName *string, metricName string, from int64, to int64) ([]MetricValue, error) {
v := url.Values{}
v.Add("name", metricName)
v.Add("from", strconv.FormatInt(from, 10))
v.Add("to", strconv.FormatInt(to, 10))
url := ""
if hostID != nil {
url = "/api/v0/hosts/" + *hostID + "/metrics"
} else if serviceName != nil {
url = "/api/v0/services/" + *serviceName + "/metrics"
} else {
return nil, errors.New("specify either host or service")
}
req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", c.urlFor(url).String(), v.Encode()), nil)
if err != nil {
return nil, err
}
resp, err := c.Request(req)
defer closeResponse(resp)
if err != nil {
return nil, err
}
var data struct {
MetricValues *[]MetricValue `json:"metrics"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, err
}
return *(data.MetricValues), err
}
| gpl-3.0 |
tomas-pluskal/masscascadeknime | src/uk/ac/ebi/masscascade/knime/identification/adduct/AdductFinderNodeFactory.java | 2499 | /*
* Copyright (C) 2013 EMBL - European Bioinformatics Institute
*
* All rights reserved. This file is part of the MassCascade feature for KNIME.
*
* The feature is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* The feature is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* the feature. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Stephan Beisken - initial API and implementation
*/
package uk.ac.ebi.masscascade.knime.identification.adduct;
import org.knime.core.data.DoubleValue;
import org.knime.core.data.StringValue;
import org.knime.core.node.NodeDialogPane;
import org.knime.core.node.NodeFactory;
import org.knime.core.node.NodeView;
import uk.ac.ebi.masscascade.knime.datatypes.featuresetcell.FeatureSetValue;
import uk.ac.ebi.masscascade.knime.defaults.DefaultDialog;
import uk.ac.ebi.masscascade.parameters.Parameter;
/**
* <code>NodeFactory</code> for the "AdductFinder" Node. Detects adducts within the peaks grouped by retention time.
*
* @author Stephan Beisken
*/
public class AdductFinderNodeFactory extends NodeFactory<AdductFinderNodeModel> {
/**
* {@inheritDoc}
*/
@Override
public AdductFinderNodeModel createNodeModel() {
return new AdductFinderNodeModel();
}
/**
* {@inheritDoc}
*/
@Override
public int getNrNodeViews() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public NodeView<AdductFinderNodeModel> createNodeView(final int viewIndex, final AdductFinderNodeModel nodeModel) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDialog() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public NodeDialogPane createNodeDialogPane() {
DefaultDialog dialog = new DefaultDialog();
dialog.addColumnSelection(Parameter.FEATURE_SET_COLUMN, FeatureSetValue.class);
dialog.addColumnSelection(Parameter.LABEL_COLUMN, 1, StringValue.class);
dialog.addColumnSelection(Parameter.VALUE_COLUMN, 1, DoubleValue.class);
dialog.addTextOption(Parameter.MZ_WINDOW_PPM, 5);
return dialog.build();
}
}
| gpl-3.0 |
Booksonic-Server/madsonic-main | src/main/java/org/madsonic/domain/MusicFolderContentMadsonic.java | 1524 | /*
* This file is part of Madsonic.
*
* Madsonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Madsonic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Madsonic. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009-2016 (C) Sindre Mehus, Martin Karel
*/
package org.madsonic.domain;
import java.util.List;
import java.util.SortedMap;
/**
* @author Martin Karel
* @version $Id$
*/
public class MusicFolderContentMadsonic {
private final SortedMap<MusicIndex, List<MusicIndex.SortableArtistforGenre>> indexedArtists;
private final List<MediaFile> singleSongs;
public MusicFolderContentMadsonic(SortedMap<MusicIndex, List<MusicIndex.SortableArtistforGenre>> indexedArtists, List<MediaFile> singleSongs) {
this.indexedArtists = indexedArtists;
this.singleSongs = singleSongs;
}
public SortedMap<MusicIndex, List<MusicIndex.SortableArtistforGenre>> getIndexedArtists() {
return indexedArtists;
}
public List<MediaFile> getSingleSongs() {
return singleSongs;
}
} | gpl-3.0 |
czlee/debatekeeper | app/src/main/java/net/czlee/debatekeeper/debateformat/PrepTimeSimpleFormat.java | 2661 | /*
* Copyright (C) 2012 Chuan-Zheng Lee
*
* This file is part of the Debatekeeper app, which is licensed under the GNU
* General Public Licence version 3 (GPLv3). You can redistribute and/or modify
* it under the terms of the GPLv3, and you must not use this file except in
* compliance with the GPLv3.
*
* This app is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public Licence for more details.
*
* You should have received a copy of the GNU General Public Licence along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.czlee.debatekeeper.debateformat;
import java.util.ArrayList;
import net.czlee.debatekeeper.PrepTimeBellsManager;
/**
* PrepTimeSimpleFormat is a passive data class that holds information about a prep format.
*
* A prep format normally only defines the length of the prep time. The rest is configured
* by the user, and this class figures out the user configurations accordingly.
*
* @author Chuan-Zheng Lee
* @since 2013-01-21
*
*/
public class PrepTimeSimpleFormat extends GenericDebatePhaseFormat implements PrepTimeFormat {
protected final long mPrepLength;
protected PrepTimeBellsManager mBellsManager;
public PrepTimeSimpleFormat(long prepLength) {
super();
this.mPrepLength = prepLength;
}
//******************************************************************************************
// Public methods
//******************************************************************************************
public void setBellsManager(PrepTimeBellsManager manager) {
this.mBellsManager = manager;
}
@Override
public long getLength() {
return mPrepLength;
}
@Override
public boolean isControlled() {
return false;
}
@Override
public boolean isPrep() {
return true;
}
//******************************************************************************************
// Protected and private methods
//******************************************************************************************
@Override
protected ArrayList<BellInfo> getBells() {
if (mBellsManager == null) {
ArrayList<BellInfo> bells = new ArrayList<>(1);
bells.add(getFinishBell());
return bells;
} else {
return mBellsManager.getBellsList(getLength());
}
}
private BellInfo getFinishBell() {
return new BellInfo(getLength(), 2);
}
}
| gpl-3.0 |
marionleborgne/sensor-data-app | database/generate_openbci_cassandra_schema.py | 1150 | __author__ = 'mleborgne'
# column family names and the associated number of columns per family
SENSOR = 'openbci'
KEYSPACE = SENSOR
METRICS = ['channel_0', 'channel_1', 'channel_2', 'channel_3', 'channel_4', 'channel_5', 'channel_6', 'channel_7']
COLUMNS = ['metric_value', 'prediction', 'anomaly_score', 'anomaly_likelihood']
SENSOR_ID = 'openbci_marion'
FILE_NAME = '%s_cassandra_schema.cql' % SENSOR_ID
# templates for column family creation
create_column_family_template = "CREATE TABLE %s (%s, PRIMARY KEY (sensor_id, timestamp)); \n"
f = open(FILE_NAME, 'w')
setup = """
DROP KEYSPACE %s;
CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3 };
USE %s;
""" % (KEYSPACE, KEYSPACE, KEYSPACE)
f.write(setup)
for metric in METRICS:
column_family_name = '%s' % (metric)
columns = 'sensor_id text, timestamp timestamp'
for column in COLUMNS:
columns += ', %s double' % column
create_column_family = create_column_family_template % (column_family_name, columns)
print create_column_family
f.write(create_column_family)
f.close()
print "\n==> Output written to file '%s'" % FILE_NAME
| gpl-3.0 |
RemyG/MicroBlog | modules/admin/views/view_connection.php | 624 | <div class="upload_picture">
<div class="upload_picture_title">Connection</div>
<form method="post" action="">
<div class="upload_picture_row">
<label for="login" class="upload_picture">Login : </label>
<input type=text" name="login" class="upload_picture" />
</div>
<div class="upload_picture_row">
<label for="password" class="upload_picture">Password : </label>
<input type="password" name="password" class="upload_picture" />
</div>
<div class="upload_picture_row">
<label class="upload_picture"></label>
<input type="submit" class="upload_picture" />
</div>
</form>
</div> | gpl-3.0 |
nipunn1313/parity | parity/blockchain.rs | 15472 | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::str::{FromStr, from_utf8};
use std::{io, fs};
use std::io::{BufReader, BufRead};
use std::time::{Instant, Duration};
use std::thread::sleep;
use std::sync::Arc;
use rustc_serialize::hex::FromHex;
use util::{ToPretty, U256, H256, Address, Hashable};
use rlp::PayloadInfo;
use ethcore::service::ClientService;
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, BlockImportError, BlockChainClient, BlockId};
use ethcore::error::ImportError;
use ethcore::miner::Miner;
use ethcore::verification::queue::VerifierSettings;
use cache::CacheConfig;
use informant::{Informant, MillisecondDuration};
use params::{SpecType, Pruning, Switch, tracing_switch_to_bool, fatdb_switch_to_bool};
use helpers::{to_client_config, execute_upgrades};
use dir::Directories;
use user_defaults::UserDefaults;
use fdlimit;
#[derive(Debug, PartialEq)]
pub enum DataFormat {
Hex,
Binary,
}
impl Default for DataFormat {
fn default() -> Self {
DataFormat::Binary
}
}
impl FromStr for DataFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"binary" | "bin" => Ok(DataFormat::Binary),
"hex" => Ok(DataFormat::Hex),
x => Err(format!("Invalid format: {}", x))
}
}
}
#[derive(Debug, PartialEq)]
pub enum BlockchainCmd {
Kill(KillBlockchain),
Import(ImportBlockchain),
Export(ExportBlockchain),
ExportState(ExportState),
}
#[derive(Debug, PartialEq)]
pub struct KillBlockchain {
pub spec: SpecType,
pub dirs: Directories,
pub pruning: Pruning,
}
#[derive(Debug, PartialEq)]
pub struct ImportBlockchain {
pub spec: SpecType,
pub cache_config: CacheConfig,
pub dirs: Directories,
pub file_path: Option<String>,
pub format: Option<DataFormat>,
pub pruning: Pruning,
pub pruning_history: u64,
pub pruning_memory: usize,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub tracing: Switch,
pub fat_db: Switch,
pub vm_type: VMType,
pub check_seal: bool,
pub with_color: bool,
pub verifier_settings: VerifierSettings,
}
#[derive(Debug, PartialEq)]
pub struct ExportBlockchain {
pub spec: SpecType,
pub cache_config: CacheConfig,
pub dirs: Directories,
pub file_path: Option<String>,
pub format: Option<DataFormat>,
pub pruning: Pruning,
pub pruning_history: u64,
pub pruning_memory: usize,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub fat_db: Switch,
pub tracing: Switch,
pub from_block: BlockId,
pub to_block: BlockId,
pub check_seal: bool,
}
#[derive(Debug, PartialEq)]
pub struct ExportState {
pub spec: SpecType,
pub cache_config: CacheConfig,
pub dirs: Directories,
pub file_path: Option<String>,
pub format: Option<DataFormat>,
pub pruning: Pruning,
pub pruning_history: u64,
pub pruning_memory: usize,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub fat_db: Switch,
pub tracing: Switch,
pub at: BlockId,
pub storage: bool,
pub code: bool,
pub min_balance: Option<U256>,
pub max_balance: Option<U256>,
}
pub fn execute(cmd: BlockchainCmd) -> Result<(), String> {
match cmd {
BlockchainCmd::Kill(kill_cmd) => kill_db(kill_cmd),
BlockchainCmd::Import(import_cmd) => execute_import(import_cmd),
BlockchainCmd::Export(export_cmd) => execute_export(export_cmd),
BlockchainCmd::ExportState(export_cmd) => execute_export_state(export_cmd),
}
}
fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let timer = Instant::now();
// load spec file
let spec = cmd.spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = cmd.dirs.database(genesis_hash, None, spec.data_dir.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit();
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = tracing_switch_to_bool(cmd.tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm)?;
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
execute_upgrades(&cmd.dirs.base, &db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// create dirs used by parity
cmd.dirs.create_dirs(false, false, false)?;
// prepare client config
let mut client_config = to_client_config(
&cmd.cache_config,
spec.name.to_lowercase(),
Mode::Active,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
"".into(),
algorithm,
cmd.pruning_history,
cmd.pruning_memory,
cmd.check_seal
);
client_config.queue.verifier_settings = cmd.verifier_settings;
// build client
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e))?;
// free up the spec in memory.
drop(spec);
let client = service.client();
let mut instream: Box<io::Read> = match cmd.file_path {
Some(f) => Box::new(fs::File::open(&f).map_err(|_| format!("Cannot open given file: {}", f))?),
None => Box::new(io::stdin()),
};
const READAHEAD_BYTES: usize = 8;
let mut first_bytes: Vec<u8> = vec![0; READAHEAD_BYTES];
let mut first_read = 0;
let format = match cmd.format {
Some(format) => format,
None => {
first_read = instream.read(&mut first_bytes).map_err(|_| "Error reading from the file/stream.")?;
match first_bytes[0] {
0xf9 => DataFormat::Binary,
_ => DataFormat::Hex,
}
}
};
let informant = Arc::new(Informant::new(client.clone(), None, None, None, None, cmd.with_color));
service.register_io_handler(informant).map_err(|_| "Unable to register informant handler".to_owned())?;
let do_import = |bytes| {
while client.queue_info().is_full() { sleep(Duration::from_secs(1)); }
match client.import_block(bytes) {
Err(BlockImportError::Import(ImportError::AlreadyInChain)) => {
trace!("Skipping block already in chain.");
}
Err(e) => {
return Err(format!("Cannot import block: {:?}", e));
},
Ok(_) => {},
}
Ok(())
};
match format {
DataFormat::Binary => {
loop {
let mut bytes = if first_read > 0 {first_bytes.clone()} else {vec![0; READAHEAD_BYTES]};
let n = if first_read > 0 {
first_read
} else {
instream.read(&mut bytes).map_err(|_| "Error reading from the file/stream.")?
};
if n == 0 { break; }
first_read = 0;
let s = PayloadInfo::from(&bytes).map_err(|e| format!("Invalid RLP in the file/stream: {:?}", e))?.total();
bytes.resize(s, 0);
instream.read_exact(&mut bytes[n..]).map_err(|_| "Error reading from the file/stream.")?;
do_import(bytes)?;
}
}
DataFormat::Hex => {
for line in BufReader::new(instream).lines() {
let s = line.map_err(|_| "Error reading from the file/stream.")?;
let s = if first_read > 0 {from_utf8(&first_bytes).unwrap().to_owned() + &(s[..])} else {s};
first_read = 0;
let bytes = s.from_hex().map_err(|_| "Invalid hex in file/stream.")?;
do_import(bytes)?;
}
}
}
client.flush_queue();
// save user defaults
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
user_defaults.fat_db = fat_db;
user_defaults.save(&user_defaults_path)?;
let report = client.report();
let ms = timer.elapsed().as_milliseconds();
info!("Import completed in {} seconds, {} blocks, {} blk/s, {} transactions, {} tx/s, {} Mgas, {} Mgas/s",
ms / 1000,
report.blocks_imported,
(report.blocks_imported * 1000) as u64 / ms,
report.transactions_applied,
(report.transactions_applied * 1000) as u64 / ms,
report.gas_processed / From::from(1_000_000),
(report.gas_processed / From::from(ms * 1000)).low_u64(),
);
Ok(())
}
fn start_client(
dirs: Directories,
spec: SpecType,
pruning: Pruning,
pruning_history: u64,
pruning_memory: usize,
tracing: Switch,
fat_db: Switch,
compaction: DatabaseCompactionProfile,
wal: bool,
cache_config: CacheConfig,
require_fat_db: bool,
) -> Result<ClientService, String> {
// load spec file
let spec = spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = dirs.database(genesis_hash, None, spec.data_dir.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit();
// select pruning algorithm
let algorithm = pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = tracing_switch_to_bool(tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = fatdb_switch_to_bool(fat_db, &user_defaults, algorithm)?;
if !fat_db && require_fat_db {
return Err("This command requires Parity to be synced with --fat-db on.".to_owned());
}
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
execute_upgrades(&dirs.base, &db_dirs, algorithm, compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// create dirs used by parity
dirs.create_dirs(false, false, false)?;
// prepare client config
let client_config = to_client_config(
&cache_config,
spec.name.to_lowercase(),
Mode::Active,
tracing,
fat_db,
compaction,
wal,
VMType::default(),
"".into(),
algorithm,
pruning_history,
pruning_memory,
true,
);
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e))?;
drop(spec);
Ok(service)
}
fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
let service = start_client(
cmd.dirs,
cmd.spec,
cmd.pruning,
cmd.pruning_history,
cmd.pruning_memory,
cmd.tracing,
cmd.fat_db,
cmd.compaction,
cmd.wal,
cmd.cache_config,
false,
)?;
let format = cmd.format.unwrap_or_default();
let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path {
Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?),
None => Box::new(io::stdout()),
};
let from = client.block_number(cmd.from_block).ok_or("From block could not be found")?;
let to = client.block_number(cmd.to_block).ok_or("To block could not be found")?;
for i in from..(to + 1) {
if i % 10000 == 0 {
info!("#{}", i);
}
let b = client.block(BlockId::Number(i)).ok_or("Error exporting incomplete chain")?.into_inner();
match format {
DataFormat::Binary => { out.write(&b).expect("Couldn't write to stream."); }
DataFormat::Hex => { out.write_fmt(format_args!("{}", b.pretty())).expect("Couldn't write to stream."); }
}
}
info!("Export completed.");
Ok(())
}
fn execute_export_state(cmd: ExportState) -> Result<(), String> {
let service = start_client(
cmd.dirs,
cmd.spec,
cmd.pruning,
cmd.pruning_history,
cmd.pruning_memory,
cmd.tracing,
cmd.fat_db,
cmd.compaction,
cmd.wal,
cmd.cache_config,
true
)?;
let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path {
Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?),
None => Box::new(io::stdout()),
};
let mut last: Option<Address> = None;
let at = cmd.at;
let mut i = 0usize;
out.write_fmt(format_args!("{{ \"state\": {{", )).expect("Couldn't write to stream.");
loop {
let accounts = client.list_accounts(at, last.as_ref(), 1000).ok_or("Specified block not found")?;
if accounts.is_empty() {
break;
}
for account in accounts.into_iter() {
let balance = client.balance(&account, at).unwrap_or_else(U256::zero);
if cmd.min_balance.map_or(false, |m| balance < m) || cmd.max_balance.map_or(false, |m| balance > m) {
last = Some(account);
continue; //filtered out
}
if i != 0 {
out.write(b",").expect("Write error");
}
out.write_fmt(format_args!("\n\"0x{}\": {{\"balance\": \"{:x}\", \"nonce\": \"{:x}\"", account.hex(), balance, client.nonce(&account, at).unwrap_or_else(U256::zero))).expect("Write error");
let code = client.code(&account, at).unwrap_or(None).unwrap_or_else(Vec::new);
if !code.is_empty() {
out.write_fmt(format_args!(", \"code_hash\": \"0x{}\"", code.sha3().hex())).expect("Write error");
if cmd.code {
out.write_fmt(format_args!(", \"code\": \"{}\"", code.to_hex())).expect("Write error");
}
}
let storage_root = client.storage_root(&account, at).unwrap_or(::util::SHA3_NULL_RLP);
if storage_root != ::util::SHA3_NULL_RLP {
out.write_fmt(format_args!(", \"storage_root\": \"0x{}\"", storage_root.hex())).expect("Write error");
if cmd.storage {
out.write_fmt(format_args!(", \"storage\": {{")).expect("Write error");
let mut last_storage: Option<H256> = None;
loop {
let keys = client.list_storage(at, &account, last_storage.as_ref(), 1000).ok_or("Specified block not found")?;
if keys.is_empty() {
break;
}
for key in keys.into_iter() {
if last_storage.is_some() {
out.write(b",").expect("Write error");
}
out.write_fmt(format_args!("\n\t\"0x{}\": \"0x{}\"", key.hex(), client.storage_at(&account, &key, at).unwrap_or_else(Default::default).hex())).expect("Write error");
last_storage = Some(key);
}
}
out.write(b"\n}").expect("Write error");
}
}
out.write(b"}").expect("Write error");
i += 1;
if i % 10000 == 0 {
info!("Account #{}", i);
}
last = Some(account);
}
}
out.write_fmt(format_args!("\n}}}}")).expect("Write error");
info!("Export completed.");
Ok(())
}
pub fn kill_db(cmd: KillBlockchain) -> Result<(), String> {
let spec = cmd.spec.spec()?;
let genesis_hash = spec.genesis_header().hash();
let db_dirs = cmd.dirs.database(genesis_hash, None, spec.data_dir);
let user_defaults_path = db_dirs.user_defaults_path();
let user_defaults = UserDefaults::load(&user_defaults_path)?;
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
let dir = db_dirs.db_path(algorithm);
fs::remove_dir_all(&dir).map_err(|e| format!("Error removing database: {:?}", e))?;
info!("Database deleted.");
Ok(())
}
#[cfg(test)]
mod test {
use super::DataFormat;
#[test]
fn test_data_format_parsing() {
assert_eq!(DataFormat::Binary, "binary".parse().unwrap());
assert_eq!(DataFormat::Binary, "bin".parse().unwrap());
assert_eq!(DataFormat::Hex, "hex".parse().unwrap());
}
}
| gpl-3.0 |
jorisros/sfBootstrapPlugin | data/generator/sfPropelModule/bootstrap/template/templates/_list_field_boolean.php | 204 | [?php if ($value): ?]
<span class="glyphicon glyphicon-ok" aria-hidden="Center Align"></span>
[?php else: ?]
<span class="glyphicon glyphicon-remove" aria-hidden="Center Align"></span>
[?php endif; ?]
| gpl-3.0 |
EbenZhang/gitextensions | GitUI/CommandsDialogs/SettingsDialog/Plugins/PluginSettingsPage.cs | 2261 | using System;
using System.Collections.Generic;
using System.Linq;
using GitUIPluginInterfaces;
namespace GitUI.CommandsDialogs.SettingsDialog.Plugins
{
public partial class PluginSettingsPage : AutoLayoutSettingsPage
{
private IGitPlugin _gitPlugin;
private GitPluginSettingsContainer _settingsContainer;
public PluginSettingsPage()
{
InitializeComponent();
}
private void CreateSettingsControls()
{
var settings = GetSettings();
foreach (var setting in settings)
{
AddSettingControl(setting.CreateControlBinding());
}
}
private void Init(IGitPlugin gitPlugin)
{
_gitPlugin = gitPlugin;
_settingsContainer = new GitPluginSettingsContainer(gitPlugin.Name);
CreateSettingsControls();
InitializeComplete();
}
public static PluginSettingsPage CreateSettingsPageFromPlugin(ISettingsPageHost pageHost, IGitPlugin gitPlugin)
{
var result = Create<PluginSettingsPage>(pageHost);
result.Init(gitPlugin);
return result;
}
protected override ISettingsSource GetCurrentSettings()
{
_settingsContainer.SetSettingsSource(base.GetCurrentSettings());
return _settingsContainer;
}
public override string GetTitle()
{
return _gitPlugin is null ? string.Empty : _gitPlugin.Description;
}
private IEnumerable<ISetting> GetSettings()
{
if (_gitPlugin is null)
{
throw new ApplicationException();
}
return _gitPlugin.HasSettings ? _gitPlugin.GetSettings() : Array.Empty<ISetting>();
}
public override SettingsPageReference PageReference => new SettingsPageReferenceByType(_gitPlugin.GetType());
protected override ISettingsLayout CreateSettingsLayout()
{
labelNoSettings.Visible = !_gitPlugin.HasSettings;
var layout = base.CreateSettingsLayout();
tableLayoutPanel1.Controls.Add(layout.GetControl(), 0, 1);
return layout;
}
}
}
| gpl-3.0 |
anupkdas-nus/global_synapses | pyNN-dispackgaes/nest/simulator.py | 8276 | # encoding: utf-8
"""
Implementation of the "low-level" functionality used by the common
implementation of the API, for the NEST simulator.
Classes and attributes usable by the common implementation:
Classes:
ID
Connection
Attributes:
state -- a singleton instance of the _State class.
All other functions and classes are private, and should not be used by other
modules.
:copyright: Copyright 2006-2016 by the PyNN team, see AUTHORS.
:license: CeCILL, see LICENSE for details.
"""
import nest
import logging
import tempfile
import numpy
from pyNN import common
from pyNN.core import reraise
logger = logging.getLogger("PyNN")
name = "NEST" # for use in annotating output data
# --- For implementation of get_time_step() and similar functions --------------
def nest_property(name, dtype):
"""Return a property that accesses a NEST kernel parameter"""
def _get(self):
return nest.GetKernelStatus(name)
def _set(self, val):
try:
nest.SetKernelStatus({name: dtype(val)})
except nest.NESTError as e:
reraise(e, "%s = %s (%s)" % (name, val, type(val)))
return property(fget=_get, fset=_set)
class _State(common.control.BaseState):
"""Represent the simulator state."""
def __init__(self):
super(_State, self).__init__()
self.initialized = False
self.optimize = False
self.spike_precision = "off_grid"
self.verbosity = "warning"
self._cache_num_processes = nest.GetKernelStatus()['num_processes'] # avoids blocking if only some nodes call num_processes
# do the same for rank?
# allow NEST to erase previously written files (defaut with all the other simulators)
nest.SetKernelStatus({'overwrite_files': True})
self.tempdirs = []
self.recording_devices = []
self.populations = [] # needed for reset
@property
def t(self):
return max(nest.GetKernelStatus('time') - self.dt, 0.0) # note that we always simulate one time step past the requested time
dt = nest_property('resolution', float)
threads = nest_property('local_num_threads', int)
grng_seed = nest_property('grng_seed', int)
rng_seeds = nest_property('rng_seeds', list)
@property
def min_delay(self):
return nest.GetKernelStatus('min_delay')
def set_delays(self, min_delay, max_delay):
if min_delay != 'auto':
min_delay = float(min_delay)
max_delay = float(max_delay)
nest.SetKernelStatus({'min_delay': min_delay,
'max_delay': max_delay})
@property
def max_delay(self):
return nest.GetKernelStatus('max_delay')
@property
def num_processes(self):
return self._cache_num_processes
@property
def mpi_rank(self):
return nest.Rank()
def _get_spike_precision(self):
ogs = nest.GetKernelStatus('off_grid_spiking')
return ogs and "off_grid" or "on_grid"
def _set_spike_precision(self, precision):
if precision == 'off_grid':
nest.SetKernelStatus({'off_grid_spiking': True})
self.default_recording_precision = 15
elif precision == 'on_grid':
nest.SetKernelStatus({'off_grid_spiking': False})
self.default_recording_precision = 3
else:
raise ValueError("spike_precision must be 'on_grid' or 'off_grid'")
spike_precision = property(fget=_get_spike_precision, fset=_set_spike_precision)
def _set_verbosity(self, verbosity):
nest.sli_run("M_%s setverbosity" % verbosity.upper())
verbosity = property(fset=_set_verbosity)
def run(self, simtime):
"""Advance the simulation for a certain time."""
for population in self.populations:
if population._deferred_parrot_connections:
population._connect_parrot_neurons()
for device in self.recording_devices:
if not device._connected:
device.connect_to_cells()
device._local_files_merged = False
if not self.running and simtime > 0:
simtime += self.dt # we simulate past the real time by one time step, otherwise NEST doesn't give us all the recorded data
self.running = True
if simtime > 0:
nest.Simulate(simtime)
def run_until(self, tstop):
self.run(tstop - self.t)
def reset(self):
nest.ResetNetwork()
nest.SetKernelStatus({'time': 0.0})
for p in self.populations:
for variable, initial_value in p.initial_values.items():
p._set_initial_value_array(variable, initial_value)
self.running = False
self.t_start = 0.0
self.segment_counter += 1
def clear(self):
self.populations = []
self.recording_devices = []
self.recorders = set()
# clear the sli stack, if this is not done --> memory leak cause the stack increases
nest.sr('clear')
# reset the simulation kernel
nest.ResetKernel()
# set tempdir
tempdir = tempfile.mkdtemp()
self.tempdirs.append(tempdir) # append tempdir to tempdirs list
nest.SetKernelStatus({'data_path': tempdir, })
self.segment_counter = -1
self.reset()
# --- For implementation of access to individual neurons' parameters -----------
class ID(int, common.IDMixin):
__doc__ = common.IDMixin.__doc__
def __init__(self, n):
"""Create an ID object with numerical value `n`."""
int.__init__(n)
common.IDMixin.__init__(self)
# --- For implementation of connect() and Connector classes --------------------
class Connection(common.Connection):
"""
Provide an interface that allows access to the connection's weight, delay
and other attributes.
"""
def __init__(self, parent, index):
"""
Create a new connection interface.
`parent` -- a Projection instance.
`index` -- the index of this connection in the parent.
"""
self.parent = parent
self.index = index
def id(self):
"""Return a tuple of arguments for `nest.GetConnection()`.
"""
return self.parent.nest_connections[self.index]
@property
def source(self):
"""The ID of the pre-synaptic neuron."""
src = ID(nest.GetStatus([self.id()], 'source')[0])
src.parent = self.parent.pre
return src
presynaptic_cell = source
@property
def target(self):
"""The ID of the post-synaptic neuron."""
tgt = ID(nest.GetStatus([self.id()], 'target')[0])
tgt.parent = self.parent.post
return tgt
postsynaptic_cell = target
def _set_weight(self, w):
nest.SetStatus([self.id()], 'weight', w * 1000.0)
def _get_weight(self):
"""Synaptic weight in nA or µS."""
w_nA = nest.GetStatus([self.id()], 'weight')[0]
if self.parent.synapse_type == 'inhibitory' and common.is_conductance(self.target):
w_nA *= -1 # NEST uses negative values for inhibitory weights, even if these are conductances
return 0.001 * w_nA
def _set_delay(self, d):
nest.SetStatus([self.id()], 'delay', d)
def _get_delay(self):
"""Synaptic delay in ms."""
return nest.GetStatus([self.id()], 'delay')[0]
weight = property(_get_weight, _set_weight)
delay = property(_get_delay, _set_delay)
def generate_synapse_property(name):
def _get(self):
return nest.GetStatus([self.id()], name)[0]
def _set(self, val):
nest.SetStatus([self.id()], name, val)
return property(_get, _set)
setattr(Connection, 'U', generate_synapse_property('U'))
setattr(Connection, 'tau_rec', generate_synapse_property('tau_rec'))
setattr(Connection, 'tau_facil', generate_synapse_property('tau_fac'))
setattr(Connection, 'u0', generate_synapse_property('u0'))
setattr(Connection, '_tau_psc', generate_synapse_property('tau_psc'))
# --- Initialization, and module attributes ------------------------------------
state = _State() # a Singleton, so only a single instance ever exists
del _State
| gpl-3.0 |
dlech/NXTCamView | NXTCamView/StripCommands/SaveFileStripCommand.cs | 2135 | //
// Copyright 2007 Paul Tingey
//
// This file is part of NXTCamView.
//
// NXTCamView is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Foobar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System.Windows.Forms;
using NXTCamView.Core;
using NXTCamView.Core.Comms;
using NXTCamView.Forms;
namespace NXTCamView.StripCommands
{
public class OpenFileStripCommand : StripCommand
{
private readonly MainForm _mainForm;
private readonly OpenFileDialog _openFileDialog;
private readonly ICommsPort _commsPort;
private readonly ColorForm _colorForm;
public OpenFileStripCommand(IAppState appState, MainForm mainForm, ColorForm colorForm, OpenFileDialog openFileDialog, ICommsPort commsPort) : base(appState)
{
_mainForm = mainForm;
_colorForm = colorForm;
_commsPort = commsPort;
_openFileDialog = openFileDialog;
}
public override bool CanExecute()
{
return true;
}
public override bool Execute()
{
if (_openFileDialog.ShowDialog() == DialogResult.OK)
{
var form = new CaptureForm( _appState, _colorForm, _commsPort ) {MdiParent = _mainForm};
form.Show();
form.LoadFile(_openFileDialog.FileName);
return true;
}
return false;
}
public override bool HasExecuted()
{
return false;
}
}
} | gpl-3.0 |
EbenZhang/gitextensions | UnitTests/CommonTestUtils/MockExecutable.cs | 7099 | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GitCommands;
using GitUI;
using GitUIPluginInterfaces;
using JetBrains.Annotations;
using NUnit.Framework;
namespace CommonTestUtils
{
public sealed class MockExecutable : IExecutable
{
private readonly ConcurrentDictionary<string, ConcurrentStack<(string output, int? exitCode)>> _outputStackByArguments = new ConcurrentDictionary<string, ConcurrentStack<(string output, int? exitCode)>>();
private readonly ConcurrentDictionary<string, int> _commandArgumentsSet = new ConcurrentDictionary<string, int>();
private readonly List<MockProcess> _processes = new List<MockProcess>();
private int _nextCommandId;
[MustUseReturnValue]
public IDisposable StageOutput(string arguments, string output, int? exitCode = 0)
{
var stack = _outputStackByArguments.GetOrAdd(
arguments,
args => new ConcurrentStack<(string output, int? exitCode)>());
stack.Push((output, exitCode));
return new DelegateDisposable(
() =>
{
if (_outputStackByArguments.TryGetValue(arguments, out var s) &&
s.TryPeek(out var r) &&
ReferenceEquals(output, r))
{
throw new AssertionException($"Staged output should have been consumed.\nArguments: {arguments}\nOutput: {output}");
}
});
}
[MustUseReturnValue]
public IDisposable StageCommand(string arguments)
{
var id = Interlocked.Increment(ref _nextCommandId);
_commandArgumentsSet[arguments] = id;
return new DelegateDisposable(
() =>
{
if (_commandArgumentsSet.TryGetValue(arguments, out var storedId) && storedId != id)
{
throw new AssertionException($"Staged command should have been consumed.\nArguments: {arguments}");
}
});
}
public bool Exists()
{
return true;
}
public void Verify()
{
Assert.IsEmpty(_outputStackByArguments, "All staged output should have been consumed.");
Assert.IsEmpty(_commandArgumentsSet, "All staged output should have been consumed.");
foreach (var process in _processes)
{
process.Verify();
}
}
public IProcess Start(ArgumentString arguments, bool createWindow, bool redirectInput, bool redirectOutput, Encoding outputEncoding, bool useShellExecute = false)
{
if (_outputStackByArguments.TryRemove(arguments, out var queue) && queue.TryPop(out var item))
{
if (queue.Count == 0)
{
_outputStackByArguments.TryRemove(arguments, out _);
}
var process = new MockProcess(item.output, item.exitCode);
_processes.Add(process);
return process;
}
if (_commandArgumentsSet.TryRemove(arguments, out _))
{
var process = new MockProcess();
_processes.Add(process);
return process;
}
throw new Exception("Unexpected arguments: " + arguments);
}
public string GetOutput(ArgumentString arguments)
{
if (_outputStackByArguments.TryRemove(arguments, out var queue) && queue.TryPop(out var item))
{
if (queue.Count == 0)
{
_outputStackByArguments.TryRemove(arguments, out _);
}
return item.output;
}
if (_commandArgumentsSet.TryRemove(arguments, out _))
{
return "";
}
throw new Exception("Unexpected arguments: " + arguments);
}
private sealed class MockProcess : IProcess
{
public MockProcess([CanBeNull] string output, int? exitCode = 0)
{
StandardOutput = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(output ?? "")));
StandardError = new StreamReader(new MemoryStream());
StandardInput = new StreamWriter(new MemoryStream());
_exitCode = exitCode;
}
public MockProcess()
{
StandardOutput = new StreamReader(new MemoryStream());
StandardError = new StreamReader(new MemoryStream());
StandardInput = new StreamWriter(new MemoryStream());
_exitCode = 0;
}
private int? _exitCode;
public StreamWriter StandardInput { get; }
public StreamReader StandardOutput { get; }
public StreamReader StandardError { get; }
public int WaitForExit()
{
return ThreadHelper.JoinableTaskFactory.Run(() => WaitForExitAsync());
}
public Task<int> WaitForExitAsync()
{
if (_exitCode.HasValue)
{
return Task.FromResult(_exitCode.Value);
}
else
{
var cts = new CancellationTokenSource();
var ct = cts.Token;
cts.Cancel();
return Task.FromCanceled<int>(ct);
}
}
public void WaitForInputIdle()
{
// TODO implement if needed
}
public void Dispose()
{
// TODO implement if needed
}
public void Verify()
{
// all output should have been read
Assert.AreEqual(StandardOutput.BaseStream.Length, StandardOutput.BaseStream.Position);
Assert.AreEqual(StandardError.BaseStream.Length, StandardError.BaseStream.Position);
// Only verify if std input is not closed.
// ExecutableExtensions.ExecuteAsync will close std input when writeInput action is specified
if (StandardInput.BaseStream is not null)
{
// no input should have been written (yet)
Assert.AreEqual(0, StandardInput.BaseStream.Length);
}
}
}
private sealed class DelegateDisposable : IDisposable
{
private readonly Action _disposeAction;
public DelegateDisposable(Action disposeAction)
{
_disposeAction = disposeAction;
}
public void Dispose()
{
_disposeAction();
}
}
}
}
| gpl-3.0 |
musxav/operaprog | Oprog/WNUsuari.xaml.cs | 597 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Oprog
{
/// <summary>
/// Lógica de interacción para WNUsuari.xaml
/// </summary>
public partial class WNUsuari : Window
{
public WNUsuari()
{
InitializeComponent();
}
}
}
| mpl-2.0 |
zhougithui/bookstore-single | src/main/java/org/bear/bookstore/common/interceptor/SensitiveWordInterceptor.java | 914 | package org.bear.bookstore.common.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class SensitiveWordInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
| mpl-2.0 |
mozilla/remote-newtab | bin/generate-directories.js | 2551 | #! /usr/bin/env node
"use strict";
const glob = require("glob");
const path = require("path");
const fs = require("fs-extra")
const generateHtml = require("./generate-html");
const generateLocaleData = require("./generate-locale-data");
const PAGE_TITLE_KEY = "newtab-pageTitle";
const JS_FILENAME = "locale-data.js";
const defaults = {
outputPath: path.join(__dirname, "../build"),
i10nPath: path.join(__dirname, "../l10n"),
staticPath: path.join(__dirname, "../www"),
channels: ["nightly", "aurora", "beta", "release", "esr"]
}
class DirectoryGenerator {
constructor(rawOptions) {
const options = Object.assign({}, defaults, rawOptions);
Object.keys(options).forEach(key => this[key] = options[key]);
this.locales = glob.sync(`${this.i10nPath}/*/`).map(file => path.relative(this.i10nPath, file));
this.staticFiles = glob.sync(`${this.staticPath}/**/*`).map(file => path.relative(this.staticPath, file));
}
outputFiles(options) {
const js = options.js;
const html = options.html;
const dirPath = options.dirPath;
const jsPath = path.join(dirPath, JS_FILENAME);
const htmlPath = path.join(dirPath, "index.html");
this.staticFiles.forEach(file => {
fs.copySync(path.join(this.staticPath, file), path.join(dirPath, file));
});
fs.outputFileSync(jsPath, js, "utf8");
fs.outputFileSync(htmlPath, html, "utf8");
}
generateForLocale(locale) {
const localeData = generateLocaleData(locale);
const messages = localeData.messages;
const js = localeData.fileString;
const html = generateHtml({
title: messages[PAGE_TITLE_KEY] || "New Tab",
locale,
paths: {
localeData: JS_FILENAME,
js: "main.js",
css: "main.css"
// TODO prerender
}
});
this.channels.forEach(channel => {
this.outputFiles({html, js, dirPath: path.join(this.outputPath, channel, locale)});
});
}
run() {
this.locales.forEach(this.generateForLocale.bind(this));
}
}
module.exports = DirectoryGenerator;
if (require.main === module) {
// called from command line
const args = require("minimist")(process.argv.slice(2), {alias: {
outputPath: ['o', 'output'],
i10nPath: ['i', 'input'],
staticPath: ['s', 'static'],
channels: ['c']
}});
const generator = new DirectoryGenerator(args);
console.log('Generating directories...');
generator.run();
console.log(`Finished generating directories for:
${generator.channels.length} channels
${generator.locales.length} locales`);
}
| mpl-2.0 |
JohnnyJ0622/Codility | src/com/johnny/java/MissingInteger.java | 596 | package com.johnny.java;
import java.util.HashSet;
/**
* Created by Johnny on 2/10/2017.
*/
public class MissingInteger {
public static void main(String[] args) {
int[] A = {4, 5, 6, 1, 2};
MissingInteger m = new MissingInteger();
System.out.println(m.solution(A));
}
public int solution(int[] A) {
int result = 1;
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < A.length; i++) {
set.add(A[i]);
}
while (set.contains(result)) {
result++;
}
return result;
}
}
| mpl-2.0 |
mstange/cleopatra | src/types/state.js | 8954 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import type {
Action,
DataSource,
PreviewSelection,
ImplementationFilter,
CallTreeSummaryStrategy,
RequestedLib,
TrackReference,
TimelineType,
CheckedSharingOptions,
Localization,
} from './actions';
import type { TabSlug } from '../app-logic/tabs-handling';
import type { StartEndRange, CssPixels, Milliseconds } from './units';
import type { Profile, ThreadIndex, Pid, TabID } from './profile';
import type {
CallNodePath,
GlobalTrack,
LocalTrack,
TrackIndex,
MarkerIndex,
ActiveTabTimeline,
OriginsTimeline,
ThreadsKey,
} from './profile-derived';
import type { Attempt } from '../utils/errors';
import type { TransformStacksPerThread } from './transforms';
import type JSZip from 'jszip';
import type { IndexIntoZipFileTable } from '../profile-logic/zip-files';
import type { PathSet } from '../utils/path.js';
import type { UploadedProfileInformation as ImportedUploadedProfileInformation } from 'firefox-profiler/app-logic/uploaded-profiles-db';
export type Reducer<T> = (T | void, Action) => T;
// This type is defined in uploaded-profiles-db.js because it is very tied to
// the data stored in our local IndexedDB, and we don't want to change it
// lightly, without changing the DB code.
// We reexport this type here mostly for easier access.
export type UploadedProfileInformation = ImportedUploadedProfileInformation;
export type SymbolicationStatus = 'DONE' | 'SYMBOLICATING';
export type ThreadViewOptions = {|
+selectedCallNodePath: CallNodePath,
+expandedCallNodePaths: PathSet,
+selectedMarker: MarkerIndex | null,
+selectedNetworkMarker: MarkerIndex | null,
|};
export type ThreadViewOptionsPerThreads = { [ThreadsKey]: ThreadViewOptions };
export type RightClickedCallNode = {|
+threadsKey: ThreadsKey,
+callNodePath: CallNodePath,
|};
export type MarkerReference = {|
+threadsKey: ThreadsKey,
+markerIndex: MarkerIndex,
|};
/**
* Full profile view state
* They should not be used from the active tab view.
* NOTE: This state is empty for now, but will be used later, do not remove.
* globalTracks and localTracksByPid states will be here in the future.
*/
export type FullProfileViewState = {|
globalTracks: GlobalTrack[],
localTracksByPid: Map<Pid, LocalTrack[]>,
|};
export type OriginsViewState = {|
originsTimeline: OriginsTimeline,
|};
/**
* Active tab profile view state
* They should not be used from the full view.
*/
export type ActiveTabProfileViewState = {|
activeTabTimeline: ActiveTabTimeline,
|};
/**
* Profile view state
*/
export type ProfileViewState = {
+viewOptions: {|
perThread: ThreadViewOptionsPerThreads,
symbolicationStatus: SymbolicationStatus,
waitingForLibs: Set<RequestedLib>,
previewSelection: PreviewSelection,
scrollToSelectionGeneration: number,
focusCallTreeGeneration: number,
rootRange: StartEndRange,
rightClickedTrack: TrackReference | null,
rightClickedCallNode: RightClickedCallNode | null,
rightClickedMarker: MarkerReference | null,
hoveredMarker: MarkerReference | null,
mouseTimePosition: Milliseconds | null,
|},
+profile: Profile | null,
+full: FullProfileViewState,
+activeTab: ActiveTabProfileViewState,
+origins: OriginsViewState,
};
export type AppViewState =
| {| +phase: 'ROUTE_NOT_FOUND' |}
| {| +phase: 'TRANSITIONING_FROM_STALE_PROFILE' |}
| {| +phase: 'PROFILE_LOADED' |}
| {| +phase: 'DATA_LOADED' |}
| {| +phase: 'DATA_RELOAD' |}
| {| +phase: 'FATAL_ERROR', +error: Error |}
| {|
+phase: 'INITIALIZING',
+additionalData?: {| +attempt: Attempt | null, +message: string |},
|};
export type Phase = $PropertyType<AppViewState, 'phase'>;
/**
* This represents the finite state machine for loading zip files. The phase represents
* where the state is now.
*/
export type ZipFileState =
| {|
+phase: 'NO_ZIP_FILE',
+zip: null,
+pathInZipFile: null,
|}
| {|
+phase: 'LIST_FILES_IN_ZIP_FILE',
+zip: JSZip,
+pathInZipFile: null,
|}
| {|
+phase: 'PROCESS_PROFILE_FROM_ZIP_FILE',
+zip: JSZip,
+pathInZipFile: string,
|}
| {|
+phase: 'FAILED_TO_PROCESS_PROFILE_FROM_ZIP_FILE',
+zip: JSZip,
+pathInZipFile: string,
|}
| {|
+phase: 'FILE_NOT_FOUND_IN_ZIP_FILE',
+zip: JSZip,
+pathInZipFile: string,
|}
| {|
+phase: 'VIEW_PROFILE_IN_ZIP_FILE',
+zip: JSZip,
+pathInZipFile: string,
|};
export type IsSidebarOpenPerPanelState = { [TabSlug]: boolean };
export type UrlSetupPhase = 'initial-load' | 'loading-profile' | 'done';
/*
* Experimental features that are mostly disabled by default. You need to enable
* them from the DevTools console with `experimental.enable<feature-camel-case>()`,
* e.g. `experimental.enableEventDelayTracks()`.
*/
export type ExperimentalFlags = {|
+eventDelayTracks: boolean,
+cpuGraphs: boolean,
|};
export type AppState = {|
+view: AppViewState,
+urlSetupPhase: UrlSetupPhase,
+hasZoomedViaMousewheel: boolean,
+isSidebarOpenPerPanel: IsSidebarOpenPerPanelState,
+panelLayoutGeneration: number,
+lastVisibleThreadTabSlug: TabSlug,
+trackThreadHeights: {
[key: ThreadsKey]: CssPixels,
},
+isNewlyPublished: boolean,
+isDragAndDropDragging: boolean,
+isDragAndDropOverlayRegistered: boolean,
+experimental: ExperimentalFlags,
+currentProfileUploadedInformation: UploadedProfileInformation | null,
|};
export type UploadPhase =
| 'local'
| 'compressing'
| 'uploading'
| 'uploaded'
| 'error';
export type UploadState = {|
phase: UploadPhase,
uploadProgress: number,
error: Error | mixed,
abortFunction: () => void,
generation: number,
|};
export type PublishState = {|
+checkedSharingOptions: CheckedSharingOptions,
+upload: UploadState,
+isHidingStaleProfile: boolean,
+hasSanitizedProfile: boolean,
+prePublishedState: State | null,
|};
export type ZippedProfilesState = {
zipFile: ZipFileState,
error: Error | null,
selectedZipFileIndex: IndexIntoZipFileTable | null,
// In practice this should never contain null, but needs to support the
// TreeView interface.
expandedZipFileIndexes: Array<IndexIntoZipFileTable | null>,
};
/**
* Full profile specific url state
* They should not be used from the active tab view.
*/
export type FullProfileSpecificUrlState = {|
globalTrackOrder: TrackIndex[],
hiddenGlobalTracks: Set<TrackIndex>,
hiddenLocalTracksByPid: Map<Pid, Set<TrackIndex>>,
localTrackOrderByPid: Map<Pid, TrackIndex[]>,
showJsTracerSummary: boolean,
legacyThreadOrder: ThreadIndex[] | null,
legacyHiddenThreads: ThreadIndex[] | null,
|};
/**
* Active tab profile specific url state
* They should not be used from the full view.
*/
export type ActiveTabSpecificProfileUrlState = {|
isResourcesPanelOpen: boolean,
|};
export type ProfileSpecificUrlState = {|
selectedThreads: Set<ThreadIndex> | null,
implementation: ImplementationFilter,
lastSelectedCallTreeSummaryStrategy: CallTreeSummaryStrategy,
invertCallstack: boolean,
showUserTimings: boolean,
committedRanges: StartEndRange[],
callTreeSearchString: string,
markersSearchString: string,
networkSearchString: string,
transforms: TransformStacksPerThread,
timelineType: TimelineType,
full: FullProfileSpecificUrlState,
activeTab: ActiveTabSpecificProfileUrlState,
|};
/**
* Determines how the timeline's tracks are organized.
*/
export type TimelineTrackOrganization =
| {| +type: 'full' |}
| {| +type: 'active-tab', +tabID: TabID | null |}
| {| +type: 'origins' |};
export type UrlState = {|
+dataSource: DataSource,
// This is used for the "public" dataSource".
+hash: string,
// This is used for the "from-url" dataSource.
+profileUrl: string,
// This is used for the "compare" dataSource, to compare 2 profiles.
+profilesToCompare: string[] | null,
+selectedTab: TabSlug,
+pathInZipFile: string | null,
+profileName: string | null,
+timelineTrackOrganization: TimelineTrackOrganization,
+profileSpecific: ProfileSpecificUrlState,
+symbolServerUrl: string | null,
|};
/**
* Localization State
*/
export type L10nFetchingPhase =
| 'not-fetching'
| 'fetching-ftl'
| 'done-fetching';
export type L10nState = {|
+l10nFetchingPhase: L10nFetchingPhase,
+localization: Localization,
+primaryLocale: string | null,
+direction: 'ltr' | 'rtl',
|};
export type IconState = Set<string>;
export type State = {|
+app: AppState,
+profileView: ProfileViewState,
+urlState: UrlState,
+icons: IconState,
+zippedProfiles: ZippedProfilesState,
+publish: PublishState,
+l10n: L10nState,
|};
export type IconWithClassName = {|
+icon: string,
+className: string,
|};
| mpl-2.0 |
svend/terraform-provider-stingray | Godeps/_workspace/src/github.com/hashicorp/terraform/config/lang/eval_test.go | 4208 | package lang
import (
"reflect"
"strconv"
"testing"
"github.com/whitepages/terraform-provider-stingray/Godeps/_workspace/src/github.com/hashicorp/terraform/config/lang/ast"
)
func TestEval(t *testing.T) {
cases := []struct {
Input string
Scope *ast.BasicScope
Error bool
Result interface{}
ResultType ast.Type
}{
{
"foo",
nil,
false,
"foo",
ast.TypeString,
},
{
"foo ${bar}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: "baz",
Type: ast.TypeString,
},
},
},
false,
"foo baz",
ast.TypeString,
},
{
"foo ${42+1}",
nil,
false,
"foo 43",
ast.TypeString,
},
{
"foo ${42-1}",
nil,
false,
"foo 41",
ast.TypeString,
},
{
"foo ${42*2}",
nil,
false,
"foo 84",
ast.TypeString,
},
{
"foo ${42/2}",
nil,
false,
"foo 21",
ast.TypeString,
},
{
"foo ${42%4}",
nil,
false,
"foo 2",
ast.TypeString,
},
{
"foo ${42.0+1.0}",
nil,
false,
"foo 43",
ast.TypeString,
},
{
"foo ${42.0+1}",
nil,
false,
"foo 43",
ast.TypeString,
},
{
"foo ${42+1.0}",
nil,
false,
"foo 43",
ast.TypeString,
},
{
"foo ${42+2*2}",
nil,
false,
"foo 88",
ast.TypeString,
},
{
"foo ${42+(2*2)}",
nil,
false,
"foo 46",
ast.TypeString,
},
{
"foo ${bar+1}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: 41,
Type: ast.TypeInt,
},
},
},
false,
"foo 42",
ast.TypeString,
},
{
"foo ${bar+1}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: "41",
Type: ast.TypeString,
},
},
},
false,
"foo 42",
ast.TypeString,
},
{
"foo ${bar+baz}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: "41",
Type: ast.TypeString,
},
"baz": ast.Variable{
Value: "1",
Type: ast.TypeString,
},
},
},
false,
"foo 42",
ast.TypeString,
},
{
"foo ${rand()}",
&ast.BasicScope{
FuncMap: map[string]ast.Function{
"rand": ast.Function{
ReturnType: ast.TypeString,
Callback: func([]interface{}) (interface{}, error) {
return "42", nil
},
},
},
},
false,
"foo 42",
ast.TypeString,
},
{
`foo ${rand("foo", "bar")}`,
&ast.BasicScope{
FuncMap: map[string]ast.Function{
"rand": ast.Function{
ReturnType: ast.TypeString,
Variadic: true,
VariadicType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
var result string
for _, a := range args {
result += a.(string)
}
return result, nil
},
},
},
},
false,
"foo foobar",
ast.TypeString,
},
// Testing implicit type conversions
{
"foo ${bar}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: 42,
Type: ast.TypeInt,
},
},
},
false,
"foo 42",
ast.TypeString,
},
{
`foo ${foo("42")}`,
&ast.BasicScope{
FuncMap: map[string]ast.Function{
"foo": ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
return strconv.FormatInt(int64(args[0].(int)), 10), nil
},
},
},
},
false,
"foo 42",
ast.TypeString,
},
// Multiline
{
"foo ${42+\n1.0}",
nil,
false,
"foo 43",
ast.TypeString,
},
}
for _, tc := range cases {
node, err := Parse(tc.Input)
if err != nil {
t.Fatalf("Error: %s\n\nInput: %s", err, tc.Input)
}
out, outType, err := Eval(node, &EvalConfig{GlobalScope: tc.Scope})
if (err != nil) != tc.Error {
t.Fatalf("Error: %s\n\nInput: %s", err, tc.Input)
}
if outType != tc.ResultType {
t.Fatalf("Bad: %s\n\nInput: %s", outType, tc.Input)
}
if !reflect.DeepEqual(out, tc.Result) {
t.Fatalf("Bad: %#v\n\nInput: %s", out, tc.Input)
}
}
}
| mpl-2.0 |
asajeffrey/servo | tests/wpt/web-platform-tests/touch-events/multi-touch-interactions.js | 18351 | setup({explicit_done: true});
var debug = document.getElementById("debug");
function debug_print (x) {
/* uncomment below statement to show debug messages */
// document.getElementById("debug").innerHTML += x;
}
var starting_elements = {};
function check_list_subset_of_targetlist(list, list_name, targetlist, targetlist_name) {
var exist_in_targetlist;
for(i=0; i<list.length; i++) {
exist_in_targetlist=false;
for(j=0; j<targetlist.length; j++)
if(list.item(i).identifier==targetlist.item(j).identifier)
exist_in_targetlist=true;
assert_true(exist_in_targetlist, list_name + ".item("+i+") exists in " + targetlist_name);
}
}
function check_list_subset_of_two_targetlists(list, list_name, targetlist1, targetlist1_name, targetlist2, targetlist2_name) {
var exist_in_targetlists;
for(i=0; i<list.length; i++) {
exist_in_targetlists=false;
for(j=0; j<targetlist1.length; j++)
if(list.item(i).identifier==targetlist1.item(j).identifier)
exist_in_targetlists=true;
if(!exist_in_targetlists)
for(j=0; j<targetlist2.length; j++)
if(list.item(i).identifier==targetlist2.item(j).identifier)
exist_in_targetlists=true;
assert_true(exist_in_targetlists, list_name + ".item("+i+") exists in " + targetlist1_name + " or " + targetlist2_name);
}
}
function is_at_least_one_item_in_targetlist(list, targetlist) {
for(i=0; i<list.length; i++)
for(j=0; j<targetlist.length; j++)
if(list.item(i).identifier==targetlist.item(j).identifier)
return true;
return false;
}
function check_no_item_in_targetlist(list, list_name, targetlist, targetlist_name) {
for(i=0; i<list.length; i++)
for(j=0; j<targetlist.length; j++) {
assert_false(list.item(i).identifier==targetlist.item(j).identifier, list_name + ".item("+i+") exists in " + targetlist_name);
return;
}
}
function check_targets(list, target) {
for(i=0; i<list.length; i++)
assert_true(list.item(i).target==target, "item(" + i + ").target is element receiving event");
}
function check_starting_elements(list) {
for (i=0; i<list.length; i++) {
assert_equals(list.item(i).target, starting_elements[list.item(i).identifier], "item(" + i + ").target matches starting element");
}
}
function run() {
var target0 = document.getElementById("target0");
var target1 = document.getElementById("target1");
var test_touchstart = async_test("touchstart event received");
var test_touchmove = async_test("touchmove event received");
var test_touchend = async_test("touchend event received");
var test_mousedown = async_test("Interaction with mouse events");
var touchstart_received = 0;
var touchmove_received = 0;
var touchend_received = 0;
var touchstart_identifier;
// last received touch lists for comparison
var last_touches;
var last_targetTouches={};
var last_changedTouches={};
on_event(window, "touchstart", function onTouchStart(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
ev.preventDefault();
if(!touchstart_received) {
// Check event ordering TA: 1.6.1
test_touchstart.step(function() {
assert_equals(touchmove_received, 0, "touchstart precedes touchmove");
assert_equals(touchend_received, 0, "touchstart precedes touchend");
});
test_touchstart.done();
test_mousedown.done(); // If we got here, then the mouse event test is not needed.
}
touchstart_received++;
// TA: 1.3.2.2, 1.3.2.4
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
assert_true(ev.changedTouches.length <= ev.touches.length, "changedTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
}, "touchstart #" + touchstart_received + ": changedTouches is a subset of touches");
// TA: 1.3.3.2, 1.3.3.3
test(function() {
assert_true(ev.targetTouches.length >= 1, "targetTouches.length is at least 1");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchstart #" + touchstart_received + ": targetTouches is a subset of touches");
// TA: 1.3.3.9
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchstart #" + touchstart_received + ": targets of targetTouches are correct");
// TA: 1.3.4.2
test(function() {
assert_true(ev.touches.length >= 1, "touches.length is at least 1");
}, "touchstart #" + touchstart_received + ": touches.length is valid");
if(touchstart_received == 1) {
// TA: 1.3.3.5, 1.3.3.7
test(function() {
assert_true(ev.targetTouches.length <= ev.changedTouches.length, "targetTouches.length is smaller than changedTouches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.changedTouches, "changedTouches");
}, "touchstart #" + touchstart_received + ": targetTouches is a subset of changedTouches");
// TA: 1.3.4.3
test(function() {
assert_equals(ev.touches.length, ev.changedTouches.length, "touches and changedTouches have the same length");
}, "touchstart #" + touchstart_received + ": touches and changedTouches have the same length");
} else {
// TA: 1.3.3.6
test(function() {
var diff_in_targetTouches = ev.targetTouches.length - (last_targetTouches[ev.target.id] ? last_targetTouches[ev.target.id].length : 0);
assert_true(diff_in_targetTouches > 0, "targetTouches.length is larger than last received targetTouches.length");
assert_true(diff_in_targetTouches <= ev.changedTouches.length, "change in targetTouches.length is smaller than changedTouches.length");
}, "touchstart #" + touchstart_received + ": change in targetTouches.length is valid");
// TA: 1.3.3.8
test(function() {
assert_true(is_at_least_one_item_in_targetlist(ev.targetTouches, ev.changedTouches), "at least one item of targetTouches is in changedTouches");
}, "touchstart #" + touchstart_received + ": at least one targetTouches item in changedTouches");
// TA: 1.3.4.4
test(function() {
var diff_in_touches = ev.touches.length - last_touches.length;
assert_true(diff_in_touches > 0, "touches.length is larger than last received touches.length");
assert_equals(diff_in_touches, ev.changedTouches.length, "change in touches.length equals changedTouches.length");
}, "touchstart #" + touchstart_received + ": change in touches.length is valid");
// TA: 1.3.4.5
test(function() {
check_list_subset_of_two_targetlists(ev.touches, "touches", ev.changedTouches, "changedTouches", last_touches, "last touches");
}, "touchstart #" + touchstart_received + ": touches is subset of {changedTouches, last received touches}");
}
// save starting element of each new touch point
for (i=0; i<ev.changedTouches.length; i++) {
starting_elements[ev.changedTouches.item(i).identifier] = ev.changedTouches.item(i).target;
}
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = {}; // changedTouches are only saved for touchend events
});
on_event(window, "touchmove", function onTouchMove(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
ev.preventDefault();
// TA: 1.6.1
test_touchmove.step(function() {
assert_true(touchstart_received>0, "touchmove follows touchstart");
// assert_false(touchend_received, "touchmove precedes touchend"); // this applies to scenario tests
});
test_touchmove.done();
touchmove_received++;
// do the detailed checking only for a few times
if(touchmove_received<6) {
// TA: 1.4.2.2, 1.4.2.4
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
assert_true(ev.changedTouches.length <= ev.touches.length, "changedTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
}, "touchmove #" + touchmove_received + ": changedTouches is a subset of touches");
// TA: 1.4.3.2, 1.4.3.4
test(function() {
assert_true(ev.targetTouches.length >= 1, "targetTouches.length is at least 1");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchmove #" + touchmove_received + ": targetTouches is a subset of touches");
// TA: 1.4.3.6
test(function() {
assert_true(is_at_least_one_item_in_targetlist(ev.targetTouches, ev.changedTouches), "at least one item of targetTouches is in changedTouches");
}, "touchmove #" + touchmove_received + ": at least one targetTouches item in changedTouches");
// TA: 1.4.3.8
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchmove #" + touchmove_received + ": targets of targetTouches are correct");
// TA: 1.4.4.2
test(function() {
assert_equals(ev.touches.length, last_touches.length, "length of touches is same as length of last received touches");
check_list_subset_of_targetlist(ev.touches, "touches", last_touches, "last received touches");
}, "touchmove #" + touchmove_received + ": touches must be same as last received touches");
// TA: 1.6.3
check_starting_elements(ev.changedTouches);
}
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = {}; // changedTouches are only saved for touchend events
});
on_event(window, "touchend", function onTouchEnd(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
test_touchend.step(function() {
assert_true(touchstart_received>0, "touchend follows touchstart");
});
test_touchend.done();
touchend_received++;
debug_print("touchend #" + touchend_received + ":<br>");
debug_print("changedTouches.length=" + ev.changedTouches.length + "<br>");
debug_print("targetTouches.length=" + ev.targetTouches.length + "<br>");
debug_print("touches.length=" + ev.touches.length + "<br>");
for(i=0; i<ev.changedTouches.length; i++)
debug_print("changedTouches.item(" + i + ").target=" + ev.changedTouches.item(i).target.id + "<br>");
// TA: 1.5.2.2
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
}, "touchend #" + touchend_received + ": length of changedTouches is valid");
// TA: 1.5.2.3
test(function() {
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", last_touches, "last received touches");
}, "touchend #" + touchend_received + ": changedTouches is a subset of last received touches");
// TA: 1.5.2.4, 1.5.2.5
test(function() {
check_no_item_in_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
check_no_item_in_targetlist(ev.changedTouches, "changedTouches", ev.targetTouches, "targetTouches");
}, "touchend #" + touchend_received + ": no item in changedTouches are in touches or targetTouches");
// TA: 1.5.2.6
test(function() {
var found=false;
for (i=0; i<ev.changedTouches.length; i++)
if (ev.changedTouches.item(i).target == ev.target)
found=true;
assert_true(found, "at least one item in changedTouches has matching target");
}, "touchend #" + touchend_received + ": at least one item in changedTouches targeted at this element");
// TA: 1.5.3.2, 1.5.3.3
test(function() {
assert_true(ev.targetTouches.length >= 0, "targetTouches.length is non-negative");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchend #" + touchend_received + ": targetTouches is a subset of touches");
// TA: 1.5.3.5 (new)
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchend #" + touchend_received + ": targets of targetTouches are correct");
// In some cases, when multiple touch points are released simultaneously
// the UA would dispatch the "same" touchend event (same changedTouches, same touches, but possibly different targetTouches)
// to each of the elements that are starting elements of the released touch points.
// in these situations, the subsequent events are exempt from TA 1.5.3.4 and 1.5.4.2
var same_event_as_last = false;
if (last_changedTouches && last_changedTouches.length==ev.changedTouches.length) {
same_event_as_last = true; // assume true until proven otherwise
for (i=0; i<last_changedTouches.length; i++) {
var match = false;
for (j=0; j<ev.changedTouches.length; j++)
if (last_changedTouches.item(i) == ev.changedTouches.item(j)) {
match = true;
break;
}
if (!match)
same_event_as_last = false;
}
}
if (!same_event_as_last) {
// TA: 1.5.3.4
// Getting semi-random failures on this and 1.5.4.2.
// See 1.5.4.2. Not sure if it's the same issue...
test(function() {
assert_true(last_targetTouches[ev.target.id].length > 0, "last received targetTouches.length is not zero");
var diff_in_targetTouches = last_targetTouches[ev.target.id].length - ev.targetTouches.length;
debug_print("diff_in_targetTouches=" + diff_in_targetTouches + "<br>");
assert_true(diff_in_targetTouches > 0, "targetTouches.length is smaller than last received targetTouches.length");
assert_true(diff_in_targetTouches <= ev.changedTouches.length, "change in targetTouches.length is smaller than changedTouches.length");
}, "touchend #" + touchend_received + ": change in targetTouches.length is valid");
// TA: 1.5.4.2
// Getting semi-random failures on this and 1.5.3.4.
// It looks like if fingers are lifted simultaneously, the "same" touchend event can be dispatched to two target elements
// but adapted to the element (same touches, changedTouches but different targetTouches).
// When one event is processed after another, ev.touches would end up being identical to last_touches, leading to failure.
// Question is why done() does not stop the processing of the latter event.
test(function() {
assert_true(last_touches.length > 0, "last received touches.length is not zero");
var diff_in_touches = last_touches.length - ev.touches.length;
debug_print("diff_in_touches=" + diff_in_touches + "<br>");
assert_true(diff_in_touches > 0, "touches.length is smaller than last received touches.length");
assert_equals(diff_in_touches, ev.changedTouches.length, "change in touches.length equals changedTouches.length");
}, "touchend #" + touchend_received + ": change in touches.length is valid");
}
// TA: 1.6.4
debug_print("touchend #" + touchend_received + ": TA 1.6.4<br>");
test(function() {
check_starting_elements(ev.changedTouches);
}, "touchend #" + touchend_received + ": event dispatched to correct element<br>");
debug_print("touchend #" + touchend_received + ": saving touch lists<br>");
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = ev.changedTouches;
debug_print("touchend #" + touchend_received + ": done<br>");
if(ev.touches.length==0)
done();
});
on_event(target0, "mousedown", function onMouseDown(ev) {
test_mousedown.step(function() {
assert_true(touchstart_received,
"The touchstart event must be dispatched before any mouse " +
"events. (If this fails, it might mean that the user agent does " +
"not implement W3C touch events at all.)"
);
});
test_mousedown.done();
if (!touchstart_received) {
// Abort the tests. If touch events are not supported, then most of
// the other event handlers will never be called, and the test will
// time out with misleading results.
done();
}
});
}
| mpl-2.0 |
wx1988/strabon | evaluation/src/main/java/org/openrdf/query/algebra/evaluation/function/spatial/geosparql/sf/SimpleFeaturesOverlapsFunc.java | 750 | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (C) 2010, 2011, 2012, Pyravlos Team
*
* http://www.strabon.di.uoa.gr/
*/
package org.openrdf.query.algebra.evaluation.function.spatial.geosparql.sf;
import org.openrdf.query.algebra.evaluation.function.spatial.geosparql.GeoSparqlRelation;
import eu.earthobservatory.constants.GeoConstants;
/**
*
* @author Manos Karpathiotakis <mk@di.uoa.gr>
*/
public class SimpleFeaturesOverlapsFunc extends GeoSparqlRelation {
@Override
public String getURI() {
return GeoConstants.sfOverlaps;
}
}
| mpl-2.0 |
terraform-providers/terraform-provider-aws | awsproviderlint/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/package.go | 1367 | package schema
import (
"fmt"
"go/ast"
"go/types"
"github.com/bflad/tfproviderlint/helper/astutils"
"github.com/bflad/tfproviderlint/helper/terraformtype"
)
const (
PackageModule = terraformtype.ModuleTerraformPluginSdk
PackageModulePath = `helper/schema`
PackageName = `schema`
PackagePath = PackageModule + `/` + PackageModulePath
)
// IsFunc returns if the function call is in the package
func IsFunc(e ast.Expr, info *types.Info, funcName string) bool {
return astutils.IsModulePackageFunc(e, info, PackageModule, PackageModulePath, funcName)
}
// IsNamedType returns if the type name matches and is from the package
func IsNamedType(t *types.Named, typeName string) bool {
return astutils.IsModulePackageNamedType(t, PackageModule, PackageModulePath, typeName)
}
// IsReceiverMethod returns if the receiver method call is in the package
func IsReceiverMethod(e ast.Expr, info *types.Info, receiverName string, methodName string) bool {
return astutils.IsModulePackageReceiverMethod(e, info, PackageModule, PackageModulePath, receiverName, methodName)
}
// PackagePathVersion returns the import path for a module version
func PackagePathVersion(moduleVersion int) string {
switch moduleVersion {
case 0, 1:
return PackagePath
default:
return fmt.Sprintf("%s/v%d/%s", PackageModule, moduleVersion, PackageModulePath)
}
}
| mpl-2.0 |
gabyx/ApproxMVBB | include/ApproxMVBB/Common/MyMatrixTypeDefs.hpp | 10625 | // ========================================================================================
// ApproxMVBB
// Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz
// (døt) ch>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================================
#ifndef ApproxMVBB_Common_MyMatrixTypeDefs_hpp
#define ApproxMVBB_Common_MyMatrixTypeDefs_hpp
#include "ApproxMVBB/Common/Platform.hpp"
//#define EIGEN_DONT_VECTORIZE
//#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT
#include <Eigen/Dense>
namespace ApproxMVBB
{
// ================================================================================================
/*! @brief This
These are some small matrix definitions.
*/
namespace MyMatrix
{
template<typename Scalar>
using Matrix44 = Eigen::Matrix<Scalar, 4, 4>;
template<typename Scalar>
using Matrix43 = Eigen::Matrix<Scalar, 4, 3>;
template<typename Scalar>
using Matrix34 = Eigen::Matrix<Scalar, 3, 4>;
template<typename Scalar>
using Matrix33 = Eigen::Matrix<Scalar, 3, 3>;
template<typename Scalar>
using Matrix32 = Eigen::Matrix<Scalar, 3, 2>;
template<typename Scalar>
using Matrix23 = Eigen::Matrix<Scalar, 2, 3>;
template<typename Scalar>
using Matrix22 = Eigen::Matrix<Scalar, 2, 2>;
template<typename Scalar>
using Vector3 = Eigen::Matrix<Scalar, 3, 1>;
template<typename Scalar>
using Vector2 = Eigen::Matrix<Scalar, 2, 1>;
template<typename Scalar>
using Quaternion = Eigen::Quaternion<Scalar>;
template<typename Scalar>
using AngleAxis = Eigen::AngleAxis<Scalar>;
template<typename Scalar>
using Vector4 = Eigen::Matrix<Scalar, 4, 1>;
template<typename Scalar>
using Vector6 = Eigen::Matrix<Scalar, 6, 1>;
template<typename Scalar>
using VectorDyn = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
template<typename Scalar>
using MatrixDynDyn = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
template<typename Scalar>
using MatrixDiagDyn = Eigen::DiagonalMatrix<Scalar, Eigen::Dynamic>;
template<typename Scalar>
using MatrixDynDynRow = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
template<typename Scalar, int M>
using MatrixStatDyn = Eigen::Matrix<Scalar, M, Eigen::Dynamic>;
template<typename Scalar, int N>
using MatrixDynStat = Eigen::Matrix<Scalar, Eigen::Dynamic, N>;
template<typename Scalar, int M, int N>
using MatrixStatStat = Eigen::Matrix<Scalar, M, N>;
template<typename Scalar, int M>
using VectorStat = Eigen::Matrix<Scalar, M, 1>;
template<typename Scalar>
using AffineTrafo = Eigen::Transform<Scalar, 3, Eigen::TransformTraits::Affine>;
template<typename Scalar>
using AffineTrafo2d = Eigen::Transform<Scalar, 2, Eigen::TransformTraits::Affine>;
template<typename Scalar, int M>
using ArrayStatDyn = Eigen::Array<Scalar, M, Eigen::Dynamic>;
template<typename Scalar, int N>
using ArrayDynStat = Eigen::Array<Scalar, Eigen::Dynamic, N>;
template<typename Scalar, int M, int N>
using ArrayStatStat = Eigen::Array<Scalar, M, N>;
template<typename Scalar, int M>
using ArrayStat = Eigen::Array<Scalar, M, 1>;
template<typename Scalar>
using Array3 = Eigen::Array<Scalar, 3, 1>;
template<typename Scalar>
using Array2 = Eigen::Array<Scalar, 2, 1>;
} // namespace MyMatrix
namespace MyMatrix
{
template<typename Derived>
using MatrixBase = Eigen::MatrixBase<Derived>;
template<typename Derived>
using ArrayBase = Eigen::ArrayBase<Derived>;
template<typename Derived>
using VectorBDyn = Eigen::VectorBlock<Derived, Eigen::Dynamic>;
template<typename Derived, int M>
using VectorBStat = Eigen::VectorBlock<Derived, M>;
template<typename Derived>
using MatrixBDynDyn = Eigen::Block<Derived>;
template<typename Derived, int M>
using MatrixBStatDyn = Eigen::Block<Derived, M, Eigen::Dynamic>;
template<typename Derived, int N>
using MatrixBDynStat = Eigen::Block<Derived, Eigen::Dynamic, N>;
template<typename EigenType>
using MatrixRef = Eigen::Ref<EigenType>;
template<typename EigenType>
using MatrixMap = Eigen::Map<EigenType>;
} // namespace MyMatrix
struct APPROXMVBB_EXPORT MyMatrixIOFormat
{
static const Eigen::IOFormat Matlab;
static const Eigen::IOFormat CommaSep;
static const Eigen::IOFormat SpaceSep;
};
} // namespace ApproxMVBB
# define ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES \
template<typename Derived> \
using MatrixBase = ApproxMVBB::MyMatrix::MatrixBase<Derived>; \
template<typename Derived> \
using ArrayBase = ApproxMVBB::MyMatrix::ArrayBase<Derived>; \
\
template<typename Derived> \
using VectorBDyn = ApproxMVBB::MyMatrix::VectorBDyn<Derived>; \
template<typename Derived, int M> \
using VectorBStat = ApproxMVBB::MyMatrix::VectorBStat<Derived, M>; \
\
template<typename Derived> \
using MatrixBDynDyn = ApproxMVBB::MyMatrix::MatrixBDynDyn<Derived>; \
template<typename Derived, int N> \
using MatrixBDynStat = ApproxMVBB::MyMatrix::MatrixBDynStat<Derived, N>; \
template<typename Derived, int M> \
using MatrixBStatDyn = ApproxMVBB::MyMatrix::MatrixBStatDyn<Derived, M>; \
\
template<typename EigenType> \
using MatrixRef = ApproxMVBB::MyMatrix::MatrixRef<EigenType>; \
template<typename EigenType> \
using MatrixMap = ApproxMVBB::MyMatrix::MatrixMap<EigenType>
/**
* @brief This macro is used to typedef all custom matrix types which have
* nothing to do with the system.
*/
# define ApproxMVBB_DEFINE_MATRIX_TYPES_OF(_PREC_) \
using Matrix44 = ApproxMVBB::MyMatrix::Matrix44<_PREC_>; \
using Matrix33 = ApproxMVBB::MyMatrix::Matrix33<_PREC_>; \
using Matrix22 = ApproxMVBB::MyMatrix::Matrix22<_PREC_>; \
using Matrix32 = ApproxMVBB::MyMatrix::Matrix32<_PREC_>; \
using Matrix23 = ApproxMVBB::MyMatrix::Matrix23<_PREC_>; \
using Matrix43 = ApproxMVBB::MyMatrix::Matrix43<_PREC_>; \
using Matrix34 = ApproxMVBB::MyMatrix::Matrix34<_PREC_>; \
using Vector3 = ApproxMVBB::MyMatrix::Vector3<_PREC_>; \
using Vector2 = ApproxMVBB::MyMatrix::Vector2<_PREC_>; \
using Vector4 = ApproxMVBB::MyMatrix::Vector4<_PREC_>; \
using Vector6 = ApproxMVBB::MyMatrix::Vector6<_PREC_>; \
using Quaternion = ApproxMVBB::MyMatrix::Quaternion<_PREC_>; \
using AngleAxis = ApproxMVBB::MyMatrix::AngleAxis<_PREC_>; \
using VectorDyn = ApproxMVBB::MyMatrix::VectorDyn<_PREC_>; \
using MatrixDynDyn = ApproxMVBB::MyMatrix::MatrixDynDyn<_PREC_>; \
using MatrixDiagDyn = ApproxMVBB::MyMatrix::MatrixDiagDyn<_PREC_>; \
using MatrixDynDynRow = ApproxMVBB::MyMatrix::MatrixDynDynRow<_PREC_>; \
\
template<int M> \
using MatrixStatDyn = ApproxMVBB::MyMatrix::MatrixStatDyn<_PREC_, M>; \
template<int N> \
using MatrixDynStat = ApproxMVBB::MyMatrix::MatrixDynStat<_PREC_, N>; \
template<int M, int N> \
using MatrixStatStat = ApproxMVBB::MyMatrix::MatrixStatStat<_PREC_, M, N>; \
template<int M> \
using VectorStat = ApproxMVBB::MyMatrix::VectorStat<_PREC_, M>; \
\
using AffineTrafo = ApproxMVBB::MyMatrix::AffineTrafo<_PREC_>; \
using AffineTrafo2d = ApproxMVBB::MyMatrix::AffineTrafo2d<_PREC_>; \
\
template<int M> \
using ArrayStatDyn = ApproxMVBB::MyMatrix::ArrayStatDyn<_PREC_, M>; \
template<int N> \
using ArrayDynStat = ApproxMVBB::MyMatrix::ArrayDynStat<_PREC_, N>; \
template<int M, int N> \
using ArrayStatStat = ApproxMVBB::MyMatrix::ArrayStatStat<_PREC_, M, N>; \
template<int M> \
using ArrayStat = ApproxMVBB::MyMatrix::ArrayStat<_PREC_, M>; \
using Array3 = ApproxMVBB::MyMatrix::Array3<_PREC_>; \
using Array2 = ApproxMVBB::MyMatrix::Array2<_PREC_>; \
\
ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES
#endif
| mpl-2.0 |
petemoore/build-funsize | funsize/backend/config/staging.py | 265 | """
Celery configuration for dev environment
export FUNSIZE_CELERY_CONFIG="funsize.backend.config.dev" to use it
"""
import os
FUNSIZE_CONF_NAME = "staging"
CELERY_ACKS_LATE = True
CELERY_DEFAULT_QUEUE = "funsize_staging"
BROKER_URL = os.environ.get('BROKER_URL')
| mpl-2.0 |
DeathsbreedGames/deathsbreedgames.github.io | games/GNP-1.5-alpha0/src/Preload.js | 1169 | /**
* GNP
* Copyright (C) 2014 DeathsbreedGames
* License: GNU Affero GPLv3
*
*/
var DeathsbreedGames = DeathsbreedGames || {};
DeathsbreedGames.Preload = function() {};
DeathsbreedGames.Preload.prototype = {
preload:function() {
// Setup the Splash image (DeathsbreedGames)
this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 50, 'DGL');
this.splash.width = 420;
this.splash.height = 90;
this.splash.anchor.setTo(0.5);
// Setup the loading bar
this.preloadBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'LoadingBar');
this.preloadBar.anchor.setTo(0.5);
this.load.setPreloadSprite(this.preloadBar);
// Load the game assets
this.load.audio('hit', 'assets/sfx/hitsfx.ogg');
this.load.audio('score', 'assets/sfx/scoresfx.ogg');
this.load.audio('music', 'assets/sfx/Never_Stop_Running.ogg');
this.load.image('bg', 'assets/gfx/background_glowy.png');
this.load.image('ball', 'assets/gfx/ball_glowy.png');
this.load.image('logo', 'assets/gfx/logo.png');
this.load.image('paddle', 'assets/gfx/player_glowy.png');
},
create:function() {
this.state.start('MainMenu');
}
};
| mpl-2.0 |
Devexperts/QD | qd-core/src/main/java/com/devexperts/qd/kit/ByteArrayField.java | 8113 | /*
* !++
* QDS - Quick Data Signalling Library
* !-
* Copyright (C) 2002 - 2021 Devexperts LLC
* !-
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
* !__
*/
package com.devexperts.qd.kit;
import com.devexperts.io.BufferedInput;
import com.devexperts.io.BufferedOutput;
import com.devexperts.io.IOUtil;
import com.devexperts.qd.SerialFieldType;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Locale;
/**
* The <code>ByteArrayField</code> represents a linear byte array field
* with plain serialized form. It uses <code>CompactInt</code> to encode
* byte array length first, then serializes bytes themselves. The value -1
* for length is used as a marker to distinguish 'null' array from empty one.
* Default representation of the value is <code>byte[]</code> as returned by {@link #readObj},
* but <code>String</code>, <code>char[]</code> and arbitrary serializable objects are also
* supported by {@link #writeObj} and {@link #toString(Object)}.
*
* <p>Note: extension of this class is not supported because of the high-performance architecture for
* binary protocol reading/writing.
*/
public final class ByteArrayField extends AbstractDataObjField {
public ByteArrayField(int index, String name) {
super(index, name, SerialFieldType.BYTE_ARRAY);
}
/**
* This method is a hook to convert byte arrays into objects.
* This implementation returns bytes.
* This method is invoked from {@link #readObj(java.io.DataInput)}.
*
* <p>This method can be overridden to provide custom conversion of byte arrays to objects.
* If you override this method, then you also typically need to override {@link #toByteArray(Object)}
* and consider overriding {@link #toString(Object)}.
* For example, if you need to convert byte arrays to {@code MyObject} instances, write:
* <pre>
* public Object fromByteArray(byte[] bytes) {
* return MyObject.forByteArray(bytes);
* }
* </pre>
* It is recommended that all such MyObject classes lazily reconstruct themselves from byte array to avoid
* potentially costly deserialization in multiplexor nodes.
*
* @param bytes Byte array to convert to object.
* @return Resulting object.
*/
public Object fromByteArray(byte[] bytes) {
return bytes;
}
/**
* This method is a hook to provide custom conversion of objects to byte arrays for serialization.
* This implementation works depending on the value class:
* <ul>
* <li>{@code byte[]} is returned as is.
* <li>{@code String} and {@code char[]} are converted to UTF8 bytes.
* <li>For other other objects <code>null</code> is returned. In this case callee if this method
* uses {@link IOUtil#objectToBytes(Object)} or {@link IOUtil#writeObject(DataOutput, Object)}.
* </ul>
* This method is invoked from {@link #equals(Object, Object)}, {@link #toString(Object)}, and
* {@link #writeObj(DataOutput, Object)}.
*
* <p>This method can be overridden to provide custom conversion of objects to byte arrays.
* If you override this method, then you also typically need to override {@link #fromByteArray(byte[])}
* and consider overriding {@link #toString(Object)}.
* For example, if you need to convert {@code MyObject} instances to byte arrays, write:
* <pre>
* public byte[] toByteArray(Object value) {
* if (value instanceof MyObject)
* return ((MyObject) value).toByteArray();
* else
* super.toByteArray(value);
* }
* </pre>
* It is recommended that all such MyObject classes cache their produced byte arrays to avoid
* potentially costly serialization in multiplexor nodes.
*
* @param value The object to convert to byte array.
* @return array of bytes or {@code null} if default conversion via {@link IOUtil#objectToBytes} or
* {@link IOUtil#writeObject(DataOutput, Object)} shall be used.
*/
public byte[] toByteArray(Object value) {
if (value instanceof byte[])
return (byte[]) value;
if (value instanceof String)
return ((String) value).getBytes(StandardCharsets.UTF_8);
else if (value instanceof char[])
return new String((char[]) value).getBytes(StandardCharsets.UTF_8);
else
return null;
}
private byte[] toByteArrayAlways(Object value) {
try {
byte[] bytes = toByteArray(value);
return bytes == null ? IOUtil.objectToBytes(value) : bytes;
} catch (IOException e) {
throw new IllegalArgumentException("Cannot convert object to bytes", e);
}
}
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
/**
* Returns string representation of the specified field value.
* This method is used for debugging purposes.
* This implementation coverts object to byte array via {@link #toByteArray(Object)},
* if that returns null, then it uses {@link IOUtil#objectToBytes(Object)}; then returns a hex
* representation of the resulting byte array.
*/
@Override
public String toString(Object value) {
if (value == null)
return null;
byte[] bytes = toByteArrayAlways(value);
StringBuilder sb = new StringBuilder(2 + 2 * bytes.length);
sb.append("0x");
for (byte b : bytes) {
int x = b & 0xff;
sb.append(HEX[x >> 4]).append(HEX[x & 0x0f]);
}
return sb.toString();
}
@Override
public Object parseString(String value) {
if (value == null)
return null;
String s = value.toUpperCase(Locale.US);
hex_decode:
if (s.startsWith("0X") && s.length() % 2 == 0) {
byte[] b = new byte[s.length() / 2 - 1];
for (int i = 0; i < b.length; i++) {
int hi = Arrays.binarySearch(HEX, s.charAt(2 * i + 2));
int lo = Arrays.binarySearch(HEX, s.charAt(2 * i + 3));
if (hi < 0 || lo < 0)
break hex_decode;
b[i] = (byte) ((hi << 4) + lo);
}
return b;
}
// failed to decode hex -- return just string bytes
return value.getBytes(StandardCharsets.UTF_8);
}
@Override
public boolean equals(Object value1, Object value2) {
if (value1 == value2)
return true;
else if (value1 == null || value2 == null)
return false;
else if (value1 instanceof byte[] && value2 instanceof byte[])
return Arrays.equals((byte[]) value1, (byte[]) value2);
else if (value1 instanceof String && value2 instanceof String)
return value1.equals(value2);
else if (value1 instanceof char[] && value2 instanceof char[])
return Arrays.equals((char[]) value1, (char[]) value2);
else
return Arrays.equals(toByteArrayAlways(value1), toByteArrayAlways(value2));
}
@Override
public void writeObj(DataOutput out, Object value) throws IOException {
byte[] bytes = toByteArray(value);
if (bytes != null)
IOUtil.writeByteArray(out, bytes);
else
IOUtil.writeObject(out, value);
}
@Override
public void writeObj(BufferedOutput out, Object value) throws IOException {
byte[] bytes = toByteArray(value);
if (bytes != null)
out.writeByteArray(bytes);
else
out.writeObject(value);
}
@Override
public Object readObj(DataInput in) throws IOException {
return fromByteArray(IOUtil.readByteArray(in));
}
@Override
public Object readObj(BufferedInput in) throws IOException {
return in.readByteArray();
}
}
| mpl-2.0 |
doodles526/vault | vendor/github.com/coreos/etcd/raft/raft.go | 39016 | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package raft
import (
"bytes"
"errors"
"fmt"
"math"
"math/rand"
"sort"
"strings"
"sync"
"time"
pb "github.com/coreos/etcd/raft/raftpb"
)
// None is a placeholder node ID used when there is no leader.
const None uint64 = 0
const noLimit = math.MaxUint64
// Possible values for StateType.
const (
StateFollower StateType = iota
StateCandidate
StateLeader
StatePreCandidate
numStates
)
type ReadOnlyOption int
const (
// ReadOnlySafe guarantees the linearizability of the read only request by
// communicating with the quorum. It is the default and suggested option.
ReadOnlySafe ReadOnlyOption = iota
// ReadOnlyLeaseBased ensures linearizability of the read only request by
// relying on the leader lease. It can be affected by clock drift.
// If the clock drift is unbounded, leader might keep the lease longer than it
// should (clock can move backward/pause without any bound). ReadIndex is not safe
// in that case.
ReadOnlyLeaseBased
)
// Possible values for CampaignType
const (
// campaignPreElection represents the first phase of a normal election when
// Config.PreVote is true.
campaignPreElection CampaignType = "CampaignPreElection"
// campaignElection represents a normal (time-based) election (the second phase
// of the election when Config.PreVote is true).
campaignElection CampaignType = "CampaignElection"
// campaignTransfer represents the type of leader transfer
campaignTransfer CampaignType = "CampaignTransfer"
)
// lockedRand is a small wrapper around rand.Rand to provide
// synchronization. Only the methods needed by the code are exposed
// (e.g. Intn).
type lockedRand struct {
mu sync.Mutex
rand *rand.Rand
}
func (r *lockedRand) Intn(n int) int {
r.mu.Lock()
v := r.rand.Intn(n)
r.mu.Unlock()
return v
}
var globalRand = &lockedRand{
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
// CampaignType represents the type of campaigning
// the reason we use the type of string instead of uint64
// is because it's simpler to compare and fill in raft entries
type CampaignType string
// StateType represents the role of a node in a cluster.
type StateType uint64
var stmap = [...]string{
"StateFollower",
"StateCandidate",
"StateLeader",
"StatePreCandidate",
}
func (st StateType) String() string {
return stmap[uint64(st)]
}
// Config contains the parameters to start a raft.
type Config struct {
// ID is the identity of the local raft. ID cannot be 0.
ID uint64
// peers contains the IDs of all nodes (including self) in the raft cluster. It
// should only be set when starting a new raft cluster. Restarting raft from
// previous configuration will panic if peers is set. peer is private and only
// used for testing right now.
peers []uint64
// ElectionTick is the number of Node.Tick invocations that must pass between
// elections. That is, if a follower does not receive any message from the
// leader of current term before ElectionTick has elapsed, it will become
// candidate and start an election. ElectionTick must be greater than
// HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
// unnecessary leader switching.
ElectionTick int
// HeartbeatTick is the number of Node.Tick invocations that must pass between
// heartbeats. That is, a leader sends heartbeat messages to maintain its
// leadership every HeartbeatTick ticks.
HeartbeatTick int
// Storage is the storage for raft. raft generates entries and states to be
// stored in storage. raft reads the persisted entries and states out of
// Storage when it needs. raft reads out the previous state and configuration
// out of storage when restarting.
Storage Storage
// Applied is the last applied index. It should only be set when restarting
// raft. raft will not return entries to the application smaller or equal to
// Applied. If Applied is unset when restarting, raft might return previous
// applied entries. This is a very application dependent configuration.
Applied uint64
// MaxSizePerMsg limits the max size of each append message. Smaller value
// lowers the raft recovery cost(initial probing and message lost during normal
// operation). On the other side, it might affect the throughput during normal
// replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
// message.
MaxSizePerMsg uint64
// MaxInflightMsgs limits the max number of in-flight append messages during
// optimistic replication phase. The application transportation layer usually
// has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
// overflowing that sending buffer. TODO (xiangli): feedback to application to
// limit the proposal rate?
MaxInflightMsgs int
// CheckQuorum specifies if the leader should check quorum activity. Leader
// steps down when quorum is not active for an electionTimeout.
CheckQuorum bool
// PreVote enables the Pre-Vote algorithm described in raft thesis section
// 9.6. This prevents disruption when a node that has been partitioned away
// rejoins the cluster.
PreVote bool
// ReadOnlyOption specifies how the read only request is processed.
//
// ReadOnlySafe guarantees the linearizability of the read only request by
// communicating with the quorum. It is the default and suggested option.
//
// ReadOnlyLeaseBased ensures linearizability of the read only request by
// relying on the leader lease. It can be affected by clock drift.
// If the clock drift is unbounded, leader might keep the lease longer than it
// should (clock can move backward/pause without any bound). ReadIndex is not safe
// in that case.
ReadOnlyOption ReadOnlyOption
// Logger is the logger used for raft log. For multinode which can host
// multiple raft group, each raft group can have its own logger
Logger Logger
}
func (c *Config) validate() error {
if c.ID == None {
return errors.New("cannot use none as id")
}
if c.HeartbeatTick <= 0 {
return errors.New("heartbeat tick must be greater than 0")
}
if c.ElectionTick <= c.HeartbeatTick {
return errors.New("election tick must be greater than heartbeat tick")
}
if c.Storage == nil {
return errors.New("storage cannot be nil")
}
if c.MaxInflightMsgs <= 0 {
return errors.New("max inflight messages must be greater than 0")
}
if c.Logger == nil {
c.Logger = raftLogger
}
return nil
}
type raft struct {
id uint64
Term uint64
Vote uint64
readStates []ReadState
// the log
raftLog *raftLog
maxInflight int
maxMsgSize uint64
prs map[uint64]*Progress
state StateType
votes map[uint64]bool
msgs []pb.Message
// the leader id
lead uint64
// leadTransferee is id of the leader transfer target when its value is not zero.
// Follow the procedure defined in raft thesis 3.10.
leadTransferee uint64
// New configuration is ignored if there exists unapplied configuration.
pendingConf bool
readOnly *readOnly
// number of ticks since it reached last electionTimeout when it is leader
// or candidate.
// number of ticks since it reached last electionTimeout or received a
// valid message from current leader when it is a follower.
electionElapsed int
// number of ticks since it reached last heartbeatTimeout.
// only leader keeps heartbeatElapsed.
heartbeatElapsed int
checkQuorum bool
preVote bool
heartbeatTimeout int
electionTimeout int
// randomizedElectionTimeout is a random number between
// [electiontimeout, 2 * electiontimeout - 1]. It gets reset
// when raft changes its state to follower or candidate.
randomizedElectionTimeout int
tick func()
step stepFunc
logger Logger
}
func newRaft(c *Config) *raft {
if err := c.validate(); err != nil {
panic(err.Error())
}
raftlog := newLog(c.Storage, c.Logger)
hs, cs, err := c.Storage.InitialState()
if err != nil {
panic(err) // TODO(bdarnell)
}
peers := c.peers
if len(cs.Nodes) > 0 {
if len(peers) > 0 {
// TODO(bdarnell): the peers argument is always nil except in
// tests; the argument should be removed and these tests should be
// updated to specify their nodes through a snapshot.
panic("cannot specify both newRaft(peers) and ConfState.Nodes)")
}
peers = cs.Nodes
}
r := &raft{
id: c.ID,
lead: None,
raftLog: raftlog,
maxMsgSize: c.MaxSizePerMsg,
maxInflight: c.MaxInflightMsgs,
prs: make(map[uint64]*Progress),
electionTimeout: c.ElectionTick,
heartbeatTimeout: c.HeartbeatTick,
logger: c.Logger,
checkQuorum: c.CheckQuorum,
preVote: c.PreVote,
readOnly: newReadOnly(c.ReadOnlyOption),
}
for _, p := range peers {
r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
}
if !isHardStateEqual(hs, emptyState) {
r.loadState(hs)
}
if c.Applied > 0 {
raftlog.appliedTo(c.Applied)
}
r.becomeFollower(r.Term, None)
var nodesStrs []string
for _, n := range r.nodes() {
nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
}
r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
return r
}
func (r *raft) hasLeader() bool { return r.lead != None }
func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
func (r *raft) hardState() pb.HardState {
return pb.HardState{
Term: r.Term,
Vote: r.Vote,
Commit: r.raftLog.committed,
}
}
func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
func (r *raft) nodes() []uint64 {
nodes := make([]uint64, 0, len(r.prs))
for id := range r.prs {
nodes = append(nodes, id)
}
sort.Sort(uint64Slice(nodes))
return nodes
}
// send persists state to stable storage and then sends to its mailbox.
func (r *raft) send(m pb.Message) {
m.From = r.id
if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
if m.Term == 0 {
// PreVote RPCs are sent at a term other than our actual term, so the code
// that sends these messages is responsible for setting the term.
panic(fmt.Sprintf("term should be set when sending %s", m.Type))
}
} else {
if m.Term != 0 {
panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
}
// do not attach term to MsgProp, MsgReadIndex
// proposals are a way to forward to the leader and
// should be treated as local message.
// MsgReadIndex is also forwarded to leader.
if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
m.Term = r.Term
}
}
r.msgs = append(r.msgs, m)
}
// sendAppend sends RPC, with entries to the given peer.
func (r *raft) sendAppend(to uint64) {
pr := r.prs[to]
if pr.isPaused() {
return
}
m := pb.Message{}
m.To = to
term, errt := r.raftLog.term(pr.Next - 1)
ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
if !pr.RecentActive {
r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
return
}
m.Type = pb.MsgSnap
snapshot, err := r.raftLog.snapshot()
if err != nil {
if err == ErrSnapshotTemporarilyUnavailable {
r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
return
}
panic(err) // TODO(bdarnell)
}
if IsEmptySnap(snapshot) {
panic("need non-empty snapshot")
}
m.Snapshot = snapshot
sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
pr.becomeSnapshot(sindex)
r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
} else {
m.Type = pb.MsgApp
m.Index = pr.Next - 1
m.LogTerm = term
m.Entries = ents
m.Commit = r.raftLog.committed
if n := len(m.Entries); n != 0 {
switch pr.State {
// optimistically increase the next when in ProgressStateReplicate
case ProgressStateReplicate:
last := m.Entries[n-1].Index
pr.optimisticUpdate(last)
pr.ins.add(last)
case ProgressStateProbe:
pr.pause()
default:
r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
}
}
}
r.send(m)
}
// sendHeartbeat sends an empty MsgApp
func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
// Attach the commit as min(to.matched, r.committed).
// When the leader sends out heartbeat message,
// the receiver(follower) might not be matched with the leader
// or it might not have all the committed entries.
// The leader MUST NOT forward the follower's commit to
// an unmatched index.
commit := min(r.prs[to].Match, r.raftLog.committed)
m := pb.Message{
To: to,
Type: pb.MsgHeartbeat,
Commit: commit,
Context: ctx,
}
r.send(m)
}
// bcastAppend sends RPC, with entries to all peers that are not up-to-date
// according to the progress recorded in r.prs.
func (r *raft) bcastAppend() {
for id := range r.prs {
if id == r.id {
continue
}
r.sendAppend(id)
}
}
// bcastHeartbeat sends RPC, without entries to all the peers.
func (r *raft) bcastHeartbeat() {
lastCtx := r.readOnly.lastPendingRequestCtx()
if len(lastCtx) == 0 {
r.bcastHeartbeatWithCtx(nil)
} else {
r.bcastHeartbeatWithCtx([]byte(lastCtx))
}
}
func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
for id := range r.prs {
if id == r.id {
continue
}
r.sendHeartbeat(id, ctx)
r.prs[id].resume()
}
}
// maybeCommit attempts to advance the commit index. Returns true if
// the commit index changed (in which case the caller should call
// r.bcastAppend).
func (r *raft) maybeCommit() bool {
// TODO(bmizerany): optimize.. Currently naive
mis := make(uint64Slice, 0, len(r.prs))
for id := range r.prs {
mis = append(mis, r.prs[id].Match)
}
sort.Sort(sort.Reverse(mis))
mci := mis[r.quorum()-1]
return r.raftLog.maybeCommit(mci, r.Term)
}
func (r *raft) reset(term uint64) {
if r.Term != term {
r.Term = term
r.Vote = None
}
r.lead = None
r.electionElapsed = 0
r.heartbeatElapsed = 0
r.resetRandomizedElectionTimeout()
r.abortLeaderTransfer()
r.votes = make(map[uint64]bool)
for id := range r.prs {
r.prs[id] = &Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight)}
if id == r.id {
r.prs[id].Match = r.raftLog.lastIndex()
}
}
r.pendingConf = false
r.readOnly = newReadOnly(r.readOnly.option)
}
func (r *raft) appendEntry(es ...pb.Entry) {
li := r.raftLog.lastIndex()
for i := range es {
es[i].Term = r.Term
es[i].Index = li + 1 + uint64(i)
}
r.raftLog.append(es...)
r.prs[r.id].maybeUpdate(r.raftLog.lastIndex())
// Regardless of maybeCommit's return, our caller will call bcastAppend.
r.maybeCommit()
}
// tickElection is run by followers and candidates after r.electionTimeout.
func (r *raft) tickElection() {
r.electionElapsed++
if r.promotable() && r.pastElectionTimeout() {
r.electionElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
}
}
// tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
func (r *raft) tickHeartbeat() {
r.heartbeatElapsed++
r.electionElapsed++
if r.electionElapsed >= r.electionTimeout {
r.electionElapsed = 0
if r.checkQuorum {
r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
}
// If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
if r.state == StateLeader && r.leadTransferee != None {
r.abortLeaderTransfer()
}
}
if r.state != StateLeader {
return
}
if r.heartbeatElapsed >= r.heartbeatTimeout {
r.heartbeatElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
}
}
func (r *raft) becomeFollower(term uint64, lead uint64) {
r.step = stepFollower
r.reset(term)
r.tick = r.tickElection
r.lead = lead
r.state = StateFollower
r.logger.Infof("%x became follower at term %d", r.id, r.Term)
}
func (r *raft) becomeCandidate() {
// TODO(xiangli) remove the panic when the raft implementation is stable
if r.state == StateLeader {
panic("invalid transition [leader -> candidate]")
}
r.step = stepCandidate
r.reset(r.Term + 1)
r.tick = r.tickElection
r.Vote = r.id
r.state = StateCandidate
r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
}
func (r *raft) becomePreCandidate() {
// TODO(xiangli) remove the panic when the raft implementation is stable
if r.state == StateLeader {
panic("invalid transition [leader -> pre-candidate]")
}
// Becoming a pre-candidate changes our step functions and state,
// but doesn't change anything else. In particular it does not increase
// r.Term or change r.Vote.
r.step = stepCandidate
r.tick = r.tickElection
r.state = StatePreCandidate
r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
}
func (r *raft) becomeLeader() {
// TODO(xiangli) remove the panic when the raft implementation is stable
if r.state == StateFollower {
panic("invalid transition [follower -> leader]")
}
r.step = stepLeader
r.reset(r.Term)
r.tick = r.tickHeartbeat
r.lead = r.id
r.state = StateLeader
ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
if err != nil {
r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
}
nconf := numOfPendingConf(ents)
if nconf > 1 {
panic("unexpected multiple uncommitted config entry")
}
if nconf == 1 {
r.pendingConf = true
}
r.appendEntry(pb.Entry{Data: nil})
r.logger.Infof("%x became leader at term %d", r.id, r.Term)
}
func (r *raft) campaign(t CampaignType) {
var term uint64
var voteMsg pb.MessageType
if t == campaignPreElection {
r.becomePreCandidate()
voteMsg = pb.MsgPreVote
// PreVote RPCs are sent for the next term before we've incremented r.Term.
term = r.Term + 1
} else {
r.becomeCandidate()
voteMsg = pb.MsgVote
term = r.Term
}
if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
// We won the election after voting for ourselves (which must mean that
// this is a single-node cluster). Advance to the next state.
if t == campaignPreElection {
r.campaign(campaignElection)
} else {
r.becomeLeader()
}
return
}
for id := range r.prs {
if id == r.id {
continue
}
r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
var ctx []byte
if t == campaignTransfer {
ctx = []byte(t)
}
r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
}
}
func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
if v {
r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
} else {
r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
}
if _, ok := r.votes[id]; !ok {
r.votes[id] = v
}
for _, vv := range r.votes {
if vv {
granted++
}
}
return granted
}
func (r *raft) Step(m pb.Message) error {
// Handle the message term, which may result in our stepping down to a follower.
switch {
case m.Term == 0:
// local message
case m.Term > r.Term:
lead := m.From
if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
force := bytes.Equal(m.Context, []byte(campaignTransfer))
inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
if !force && inLease {
// If a server receives a RequestVote request within the minimum election timeout
// of hearing from a current leader, it does not update its term or grant its vote
r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)",
r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
return nil
}
lead = None
}
switch {
case m.Type == pb.MsgPreVote:
// Never change our term in response to a PreVote
case m.Type == pb.MsgPreVoteResp && !m.Reject:
// We send pre-vote requests with a term in our future. If the
// pre-vote is granted, we will increment our term when we get a
// quorum. If it is not, the term comes from the node that
// rejected our vote so we should become a follower at the new
// term.
default:
r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
r.id, r.Term, m.Type, m.From, m.Term)
r.becomeFollower(m.Term, lead)
}
case m.Term < r.Term:
if r.checkQuorum && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
// We have received messages from a leader at a lower term. It is possible
// that these messages were simply delayed in the network, but this could
// also mean that this node has advanced its term number during a network
// partition, and it is now unable to either win an election or to rejoin
// the majority on the old term. If checkQuorum is false, this will be
// handled by incrementing term numbers in response to MsgVote with a
// higher term, but if checkQuorum is true we may not advance the term on
// MsgVote and must generate other messages to advance the term. The net
// result of these two features is to minimize the disruption caused by
// nodes that have been removed from the cluster's configuration: a
// removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
// but it will not receive MsgApp or MsgHeartbeat, so it will not create
// disruptive term increases
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
} else {
// ignore other cases
r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
r.id, r.Term, m.Type, m.From, m.Term)
}
return nil
}
switch m.Type {
case pb.MsgHup:
if r.state != StateLeader {
ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
if err != nil {
r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
}
if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
return nil
}
r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
if r.preVote {
r.campaign(campaignPreElection)
} else {
r.campaign(campaignElection)
}
} else {
r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
}
case pb.MsgVote, pb.MsgPreVote:
// The m.Term > r.Term clause is for MsgPreVote. For MsgVote m.Term should
// always equal r.Term.
if (r.Vote == None || m.Term > r.Term || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type)})
if m.Type == pb.MsgVote {
// Only record real votes.
r.electionElapsed = 0
r.Vote = m.From
}
} else {
r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type), Reject: true})
}
default:
r.step(r, m)
}
return nil
}
type stepFunc func(r *raft, m pb.Message)
func stepLeader(r *raft, m pb.Message) {
// These message types do not require any progress for m.From.
switch m.Type {
case pb.MsgBeat:
r.bcastHeartbeat()
return
case pb.MsgCheckQuorum:
if !r.checkQuorumActive() {
r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
r.becomeFollower(r.Term, None)
}
return
case pb.MsgProp:
if len(m.Entries) == 0 {
r.logger.Panicf("%x stepped empty MsgProp", r.id)
}
if _, ok := r.prs[r.id]; !ok {
// If we are not currently a member of the range (i.e. this node
// was removed from the configuration while serving as leader),
// drop any new proposals.
return
}
if r.leadTransferee != None {
r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
return
}
for i, e := range m.Entries {
if e.Type == pb.EntryConfChange {
if r.pendingConf {
m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
}
r.pendingConf = true
}
}
r.appendEntry(m.Entries...)
r.bcastAppend()
return
case pb.MsgReadIndex:
if r.quorum() > 1 {
// thinking: use an interally defined context instead of the user given context.
// We can express this in terms of the term and index instead of a user-supplied value.
// This would allow multiple reads to piggyback on the same message.
switch r.readOnly.option {
case ReadOnlySafe:
r.readOnly.addRequest(r.raftLog.committed, m)
r.bcastHeartbeatWithCtx(m.Entries[0].Data)
case ReadOnlyLeaseBased:
var ri uint64
if r.checkQuorum {
ri = r.raftLog.committed
}
if m.From == None || m.From == r.id { // from local member
r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
} else {
r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
}
}
} else {
r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
}
return
}
// All other message types require a progress for m.From (pr).
pr, prOk := r.prs[m.From]
if !prOk {
r.logger.Debugf("%x no progress available for %x", r.id, m.From)
return
}
switch m.Type {
case pb.MsgAppResp:
pr.RecentActive = true
if m.Reject {
r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
r.id, m.RejectHint, m.From, m.Index)
if pr.maybeDecrTo(m.Index, m.RejectHint) {
r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
if pr.State == ProgressStateReplicate {
pr.becomeProbe()
}
r.sendAppend(m.From)
}
} else {
oldPaused := pr.isPaused()
if pr.maybeUpdate(m.Index) {
switch {
case pr.State == ProgressStateProbe:
pr.becomeReplicate()
case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
pr.becomeProbe()
case pr.State == ProgressStateReplicate:
pr.ins.freeTo(m.Index)
}
if r.maybeCommit() {
r.bcastAppend()
} else if oldPaused {
// update() reset the wait state on this node. If we had delayed sending
// an update before, send it now.
r.sendAppend(m.From)
}
// Transfer leadership is in progress.
if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
r.sendTimeoutNow(m.From)
}
}
}
case pb.MsgHeartbeatResp:
pr.RecentActive = true
// free one slot for the full inflights window to allow progress.
if pr.State == ProgressStateReplicate && pr.ins.full() {
pr.ins.freeFirstOne()
}
if pr.Match < r.raftLog.lastIndex() {
r.sendAppend(m.From)
}
if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
return
}
ackCount := r.readOnly.recvAck(m)
if ackCount < r.quorum() {
return
}
rss := r.readOnly.advance(m)
for _, rs := range rss {
req := rs.req
if req.From == None || req.From == r.id { // from local member
r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
} else {
r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
}
}
case pb.MsgSnapStatus:
if pr.State != ProgressStateSnapshot {
return
}
if !m.Reject {
pr.becomeProbe()
r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
} else {
pr.snapshotFailure()
pr.becomeProbe()
r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
}
// If snapshot finish, wait for the msgAppResp from the remote node before sending
// out the next msgApp.
// If snapshot failure, wait for a heartbeat interval before next try
pr.pause()
case pb.MsgUnreachable:
// During optimistic replication, if the remote becomes unreachable,
// there is huge probability that a MsgApp is lost.
if pr.State == ProgressStateReplicate {
pr.becomeProbe()
}
r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
case pb.MsgTransferLeader:
leadTransferee := m.From
lastLeadTransferee := r.leadTransferee
if lastLeadTransferee != None {
if lastLeadTransferee == leadTransferee {
r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
r.id, r.Term, leadTransferee, leadTransferee)
return
}
r.abortLeaderTransfer()
r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
}
if leadTransferee == r.id {
r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
return
}
// Transfer leadership to third party.
r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
// Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
r.electionElapsed = 0
r.leadTransferee = leadTransferee
if pr.Match == r.raftLog.lastIndex() {
r.sendTimeoutNow(leadTransferee)
r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
} else {
r.sendAppend(leadTransferee)
}
}
}
// stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
// whether they respond to MsgVoteResp or MsgPreVoteResp.
func stepCandidate(r *raft, m pb.Message) {
// Only handle vote responses corresponding to our candidacy (while in
// StateCandidate, we may get stale MsgPreVoteResp messages in this term from
// our pre-candidate state).
var myVoteRespType pb.MessageType
if r.state == StatePreCandidate {
myVoteRespType = pb.MsgPreVoteResp
} else {
myVoteRespType = pb.MsgVoteResp
}
switch m.Type {
case pb.MsgProp:
r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
return
case pb.MsgApp:
r.becomeFollower(r.Term, m.From)
r.handleAppendEntries(m)
case pb.MsgHeartbeat:
r.becomeFollower(r.Term, m.From)
r.handleHeartbeat(m)
case pb.MsgSnap:
r.becomeFollower(m.Term, m.From)
r.handleSnapshot(m)
case myVoteRespType:
gr := r.poll(m.From, m.Type, !m.Reject)
r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
switch r.quorum() {
case gr:
if r.state == StatePreCandidate {
r.campaign(campaignElection)
} else {
r.becomeLeader()
r.bcastAppend()
}
case len(r.votes) - gr:
r.becomeFollower(r.Term, None)
}
case pb.MsgTimeoutNow:
r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
}
}
func stepFollower(r *raft, m pb.Message) {
switch m.Type {
case pb.MsgProp:
if r.lead == None {
r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
return
}
m.To = r.lead
r.send(m)
case pb.MsgApp:
r.electionElapsed = 0
r.lead = m.From
r.handleAppendEntries(m)
case pb.MsgHeartbeat:
r.electionElapsed = 0
r.lead = m.From
r.handleHeartbeat(m)
case pb.MsgSnap:
r.electionElapsed = 0
r.lead = m.From
r.handleSnapshot(m)
case pb.MsgTransferLeader:
if r.lead == None {
r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
return
}
m.To = r.lead
r.send(m)
case pb.MsgTimeoutNow:
r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
// Leadership transfers never use pre-vote even if r.preVote is true; we
// know we are not recovering from a partition so there is no need for the
// extra round trip.
r.campaign(campaignTransfer)
case pb.MsgReadIndex:
if r.lead == None {
r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
return
}
m.To = r.lead
r.send(m)
case pb.MsgReadIndexResp:
if len(m.Entries) != 1 {
r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
return
}
r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
}
}
func (r *raft) handleAppendEntries(m pb.Message) {
if m.Index < r.raftLog.committed {
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
return
}
if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
} else {
r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
}
}
func (r *raft) handleHeartbeat(m pb.Message) {
r.raftLog.commitTo(m.Commit)
r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
}
func (r *raft) handleSnapshot(m pb.Message) {
sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
if r.restore(m.Snapshot) {
r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, sindex, sterm)
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
} else {
r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, sindex, sterm)
r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
}
}
// restore recovers the state machine from a snapshot. It restores the log and the
// configuration of state machine.
func (r *raft) restore(s pb.Snapshot) bool {
if s.Metadata.Index <= r.raftLog.committed {
return false
}
if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.commitTo(s.Metadata.Index)
return false
}
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.restore(s)
r.prs = make(map[uint64]*Progress)
for _, n := range s.Metadata.ConfState.Nodes {
match, next := uint64(0), r.raftLog.lastIndex()+1
if n == r.id {
match = next - 1
}
r.setProgress(n, match, next)
r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
}
return true
}
// promotable indicates whether state machine can be promoted to leader,
// which is true when its own id is in progress list.
func (r *raft) promotable() bool {
_, ok := r.prs[r.id]
return ok
}
func (r *raft) addNode(id uint64) {
if _, ok := r.prs[id]; ok {
// Ignore any redundant addNode calls (which can happen because the
// initial bootstrapping entries are applied twice).
return
}
r.setProgress(id, 0, r.raftLog.lastIndex()+1)
r.pendingConf = false
}
func (r *raft) removeNode(id uint64) {
r.delProgress(id)
r.pendingConf = false
// do not try to commit or abort transferring if there is no nodes in the cluster.
if len(r.prs) == 0 {
return
}
// The quorum size is now smaller, so see if any pending entries can
// be committed.
if r.maybeCommit() {
r.bcastAppend()
}
// If the removed node is the leadTransferee, then abort the leadership transferring.
if r.state == StateLeader && r.leadTransferee == id {
r.abortLeaderTransfer()
}
}
func (r *raft) resetPendingConf() { r.pendingConf = false }
func (r *raft) setProgress(id, match, next uint64) {
r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
}
func (r *raft) delProgress(id uint64) {
delete(r.prs, id)
}
func (r *raft) loadState(state pb.HardState) {
if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
}
r.raftLog.committed = state.Commit
r.Term = state.Term
r.Vote = state.Vote
}
// pastElectionTimeout returns true iff r.electionElapsed is greater
// than or equal to the randomized election timeout in
// [electiontimeout, 2 * electiontimeout - 1].
func (r *raft) pastElectionTimeout() bool {
return r.electionElapsed >= r.randomizedElectionTimeout
}
func (r *raft) resetRandomizedElectionTimeout() {
r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
}
// checkQuorumActive returns true if the quorum is active from
// the view of the local raft state machine. Otherwise, it returns
// false.
// checkQuorumActive also resets all RecentActive to false.
func (r *raft) checkQuorumActive() bool {
var act int
for id := range r.prs {
if id == r.id { // self is always active
act++
continue
}
if r.prs[id].RecentActive {
act++
}
r.prs[id].RecentActive = false
}
return act >= r.quorum()
}
func (r *raft) sendTimeoutNow(to uint64) {
r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
}
func (r *raft) abortLeaderTransfer() {
r.leadTransferee = None
}
func numOfPendingConf(ents []pb.Entry) int {
n := 0
for i := range ents {
if ents[i].Type == pb.EntryConfChange {
n++
}
}
return n
}
| mpl-2.0 |
magnusfeuer/m1_core | tools/sqltool/sqlcommon.cc | 85560 | //
// All rights reserved. Reproduction, modification, use or disclosure
// to third parties without express authority is forbidden.
// Copyright Magden LLC, California, USA, 2005, 2006, 2007, 2008.
//
// Some common SQL stuff.
#include "sqlcommon.hh"
#include <sys/time.h>
#include <time.h>
extern void usage(void);
unsigned long time_stamp(void)
{
struct timeval tm;
static unsigned long long first_ts = 0LL;
unsigned long long ts;
gettimeofday(&tm, 0);
ts =tm.tv_sec*1000000LL + tm.tv_usec;
if (first_ts == 0LL)
first_ts = ts;
return (unsigned long) (ts-first_ts)/1000LL; // msec
}
bool extract_from(const string &aFrom,
string &aAccount,
string &aProvider)
{
string::size_type at_pos = aFrom.find("@", 0);
aAccount = "";
aProvider = "";
if (at_pos == string::npos)
return false;
aAccount = aFrom.substr(0, at_pos);
aProvider = aFrom.substr(at_pos + 1);
return true;
}
// Allocate enough bytes to make a safe escape
char *ctx_escape_mysql(MYSQL *aDBDesc, const char *aString, int aLength, CStringContext *aContext)
{
char *res;
unsigned long len = (aLength>0)?aLength:strlen(aString);
if (!(res = (char *) malloc(len * 2 + 1)))
return (char *) "";
mysql_real_escape_string(aDBDesc, res, aString, len);
if (aContext)
aContext->push_back(res);
return res;
}
char *ctx_strcpy(const char *aString, int aLength, CStringContext *aContext)
{
char *res;
unsigned long len = (aLength>0)?aLength:strlen(aString);
if (!(res = (char *) malloc(len + 1)))
return (char *) "";
strncpy(res, aString, len);
res[len] = 0;
if (aContext)
aContext->push_back(res);
return res;
}
char *ctx_sprintf(CStringContext *aContext, char *aFormat, ...)
{
va_list ap;
char *res;
va_start(ap, aFormat);
// $10 bucks you do a man on this function...
vasprintf(&res, aFormat, ap);
va_end(ap);
if (aContext)
aContext->push_back(res);
return res;
}
bool extract_packet_id(string &aID,
string &aAccount,
string &aProvider,
string &aPacket,
int &aMajor,
int &aMinor,
int &aPatch)
{
string tmp;
string::size_type first_slash_pos, second_slash_pos;
// Format is account@provider/packet
if (!extract_from(aID, aAccount, tmp))
return false;
first_slash_pos = tmp.find("/", 0);
second_slash_pos = tmp.find_last_of("/");
// Did we find the slash?
if (first_slash_pos == string::npos)
return false;
aProvider = tmp.substr(0, first_slash_pos);
aMajor = aMinor = aPatch = -1;
// Extract version information.
if (second_slash_pos != string::npos) {
sscanf(tmp.substr(second_slash_pos + 1).c_str(),
"%d.%d.%d",
&aMajor,
&aMinor,
&aPatch);
aPacket = tmp.substr(first_slash_pos + 1, second_slash_pos - first_slash_pos - 1);
} else {
aPacket = tmp.substr(first_slash_pos + 1);
}
// fprintf(stderr, "extract_packet_id() ID[%s] Account[%s] Provider[%s] Packet[%s] Version[%d.%d.%d]\n",
// aID.c_str(),
// aAccount.c_str(),
// aProvider.c_str(),
// aPacket.c_str(),
// aMajor,
// aMinor,
// aPatch);
return true;
}
int db_connect(MYSQL **aDBDesc, string aHost, string aUserName, string aPasswd, string aDatabase, string aCharacterSet)
{
CStringContext ctx;
int port = 0;
char *stmt;
string::size_type col_pos;
if (*aDBDesc != 0)
mysql_close(*aDBDesc);
*aDBDesc = mysql_init(0);
if (aHost == "" && getenv("DB_HOST") != 0)
aHost = getenv("DB_HOST");
if (aUserName == "" && getenv("DB_USER") != 0)
aUserName = getenv("DB_USER");
if (aPasswd == "" && getenv("DB_PASSWORD") != 0)
aPasswd = getenv("DB_PASSWORD");
if (aDatabase == "" && getenv("DB_DATABASE") != 0)
aDatabase = getenv("DB_DATABASE");
//
// Splice port if provided
//
col_pos = aHost.find(':', 0);
if (col_pos != string::npos && aHost.size() > col_pos) {
port = atoi(aHost.substr(col_pos + 1).c_str());
aHost = aHost.substr(0, col_pos);
}
if (!mysql_real_connect(*aDBDesc, aHost.c_str(), aUserName.c_str(), aPasswd.c_str(), aDatabase.c_str(), port, 0, 0)) {
fprintf(stderr, "%lu: db_connect:(): Failed to connect [%s]\n", time_stamp(), mysql_error(*aDBDesc));
mysql_close(*aDBDesc);
return 0;
}
stmt = ctx_sprintf(&ctx, "SET NAMES %s", aCharacterSet.c_str());
if (mysql_query(*aDBDesc, stmt)) {
fprintf(stderr, "$lu: db_connect:(): Failed to [%s] [%s]\n", time_stamp(), stmt, mysql_error(*aDBDesc));
mysql_close(*aDBDesc);
return 0;
}
return 1;
}
// Locate an account id basd on aEmail address.
int db_find_account_by_email(MYSQL *aDBDesc, string aEmail, CAccount *aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
char *stmt;
CStringContext esc_ctx;
// char esc_email[512];
long dbid;
if (!aDBDesc) {
fprintf(stderr, "%lu: db_find_account_by_email(%s): Database not open\n", time_stamp(), aEmail.c_str());
return 0L;
}
// mysql_real_escape_string(aDBDesc, esc_email, aEmail.c_str(), (aEmail.length()>255)?255:aEmail.length());
//
// If the provided TSPID is 0, read everything added after the last timestamp.
//
//
// If TSPID is not zero, read the row
//
stmt = ctx_sprintf(&esc_ctx,
"SELECT "
" id, " // 0
" email, " // 1
" password, " // 2
" password_hint, " // 3
" first_name, " // 4
" middle_name, " // 5
" last_name, " // 6
" address1, " // 7
" address2, " // 8
" city, " // 9
" zip, " // 10
" state, " // 11
" country, " // 12
" home_phone, " // 13
" work_phone, " // 14
" cell_phone, " // 15
" comments, " // 16
" free_shipping, " // 17
" tax_exempt " // 18
"FROM "
" account "
"WHERE "
" email =\'%s\'",
ctx_escape_mysql(aDBDesc, aEmail.c_str(), 0, &esc_ctx));
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "%lu: db_find_account_by_email(%s): Could not execute SQL statement\n%s\n%s\n",
time_stamp(), aEmail.c_str(), stmt, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
return 0L;
}
dbid = atoi(row[0]);
if (!aResult) {
mysql_free_result(res);
return dbid;
}
aResult->mDbID = dbid;
aResult->mEmail = row[1];
aResult->mPassword = row[2];
aResult->mPasswdHint = row[3];
aResult->mFirstName = row[4];
aResult->mMiddleName = row[5];
aResult->mLastName = row[6];
aResult->mAddress1 = row[7];
aResult->mAddress2 = row[8];
aResult->mCity = row[9];
aResult->mZip = row[10];
aResult->mState = row[11];
aResult->mCountry = row[12];
aResult->mHomePhone = row[13];
aResult->mWorkPhone = row[14];
aResult->mCellPhone = row[15];
aResult->mComment = row[16];
aResult->mFreeShipping = atoi(row[17]);
aResult->mTaxExempt = atoi(row[18]);
mysql_free_result(res);
return dbid;
}
// Locate an account id basd on account id address.
long db_find_account_by_id(MYSQL *aDBDesc, long aAccountID, CAccount *aResult)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
if (!aDBDesc) {
fprintf(stderr, "db_find_account_by_id(%s): Database not open\n", aAccountID);
return 0L;
}
//
// If the provided TSPID is 0, read everything added after the last timestamp.
//
//
// If TSPID is not zero, read the row
//
sprintf(buf,
"SELECT "
" id, " // 0
" email, " // 1
" password, " // 2
" password_hint, " // 3
" first_name, " // 4
" middle_name, " // 5
" last_name, " // 6
" address1, " // 7
" address2, " // 8
" city, " // 9
" zip, " // 10
" state, " // 11
" country, " // 12
" home_phone, " // 13
" work_phone, " // 14
" cell_phone, " // 15
" comments, " // 16
" free_shipping, " // 17
" tax_exempt " // 18
"FROM "
" account "
"WHERE "
" id = %ld",
aAccountID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_find_account_by_id(%ld): Could not execute SQL statement\n%s\n%s\n",
aAccountID, buf, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
fprintf(stderr, "db_find_account_by_id(%ld): [%s] Yielded no rows. Error: [%s].\n",
aAccountID, buf, mysql_error(aDBDesc));
return 0L;
}
aResult->mDbID = atoi(row[0]);
aResult->mEmail = row[1];
aResult->mPassword = row[2];
aResult->mPasswdHint = row[3];
aResult->mFirstName = row[4];
aResult->mMiddleName = row[5];
aResult->mLastName = row[6];
aResult->mAddress1 = row[7];
aResult->mAddress2 = row[8];
aResult->mCity = row[9];
aResult->mZip = row[10];
aResult->mState = row[11];
aResult->mCountry = row[12];
aResult->mHomePhone = row[13];
aResult->mWorkPhone = row[14];
aResult->mCellPhone = row[15];
aResult->mComment = row[16];
aResult->mFreeShipping = atoi(row[17]);
aResult->mTaxExempt = atoi(row[18]);
mysql_free_result(res);
// fprintf(stderr, "db_find_account_by_id(%ld): email [%s]\n", aAccountID, aResult->mEmail.c_str());
return aResult->mDbID;
}
// Locate a packfile
// account@domain/name
// account_id represents the account@domain
// while packfile_name is the /name part.
//
int db_find_packfile(MYSQL *aDBDesc, string aPacketID, CPackfileList &aPackfiles)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
char esc_name[514];
char esc_email[514];
string d_acc, d_prov, d_name;
int d_maj, d_min, d_pat;
char *email;
int row_count = 0;
CStringContext esc_ctx;
char *stmt;
if (!aDBDesc) {
fprintf(stderr, "db_find_packfile(%s): Database not open\n", aPacketID.c_str());
return 0;
}
if (!extract_packet_id(aPacketID, d_acc, d_prov, d_name, d_maj, d_min, d_pat)) {
fprintf(stderr, "db_find_packfile(%s): Malformed packet identifier\n", aPacketID.c_str());
return 0;
}
email = ctx_sprintf(&esc_ctx, "%s@%s", d_acc.c_str(), d_prov.c_str());
//
// Big phat select
//
stmt = ctx_sprintf(&esc_ctx,
"SELECT "
" packfile.id, " // 0
" packfile.svn_revision, " // 1
" packfile.creator_account_id, " // 2
" packfile.name, " // 3
" packfile.restart_action, " // 4
" pf_version.id, " // 5
" pf_version.major, " // 6
" pf_version.minor, " // 7
" pf_version.patch, " // 8
" UNIX_TIMESTAMP(pf_version.created) " // 9
"FROM "
" account, packfile, pf_version "
"WHERE "
" account.email LIKE '%s' AND "
" packfile.creator_account_id = account.id AND "
" packfile.name LIKE '%s' AND "
" pf_version.packfile_id = packfile.id AND "
" (pf_version.major = %ld OR %ld = -1) AND "
" (pf_version.minor = %ld OR %ld = -1) AND "
" (pf_version.patch = %ld OR %ld = -1) "
"ORDER BY "
" pf_version.major DESC, "
" pf_version.minor DESC, "
" pf_version.patch DESC",
ctx_escape_mysql(aDBDesc, email, 0, &esc_ctx),
ctx_escape_mysql(aDBDesc, d_name.c_str(), 0, &esc_ctx),
d_maj, d_maj,
d_min, d_min,
d_pat, d_pat);
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_find_packfile(%s): Could not execute SQL statement\n%s\n%s\n",
aPacketID.c_str(), stmt, mysql_error(aDBDesc));
return -1;
}
res = mysql_store_result(aDBDesc);
if (!res) {
fprintf(stderr, "db_find_packfile(%s): [%s] Yielded no rows. Error: [%s].\n",
aPacketID.c_str(), stmt, mysql_error(aDBDesc));
return 0;
}
while((row = mysql_fetch_row(res))) {
row_count++;
// Another entry.
aPackfiles.push_back(CPackfile(atol(row[0]),
atol(row[1]),
row[3],
row[4],
atol(row[2]),
atol(row[5]),
atol(row[6]),
atol(row[7]),
atol(row[8]),
atol(row[9])));
// fprintf(stderr, "db_find_packfile(%s): Got Id[%ld] name[%s] Restart[%s] CreatorID[%ld] VersID[%ld] Major[%ld] Minor[%ld] Patch[%ld] Created[%.24s]\n",
// aPacketID.c_str(),
// aPackfiles.back().mID,
// aPackfiles.back().mName.c_str(),
// aPackfiles.back().mRestartAction.c_str(),
// aPackfiles.back().mCreatorAccountID,
// aPackfiles.back().mVersionID,
// aPackfiles.back().mMajor,
// aPackfiles.back().mMinor,
// aPackfiles.back().mPatch,
// ctime(&(aPackfiles.back().mCreatorTimeStamp)));
}
mysql_free_result(res);
return row_count;
}
long db_create_packfile(MYSQL *aDBDesc, CPackfile &aPackfile)
{
char *stmt;
time_t now;
CStringContext str_ctx;
CPackfileList existing;
CAccount acct;
// Check that an earlier version does not already exist.
if (!db_find_account_by_id(aDBDesc, aPackfile.mCreatorAccountID, &acct)) {
fprintf(stderr, "db_create_packfile(): Failed to retrieve account [%ld]\n",
aPackfile.mCreatorAccountID);
return false;
}
//
// Return all existing versions of the packfile. If no versions
// exist, create a new packfile row, else reuse existing one.
//
if (!db_find_packfile(aDBDesc, acct.mEmail + string("/") + aPackfile.mName, existing)) {
fprintf(stderr, "No packfile named %s/%s exists. Will create it\n", acct.mEmail.c_str(), aPackfile.mName.c_str());
// Create packfile row.
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO packfile "
" (svn_revision, creator_account_id, name, restart_action) "
"VALUES (%ld, %ld, '%s', '%s')",
aPackfile.mSVNRevision,
aPackfile.mCreatorAccountID,
ctx_escape_mysql(aDBDesc, aPackfile.mName.c_str(), 0, &str_ctx),
aPackfile.mRestartAction.c_str());
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_packfile:(): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return 0;
}
// Retrieve the auto generated trusted.id column
aPackfile.mID = (long) mysql_insert_id(aDBDesc);
// fprintf(stderr, "db_create_packfile(): Created packfile id[%ld]\n", aPackfile.mID);
} else {
// Reuse existing packfile id
aPackfile.mID = existing.front().mID;
}
//
// Create version row.
//
aPackfile.mCreatorTimeStamp = time(0);
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_version "
" (packfile_id, major, minor, patch, created) "
"VALUES (%ld, %d, %d, %d, FROM_UNIXTIME(%lu))",
aPackfile.mID,
aPackfile.mMajor,
aPackfile.mMinor,
aPackfile.mPatch,
aPackfile.mCreatorTimeStamp);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_packfile:(): Failed [%s]: [%s]\n", stmt, mysql_error(aDBDesc));
return 0;
}
// Retrieve the auto generated trusted.id column
aPackfile.mVersionID = (long) mysql_insert_id(aDBDesc);
// fprintf(stderr, "db_create_packfile(): Created version id[%ld]\n", aPackfile.mVersionID);
return aPackfile.mVersionID;
}
bool db_delete_packfile(MYSQL *aDBDesc, CPackfile &aPackfile)
{
char *stmt;
CStringContext str_ctx;
CAccount acct;
CPackfileList versions;
// Collect all versions of this packfile so that we know if we are to
// remove the packfile row as well (after last version has been removed).
if (!db_find_account_by_id(aDBDesc, aPackfile.mCreatorAccountID, &acct)) {
fprintf(stderr, "db_delete_packfile(): Failed to retrieve account [%ld]\n",
aPackfile.mCreatorAccountID);
return false;
}
db_find_packfile(aDBDesc, acct.mEmail + string("/") + aPackfile.mName, versions); // Will return one element if this is the last.
// Remove all pf_component_parts
stmt = ctx_sprintf(&str_ctx,
"DELETE "
" pf_component_part "
"FROM "
" pf_component_part, "
" pf_component "
"WHERE "
" pf_component_part.pf_component_id = pf_component.id AND "
" pf_component.pf_version_id = %ld",
aPackfile.mVersionID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(pf_component_part): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
// Remove all pf_component
stmt = ctx_sprintf(&str_ctx,
"DELETE FROM "
" pf_component "
"WHERE "
" pf_version_id = %ld",
aPackfile.mVersionID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(pf_component): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
// Remove all pf_version_dependencies
stmt = ctx_sprintf(&str_ctx,
"DELETE FROM "
" pf_dependencies "
"WHERE "
" pf_version_id = %ld",
aPackfile.mVersionID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(pf_dependencies): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
// Remove all pf_version
stmt = ctx_sprintf(&str_ctx,
"DELETE FROM "
" pf_version "
"WHERE "
" id = %ld",
aPackfile.mVersionID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(pf_version): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
// If there are other pf_version rows still referencing
// the packfile, return now.
if (versions.size() != 1) {
fprintf(stderr, "db_delete_packfile(): Leaving packfile in place since it is still in use by [%ld] pf_versions\n",
versions.size() - 1);
return true;
}
//
// Remove all references from use accounts to this content.
//
fprintf(stderr, "Deleting packfile.id[%ld]\n", aPackfile.mID);
stmt = ctx_sprintf(&str_ctx,
"DELETE FROM "
" content "
"WHERE "
" packfile_id = %ld",
aPackfile.mID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(content): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
// Remove all pf_packfile
stmt = ctx_sprintf(&str_ctx,
"DELETE FROM "
" packfile "
"WHERE "
" id = %ld",
aPackfile.mID);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_delete_packfile:(pf_packfile): Failed to [%s] [%s]\n", stmt,mysql_error(aDBDesc));
return false;
}
return true;
}
// Retrieve all content entries undr the given aVersion.
int db_get_files(MYSQL *aDBDesc, long aVersionID, CContentList &aResult)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
CIDMap map;
int f_cnt = 0;
sprintf(buf,
"SELECT "
" id, " // 0
" fs_path, " // 1
" fs_symlink, " // 2
" comp_type, " // 3
" permission, " // 4
" content_length, " // 5
" link_id, " // 6
" dev_major, " // 7
" dev_minor " // 8
"FROM "
" pf_component "
" WHERE "
" pf_version_id = %ld "
"ORDER BY "
" id ASC", // Make sure we get files before we get the hardlinks to them
aVersionID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_get_files(%ld): Could not execute SQL statement[%s]: %s\n",
aVersionID, buf, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
if (!res) {
fprintf(stderr, "db_get_files(%ld): [%s] Yielded no rows. Error: [%s].\n",
aVersionID, buf, mysql_error(aDBDesc));
return 0L;
}
// Build a list
while ((row = mysql_fetch_row(res))) {
aResult.push_back(CContent(row[1]?row[1]:"", // aPath
row[5]?atol(row[5]):0, // size
atol(row[4]), // perm
atol(row[3]), // type
row[2]?row[2]:"", // symlink target
row[7]?atol(row[7]):0, // major
row[8]?atol(row[8]):0, // minor
0, // Link ptr
atol(row[0]), // db id
row[6]?atol(row[6]):0)); // link id
// fprintf(stderr, "db_get_files(%ld): Got path[%s] size[%lu] perm[%o] type[%d] symlnk[%s] maj[%ld] min[%ld] id[%ld] lnk_id[%ld]\n",
// aVersionID,
// aResult.back().mPath.c_str(),
// aResult.back().mSize,
// aResult.back().mPermission,
// aResult.back().mType,
// aResult.back().mSymlinkTarget.c_str(),
// aResult.back().mMajor,
// aResult.back().mMinor,
// aResult.back().mDbID,
// aResult.back().mLinkID);
map[aResult.back().mDbID] = &(aResult.back());
f_cnt++;
}
mysql_free_result(res);
//
// Resolve mLink ptr in aResult members.
//
for(CContentListIterator iter = aResult.begin(); iter != aResult.end(); ++iter) {
CContent *target;
if (!iter->mLinkID)
continue;
if (!(target = map[iter->mLinkID])) {
fprintf(stderr, "Could not resolve hardlink for file[%s] db link id[%ld]\n", iter->mPath.c_str(), iter->mLinkID);
return 0;
}
fprintf(stderr, "file[%s] linked to [%s]\n", iter->mPath.c_str(), target->mPath.c_str());
iter->mLink = target;
}
return f_cnt;
}
// Load content of file referenced by aContent into aResult.
// aResult will contain aContent->mSize bytes.
//
int db_get_file_content(MYSQL *aDBDesc, CContent *aContent, char *aResult)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
CIDMap map;
unsigned long bytes_read = 0L;
if (aContent->mDbID == 0) {
fprintf(stderr, "db_get_file_content(%s): Database index for this content is 0\n", aContent->mPath.c_str());
return 0;
}
sprintf(buf,
"SELECT "
" content, " // 0
" LENGTH(content) " // 1
"FROM "
" pf_component_part "
"WHERE "
" pf_component_id = %ld "
"ORDER BY "
" id ASC",
aContent->mDbID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_get_file_content(%s): Could not execute SQL statement[%s]: %s\n",
aContent->mPath.c_str(), buf, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
if (!res) {
fprintf(stderr, "db_get_file_content(%s): [%s] Yielded no rows. Error: [%s].\n",
aContent->mPath.c_str(), buf, mysql_error(aDBDesc));
return 0L;
}
while((row = mysql_fetch_row(res))) {
long len = atoi(row[1]);
memcpy(aResult + bytes_read, row[0], len);
bytes_read += len;
}
mysql_free_result(res);
return bytes_read;
}
long db_add_file(MYSQL *aDBDesc, long aVersionID, CContent &aEntry, string aRootPrefix, int aPartSize)
{
long comp_id;
char esc_path[0xFFFF*2+2];
char *stmt;
CStringContext str_ctx;
// Read file if regular.
if (aEntry.mType == DB_CONT_REGULAR || aEntry.mType == DB_CONT_PACKFILE) {
unsigned long bytes_read = 0L;
unsigned long stmt_len;
// Prep statement
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_component "
" (pf_version_id, fs_path, fs_symlink, comp_type, permission, link_id, dev_major, dev_minor, content_length) "
"VALUES(%ld, '%s',NULL, %d, %d, NULL, NULL, NULL, %ld)",
aVersionID,
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mPath).c_str(), 0, &str_ctx),
aEntry.mType,
aEntry.mPermission,
aEntry.mSize);
goto install_entry;
}
// We need to escape the symlink name.
if (aEntry.mType == DB_CONT_SYMLINK) {
// Setup a insert statement for a non regular file
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_component "
" (pf_version_id, fs_path, fs_symlink, comp_type, permission, link_id, dev_major, dev_minor) "
"VALUES(%ld, '%s', '%s', %d, %ld, NULL, NULL, NULL)",
aVersionID,
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mPath).c_str(), 0, &str_ctx),
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mSymlinkTarget).c_str(), 0, &str_ctx),
aEntry.mType,
aEntry.mPermission);
goto install_entry;
};
if (aEntry.mType == DB_CONT_HARDLINK) {
// Setup a insert statement for a non regular file
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_component "
" (pf_version_id, fs_path, fs_symlink, comp_type, permission, link_id, dev_major, dev_minor) "
"VALUES(%ld, '%s', NULL, %d, %ld, %ld, NULL, NULL)",
aVersionID,
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mPath).c_str(), 0, &str_ctx),
aEntry.mType,
aEntry.mPermission,
aEntry.mLink->mDbID);
// fprintf(stderr, "[%s] hardlinked to [%ld]\n", aEntry.mPath.c_str(), aEntry.mLink->mDbID);
goto install_entry;
};
if (aEntry.mType == DB_CONT_BLOCKDEV ||
aEntry.mType == DB_CONT_CHARDEV) {
// Setup a insert statement for a non regular file
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_component "
" (pf_version_id, fs_path, fs_symlink, comp_type, permission, link_id, dev_major, dev_minor) "
"VALUES(%ld, '%s', NULL, %d, %ld, NULL, %lu, %lu)",
aVersionID,
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mPath).c_str(), 0, &str_ctx),
aEntry.mType,
aEntry.mPermission,
aEntry.mMajor,
aEntry.mMinor);
goto install_entry;
};
// Default management
// Setup a insert statement for a non regular file
stmt = ctx_sprintf(&str_ctx,
"INSERT INTO pf_component "
" (pf_version_id, fs_path, fs_symlink, comp_type, permission, link_id, dev_major, dev_minor) "
"VALUES(%ld, '%s',NULL, %d, %ld, NULL, NULL, NULL)",
aVersionID,
ctx_escape_mysql(aDBDesc, (aRootPrefix + aEntry.mPath).c_str(), 0, &str_ctx),
aEntry.mType);
install_entry:
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_add_file:(): Failed to insert into trusted.pf_component [%s]: [%s]\n", stmt, mysql_error(aDBDesc));
return 0;
}
// Retrieve the auto generated trusted.id column
aEntry.mDbID = (long) mysql_insert_id(aDBDesc);
// fprintf(stderr, "db_add_file(): Created pf_component [%s] id[%ld] size[%ld]\n", aEntry.mPath.c_str(), aEntry.mDbID, aEntry.mSize);
// Update this entry with the db id.
//
// Insert component parts if necessary.
//
if (aEntry.mType == DB_CONT_REGULAR || aEntry.mType == DB_CONT_PACKFILE) {
unsigned long bytes_left = aEntry.mSize;
int fdesc = open(aEntry.mPath.c_str(), O_RDONLY);
unsigned char inbuf[aPartSize];
int ret;
int part_count = 0;
if (fdesc == -1) {
fprintf(stderr, "db_add_file(%s): Could not open file: %s\n", aEntry.mPath.c_str(), strerror(errno));
return 0;
}
while(bytes_left > 0) {
int len;
CStringContext part_ctx;
char *part_stmt;
// Read next part
len = read(fdesc, inbuf, aPartSize);
if (len <= 0) {
fprintf(stderr, "db_add_file(%s): Could not read file file: %s\n", aEntry.mPath.c_str(), strerror(errno));
close(fdesc);
return 0;
}
bytes_left -= len;
part_stmt = ctx_sprintf(&part_ctx,
"INSERT INTO pf_component_part "
" (id, pf_component_id, content) "
"VALUES (NULL, %ld, '%s')",
aEntry.mDbID,
ctx_escape_mysql(aDBDesc, (const char *) inbuf, len, &part_ctx));
// We now have an insert query to execute.
if (mysql_query(aDBDesc, part_stmt)) {
fprintf(stderr, "db_add_file:(): Failed to insert into trusted.pf_component_part [%s]", mysql_error(aDBDesc));
close(fdesc);
return 0;
}
// fprintf(stderr, "db_add_file(): Created pf_component_part [%s] id[%ld] len[%d]\n",
// aEntry.mPath.c_str(),
// (long) mysql_insert_id(aDBDesc),
// len);
//
// We have another component part to install.
// Setup insert statement.
//
++part_count;
// Retrieve the auto generated trusted.id column
}
// Flush last part.
close(fdesc);
}
return aEntry.mDbID;
}
long db_add_dependency(MYSQL *aDBDesc, long aPacketVersionID, long aNeededVersionID)
{
long pf_id; // Packfile id. Automatically generated.
long dep_id; // Version id. Automatically generated.
long req_id; // Version id. Automatically generated.
char buf[256];
//
// Create version row.
//
sprintf(buf,
"INSERT INTO pf_dependencies "
" (pf_version_id, requires_pf_version_id) "
"VALUES(%ld, %d)",
aPacketVersionID,
aNeededVersionID);
if (mysql_query(aDBDesc, buf)) {
fprintf(stderr, "db_add_dependency:(): Failed to insert into trusted.pf_dependencies [%s]", mysql_error(aDBDesc));
return 0;
}
// Retrieve the auto generated trusted.id column
dep_id = (long) mysql_insert_id(aDBDesc);
fprintf(stderr, "db_add_dependency pf_dependicies.id[%ld]\n", dep_id);
return dep_id;
}
int db_get_dependencies(MYSQL *aDBDesc, long aPacketVersionID, CDependencyList *aResult)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
char esc_name[514];
char esc_email[514];
string d_acc, d_prov, d_name;
int d_maj, d_min, d_pat;
string email;
int row_count = 0;
if (!aDBDesc) {
fprintf(stderr, "db_get_dependencies(%ld): Database not open\n", aPacketVersionID);
return 0L;
}
sprintf(buf,
"SELECT "
" account.email, " // 0
" packfile.name, " // 1
" pf_version.id, " // 2
" pf_version.major, " // 3
" pf_version.minor, " // 4
" pf_version.patch " // 5
"FROM "
" account, packfile, pf_version, pf_dependencies "
"WHERE "
" pf_dependencies.pf_version_id = %ld AND "
" pf_version.id = pf_dependencies.requires_pf_version_id AND "
" packfile.id = pf_version.packfile_id AND "
" account.id = packfile.creator_account_id "
"ORDER BY "
" packfile.id ASC",
aPacketVersionID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_get_dependencies(%ld): Could not execute SQL statement\n%s\n%s\n",
aPacketVersionID, buf, mysql_error(aDBDesc));
return -1;
}
res = mysql_store_result(aDBDesc);
if (!res) {
fprintf(stderr, "db_get_dependencies(%ld): [%s] Yielded no rows. Error: [%s].\n",
aPacketVersionID, buf, mysql_error(aDBDesc));
return 0;
}
while((row = mysql_fetch_row(res))) {
row_count++;
// Another entry.
aResult->push_back(CDependency(atol(row[2]),
row[0],
row[1],
atol(row[3]),
atol(row[4]),
atol(row[5])));
// fprintf(stderr, "db_get_dependencies(%ld): Got Email[%s] Name[%s] VersID[%ld] Major[%ld] Minor[%ld] Patch[%ld]\n",
// aPacketVersionID,
// aResult->back().mEmail.c_str(),
// aResult->back().mName.c_str(),
// aResult->back().mVersionID,
// aResult->back().mMajor,
// aResult->back().mMinor,
// aResult->back().mPatch);
}
mysql_free_result(res);
return row_count;
}
// Return multiple keys
long db_find_encryption_keys(MYSQL *aDBDesc,
CKeyDataList &aResult,
string aKeyName, // Wildcard search %ABC%
bool aDeviceKeyFlag) // Device flag set or not
{
MYSQL_RES *res;
char *stmt;
MYSQL_ROW row;
CStringContext ctx;
int count = 0;
//
// Create a enc_key row for the device key
//
if (aKeyName != "")
stmt = ctx_sprintf(&ctx,
"SELECT "
" priv_key_data, " // 0
" LENGTH(priv_key_data), " // 1
" pub_key_data, " // 2
" LENGTH(pub_key_data), " // 3
" bin_key_data, " // 4
" LENGTH(bin_key_data), " // 5
" key_name, " // 6
" device_key_flag " // 7
"FROM "
" enc_key "
"WHERE "
" key_name LIKE '%s' AND "
" device_key_flag = %d",
ctx_escape_mysql(aDBDesc, aKeyName.c_str(), 0, &ctx),
aDeviceKeyFlag);
else
stmt = ctx_sprintf(&ctx,
"SELECT "
" priv_key_data, " // 0
" LENGTH(priv_key_data), " // 1
" pub_key_data, " // 2
" LENGTH(pub_key_data), " // 3
" bin_key_data, " // 4
" LENGTH(bin_key_data), " // 5
" key_name, " // 6
" device_key_flag " // 7
"FROM "
" enc_key "
"WHERE "
" device_key_flag = %d ",
aDeviceKeyFlag);
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_find_encryption_keys(%s): Could not execute SQL statement[%s]: %s\n",
aKeyName.c_str(), stmt, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
if (!res) {
fprintf(stderr, "db_find_encryption_keys(%s): [%s] Yielded no rows. Error: [%s].\n",
aKeyName.c_str(), stmt, mysql_error(aDBDesc));
return 0L;
}
while (row = mysql_fetch_row(res)) {
// fprintf(stderr, "db_find_encryption_keys(%s): Adding[%s]\n",aKeyName.c_str(), row[2]);
aResult.push_back(CKeyData(row[6],
row[0], atoi(row[1]),
row[2], atoi(row[3]),
row[4], atoi(row[5]),
atoi(row[7])));
++count;
}
mysql_free_result(res);
return count;
}
long db_get_encryption_key(MYSQL *aDBDesc,
string aKeyName,
CKeyData &aKeyData)
{
MYSQL_RES *res;
char *stmt;
MYSQL_ROW row;
CStringContext ctx;
long key_id;
//
// Create a enc_key row for the device key
//
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" priv_key_data, " // 1
" LENGTH(priv_key_data), " // 2
" pub_key_data, " // 3
" LENGTH(pub_key_data), " // 4
" bin_key_data, " // 5
" LENGTH(bin_key_data), " // 6
" device_key_flag " // 7
"FROM "
" enc_key "
"WHERE "
" key_name = '%s' ",
ctx_escape_mysql(aDBDesc, aKeyName.c_str(), 0, &ctx));
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_encryption_key(%s): Could not execute SQL statement[%s]: %s\n",
aKeyName.c_str(), stmt, mysql_error(aDBDesc));
return 0L;
}
res = mysql_store_result(aDBDesc);
// Did we get a result?
if (!res || !(row = mysql_fetch_row(res))) {
fprintf(stderr, "db_get_encryption_key(%s): [%s] Yielded no rows. Error: [%s].\n",
aKeyName.c_str(), stmt, mysql_error(aDBDesc));
return 0L;
}
// Update provided key
aKeyData.setPrivKeyData(row[1], atoi(row[2]));
aKeyData.setPubKeyData(row[3], atoi(row[4]));
aKeyData.setBinKeyData(row[5], atoi(row[6]));
aKeyData.mDeviceKeyFlag = atoi(row[7]);
aKeyData.mKeyName = aKeyName;
key_id = atoi(row[0]);
mysql_free_result(res);
return key_id;
}
long db_add_encryption_key(MYSQL *aDBDesc,
string aKeyName,
bool aDeviceKeyFlag,
char *aPrivKeyData,
int aPrivKeyDataLength,
char *aPubKeyData,
int aPubKeyDataLength,
char *aBinKeyData,
int aBinKeyDataLength)
{
long enc_key_id;
char *stmt;
CStringContext ctx;
//
// Create a enc_key row for the device key
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO enc_key ( "
" key_name, "
" priv_key_data, "
" pub_key_data, "
" bin_key_data, "
" device_key_flag "
")"
"VALUES ( "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" %d "
")",
aKeyName.c_str(),
ctx_escape_mysql(aDBDesc, aPrivKeyData, aPrivKeyDataLength, &ctx),
ctx_escape_mysql(aDBDesc, aPubKeyData, aPubKeyDataLength, &ctx ),
ctx_escape_mysql(aDBDesc, aBinKeyData, aBinKeyDataLength, &ctx),
aDeviceKeyFlag);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_add_encryption_key:(): Failed to insert into trusted.enc_key [%s]\n", mysql_error(aDBDesc));
return 0;
}
return (long) mysql_insert_id(aDBDesc);
}
long db_get_m1_unit(MYSQL *aDBDesc,
string aSerial, // Serial number of unit to retrieve
CM1Unit &aUnit)
{
MYSQL_RES *res;
MYSQL_ROW row;
CIDMap map;
unsigned long bytes_read = 0L;
CStringContext ctx;
long m1_id = 0;
char *stmt;
//
// Extract m1_row
//
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" build_order_id, " // 1
" UNIX_TIMESTAMP(mfg_date), " // 2
" disk_serial, " // 3
" account_id, " // 4
" enc_key_id " // 5
"FROM "
" m1_unit "
"WHERE "
" serial_nr = '%s' ",
ctx_escape_mysql(aDBDesc, aSerial.c_str(), 0, &ctx));
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_m1_unit(%s): Could not execute SQL statement[%s]: %s\n",
aSerial.c_str(), stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
fprintf(stderr, "db_get_m1_unit(%s): [%s] Yielded no rows. Error: [%s].\n",
aSerial.c_str(), stmt, mysql_error(aDBDesc));
return 0;
}
aUnit.mDbID = atol(row[0]);
aUnit.mSerial = aSerial;
aUnit.mBuildOrderID = atol(row[1]);
aUnit.mManufactureDate = atol(row[2]);
aUnit.mDiskID = row[3];
aUnit.mOwnerAccountID = atol(row[4]);
aUnit.mDeviceKeyID = atol(row[5]);
mysql_free_result(res);
return aUnit.mDbID;
}
int db_add_m1_unit(MYSQL *aDBDesc,
string aPartNr,
string aSerialNr,
char *aDevicePrivKey,
int aDevicePrivKeyLength,
char *aDevicePubKey,
int aDevicePubKeyLength,
char *aDeviceBinKey,
int aDeviceBinKeyLength,
string aDiskSerialNr,
long aOwnerAccountID) // Ref to account
{
long unit_id;
long enc_key_id;
char *stmt;
CStringContext ctx;
CBuildOrder *bo = 0;
CBuildOrderList build_orders;
CPart part;
int bo_cnt;
int bo_remain = 0;
CLotList bo_lots;
// Retrieve the part of the part nr.
if (!db_get_part_by_part_nr(aDBDesc, aPartNr, part)) {
fprintf(stderr, "Could not find part nr [%s] in database\n", aPartNr.c_str());
return false;
}
// Check that we have one build order.
bo_cnt = db_get_build_order(aDBDesc, part.mID, DB_STATUS_ACTIVE, build_orders);
if (bo_cnt <= 0) {
printf("No active build orders found for part [%s]\n", aPartNr.c_str());
return 0L;
}
if (bo_cnt > 1) {
printf("%d build orders active for part [%s]. Only one order must be active at any given time.\n",
bo_cnt, aPartNr.c_str());
while(build_orders.begin() != build_orders.end()) {
printf(" %d - %s\n", build_orders.front().mID, build_orders.front().mDescription.c_str());
build_orders.pop_front();
}
return 0L;
}
bo = &(build_orders.front()); // Shorthand.
// Check how many units are left on this build order.
bo_remain = db_setup_build_order_lots(aDBDesc, bo->mPartID, bo_lots);
if (bo_remain < 1) {
printf("Build order [%ld - %s] is depleted but still active.\n",
bo->mID, bo->mDescription.c_str());
return 0L;
}
if (!(enc_key_id = db_add_encryption_key(aDBDesc, aSerialNr, true,
aDevicePrivKey, aDevicePrivKeyLength,
aDevicePubKey, aDevicePubKeyLength,
aDeviceBinKey, aDeviceBinKeyLength)))
return 0L;
//
// Create m1_unit row.
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO m1_unit ( "
" build_order_id, "
" serial_nr, "
" mfg_date, "
" disk_serial, "
" account_id, "
" enc_key_id) "
"VALUES ( "
" %ld, "
" '%s', "
" NOW(), "
" '%s', "
" %ld, "
" %ld)",
bo->mID,
aSerialNr.c_str(),
aDiskSerialNr.c_str(),
aOwnerAccountID,
enc_key_id);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_add_m1_unit:(): Failed to insert into trusted.m1_units [%s]\n", mysql_error(aDBDesc));
return 0;
}
// Retrieve the auto generated trusted.id column
unit_id = (long) mysql_insert_id(aDBDesc);
//
// Decrease the inventory of all lots used by the build order.
//
db_deplete_build_order(aDBDesc, bo, 1);
return unit_id;
}
int db_add_account(MYSQL *aTrustedDesc,
MYSQL *aUntrustedDesc,
string aEmail,
string aPassword,
string aPasswordHint,
string aFirstName,
string aMiddleName,
string aLastName,
string aAddress1,
string aAddress2,
string aCity,
string aZip,
string aState,
string aCountry,
string aHomePhone,
string aWorkPhone,
string aCellPhone,
string aComment,
FILE *aLog)
{
char *stmt;
CStringContext ctx;
long id;
//
// Create a trusted.account row
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO account ( "
" id,"
" email,"
" password,"
" password_hint,"
" first_name,"
" middle_name,"
" last_name,"
" address1,"
" address2,"
" city,"
" zip,"
" state,"
" country,"
" home_phone,"
" work_phone,"
" cell_phone,"
" free_shipping,"
" tax_exempt,"
" comments, "
" created) "
"VALUES ( "
" NULL, "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" 0, " // Free shipping
" 0, " // Tax exempt
" '%s', "
" NOW()"
")",
ctx_escape_mysql(aTrustedDesc, aEmail.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aPassword.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aPasswordHint.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aFirstName.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aMiddleName.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aLastName.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aAddress1.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aAddress2.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aCity.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aZip.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aState.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aCountry.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aHomePhone.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aWorkPhone.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aCellPhone.c_str(), 0, &ctx),
ctx_escape_mysql(aTrustedDesc, aComment.c_str(), 0, &ctx));
if (aLog)
fprintf(aLog, "db_add_account: Will insert into trusted [%s]\n", stmt);
if (mysql_query(aTrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to insert into trusted.account [%s]\n[%s]", mysql_error(aTrustedDesc), stmt);
return 0;
}
id = (long) mysql_insert_id(aTrustedDesc);
//
// Create an untrusted.account row
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO account ( "
" id,"
" email,"
" password_hint,"
" first_name,"
" middle_name,"
" last_name,"
" address1,"
" address2,"
" city,"
" zip,"
" state,"
" country,"
" home_phone,"
" work_phone,"
" cell_phone,"
" comments) "
"VALUES ( "
" %ld, "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s', "
" '%s' "
")",
id,
ctx_escape_mysql(aUntrustedDesc, aEmail.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aPasswordHint.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aFirstName.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aMiddleName.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aLastName.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aAddress1.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aAddress2.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aCity.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aZip.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aState.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aCountry.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aHomePhone.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aWorkPhone.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aCellPhone.c_str(), 0, &ctx),
ctx_escape_mysql(aUntrustedDesc, aComment.c_str(), 0, &ctx));
if (aLog)
fprintf(aLog, "db_add_account: Will insert into untrusted [%s]\n", stmt);
if (mysql_query(aUntrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to insert into untrusted.account [%s]\n[%s]", mysql_error(aUntrustedDesc), stmt);
return 0;
}
// Retrieve the auto generated trusted.id column
return id;
}
int db_edit_account(MYSQL *aTrustedDesc,
MYSQL *aUntrustedDesc,
FILE *aLog,
string aAccountEmail,
string aEmail, bool aUpdateEmail,
string aPassword, bool aUpdatePassword,
string aPasswordHint, bool aUpdatePasswordHint,
string aFirstName, bool aUpdateFirstName,
string aMiddleName, bool aUpdateMiddleName,
string aLastName, bool aUpdateLastName,
string aAddress1, bool aUpdateAddress1,
string aAddress2, bool aUpdateAddress2,
string aCity, bool aUpdateCity,
string aZip, bool aUpdateZip,
string aState, bool aUpdateState,
string aCountry, bool aUpdateCountry,
string aHomePhone, bool aUpdateHomePhone,
string aWorkPhone, bool aUpdateWorkPhone,
string aCellPhone, bool aUpdateCellPhone,
string aComment, bool aUpdateComment,
CM1UnitList &aOwnedUnits)
{
char *stmt;
CStringContext ctx;
long id;
CM1UnitListIterator unit_iter = aOwnedUnits.begin();
char *cols;
char *vals;
bool c_flg = false;
// Check that
if (!aUpdateEmail && !aUpdatePassword && !aUpdatePasswordHint && !aUpdateFirstName &&
!aUpdateMiddleName && !aUpdateLastName && !aUpdateAddress1 && !aUpdateAddress2 &&
!aUpdateCity && !aUpdateZip &&!aUpdateState && !aUpdateCountry && !aUpdateHomePhone &&
!aUpdateWorkPhone && !aUpdateCellPhone && !aUpdateComment) {
bool updated = false;
// Check if any serial numbers have been provided.
for (CM1UnitListIterator iter = aOwnedUnits.begin(); iter != aOwnedUnits.end(); iter++) {
if (iter->mSerial != "")
updated = true;
++iter;
}
if (!updated) {
if (aLog)
fprintf(aLog, "%lu: cgi_edit_account(): Nothing to be updated for [%s]\n", time_stamp(), aAccountEmail.c_str());
return 1;
}
}
// Setup all stmt we need for trusted.
stmt = ctx_strcpy("UPDATE account SET ", 0, &ctx);
if (aUpdateEmail) { stmt = ctx_sprintf(&ctx, "%s %s email='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aEmail.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdatePassword) { stmt = ctx_sprintf(&ctx, "%s %s password='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aPassword.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdatePasswordHint) { stmt = ctx_sprintf(&ctx, "%s %s password_hint='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aPasswordHint.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateFirstName) { stmt = ctx_sprintf(&ctx, "%s %s first_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aFirstName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateMiddleName) { stmt = ctx_sprintf(&ctx, "%s %s middle_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aMiddleName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateLastName) { stmt = ctx_sprintf(&ctx, "%s %s last_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aLastName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateAddress1) { stmt = ctx_sprintf(&ctx, "%s %s address1='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aAddress1.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateAddress2) { stmt = ctx_sprintf(&ctx, "%s %s address2='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aAddress2.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCity) { stmt = ctx_sprintf(&ctx, "%s %s city='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aCity.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateZip) { stmt = ctx_sprintf(&ctx, "%s %s zip='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aZip.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateState) { stmt = ctx_sprintf(&ctx, "%s %s state='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aState.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCountry) { stmt = ctx_sprintf(&ctx, "%s %s country='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aCountry.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateHomePhone) { stmt = ctx_sprintf(&ctx, "%s %s home_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aHomePhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateWorkPhone) { stmt = ctx_sprintf(&ctx, "%s %s work_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aWorkPhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCellPhone) { stmt = ctx_sprintf(&ctx, "%s %s cell_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aCellPhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateComment) { stmt = ctx_sprintf(&ctx, "%s %s comments='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aTrustedDesc, aComment.c_str(), 0, &ctx)); c_flg = true; }
stmt = ctx_sprintf(&ctx, "%s WHERE email='%s'", stmt, ctx_escape_mysql(aTrustedDesc, aAccountEmail.c_str(), 0, &ctx));
if (aLog)
fprintf(aLog, "%lu: cgi_edit_account(): Updating trusted database: [%s]\n", time_stamp(), stmt);
if (mysql_query(aTrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to insert into trusted.account [%s]\n[%s]", mysql_error(aTrustedDesc), stmt);
return 0;
}
fprintf(aLog, "%lu: cgi_edit_account(): Done updating trusted database.\n", time_stamp());
//
// Wipe all old units owned by the account.
//
if (aOwnedUnits.size() > 0) {
CAccount acc;
if (aUpdateEmail)
db_find_account_by_email(aTrustedDesc, aEmail, &acc);
else
db_find_account_by_email(aTrustedDesc, aAccountEmail, &acc);
stmt = ctx_sprintf(&ctx, "UPDATE m1_unit SET account_id=1 WHERE id = %ld", acc.mDbID);
if (mysql_query(aTrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to unset ownership of m1_units [%s]\n[%s]", mysql_error(aTrustedDesc), stmt);
return 0;
}
//
// Set new ownership on all listed units.
//
for (CM1UnitListIterator iter = aOwnedUnits.begin(); iter != aOwnedUnits.end(); iter++) {
stmt = ctx_sprintf(&ctx, "UPDATE m1_unit SET account_id=%ld WHERE serial_nr = '%s'",
acc.mDbID, ctx_escape_mysql(aTrustedDesc, iter->mSerial.c_str(), 0, &ctx));
if (aLog)
fprintf(aLog, "%lu: cgi_edit_account(): Updating m1 unit[%s] to be owned by [%s]\n",
time_stamp(), iter->mSerial.c_str(), aEmail.c_str());
if (mysql_query(aTrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to set ownership of m1_unit [%s]\n[%s]", mysql_error(aTrustedDesc), stmt);
return 0;
}
if (aLog)
fprintf(aLog, "%lu: cgi_edit_account(): Done updating m1 unit[%s]\n",
time_stamp(), iter->mSerial.c_str());
}
}
// Setup untrusted.
// Retrieve the auto generated trusted.id column
c_flg = false;
stmt = ctx_strcpy("UPDATE account SET ", 0, &ctx);
if (aUpdateEmail) { stmt = ctx_sprintf(&ctx, "%s %s email='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aEmail.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdatePasswordHint) { stmt = ctx_sprintf(&ctx, "%s %s password_hint='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aPasswordHint.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateFirstName) { stmt = ctx_sprintf(&ctx, "%s %s first_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aFirstName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateMiddleName) { stmt = ctx_sprintf(&ctx, "%s %s middle_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aMiddleName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateLastName) { stmt = ctx_sprintf(&ctx, "%s %s last_name='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aLastName.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateAddress1) { stmt = ctx_sprintf(&ctx, "%s %s address1='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aAddress1.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateAddress2) { stmt = ctx_sprintf(&ctx, "%s %s address2='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aAddress2.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCity) { stmt = ctx_sprintf(&ctx, "%s %s city='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aCity.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateZip) { stmt = ctx_sprintf(&ctx, "%s %s zip='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aZip.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateState) { stmt = ctx_sprintf(&ctx, "%s %s state='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aState.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCountry) { stmt = ctx_sprintf(&ctx, "%s %s country='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aCountry.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateHomePhone) { stmt = ctx_sprintf(&ctx, "%s %s home_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aHomePhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateWorkPhone) { stmt = ctx_sprintf(&ctx, "%s %s work_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aWorkPhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateCellPhone) { stmt = ctx_sprintf(&ctx, "%s %s cell_phone='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aCellPhone.c_str(), 0, &ctx)); c_flg = true; }
if (aUpdateComment) { stmt = ctx_sprintf(&ctx, "%s %s comments='%s'", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, aComment.c_str(), 0, &ctx)); c_flg = true; }
// Set units. Ugly for now, but this table will be dumped in the future.
if (unit_iter != aOwnedUnits.end()) { stmt = ctx_sprintf(&ctx, "%s %s m1_serial1=UPPER('%s')", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, unit_iter->mSerial.c_str(), 0, &ctx)); c_flg = true; ++unit_iter; }
if (unit_iter != aOwnedUnits.end()) { stmt = ctx_sprintf(&ctx, "%s %s m1_serial2=UPPER('%s')", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, unit_iter->mSerial.c_str(), 0, &ctx)); c_flg = true; ++unit_iter; }
if (unit_iter != aOwnedUnits.end()) { stmt = ctx_sprintf(&ctx, "%s %s m1_serial3=UPPER('%s')", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, unit_iter->mSerial.c_str(), 0, &ctx)); c_flg = true; ++unit_iter; }
if (unit_iter != aOwnedUnits.end()) { stmt = ctx_sprintf(&ctx, "%s %s m1_serial4=UPPER('%s')", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, unit_iter->mSerial.c_str(), 0, &ctx)); c_flg = true; ++unit_iter; }
if (unit_iter != aOwnedUnits.end()) { stmt = ctx_sprintf(&ctx, "%s %s m1_serial5=UPPER('%s')", stmt, c_flg?",":"", ctx_escape_mysql(aUntrustedDesc, unit_iter->mSerial.c_str(), 0, &ctx)); c_flg = true; ++unit_iter; }
stmt = ctx_sprintf(&ctx, "%s WHERE email='%s'", stmt, ctx_escape_mysql(aUntrustedDesc, aAccountEmail.c_str(), 0, &ctx));
if (aLog)
fprintf(aLog, "%lu: Updating untrusted database: [%s]\n", time_stamp(), stmt);
if (mysql_query(aUntrustedDesc, stmt)) {
fprintf(stderr, "db_add_account:(): Failed to insert into untrusted.account [%s]\n[%s]", mysql_error(aUntrustedDesc), stmt);
return 0;
}
if (aLog)
fprintf(aLog, "%lu: Done updating untrusted database.\n", time_stamp());
return 1;
}
long db_get_serial(MYSQL *aDBDesc,
string aSerial,
long &aDbID,
time_t &aAssignedTS)
{
MYSQL_RES *res;
MYSQL_ROW row;
int ind = 6;
CStringContext ctx;
char *stmt;
aDbID = 0;
aAssignedTS = 0L;
if (aSerial.length() > 6 ||
!isalnum(aSerial[0]) || !isalnum(aSerial[1]) || !isalnum(aSerial[2]) ||
!isalnum(aSerial[3]) || !isalnum(aSerial[4]) || !isalnum(aSerial[5])) {
fprintf(stderr, "db_get_serial(%s) serial number is not in correct format\n",
aSerial.c_str());
return 0;
}
while(ind--)
aSerial[ind] = toupper(aSerial[ind]);
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" UNIX_TIMESTAMP(assigned) " // 1
"FROM "
" m1_serial "
"WHERE "
" serial = '%s' ",
ctx_escape_mysql(aDBDesc, aSerial.c_str(), 0, &ctx));
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_serial(%s): Could not execute SQL statement[%s]: %s\n",
aSerial.c_str(), stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
return 0;
}
aDbID = atol(row[0]);
aAssignedTS = row[1]?atol(row[1]):0L;
mysql_free_result(res);
return aDbID;
}
int db_get_max_serial_batch(MYSQL *aDBDesc, int &aBatch)
{
MYSQL_RES *res;
MYSQL_ROW row;
int ind = 6;
CStringContext ctx;
char *stmt;
aBatch = 0;
stmt = ctx_sprintf(&ctx, "SELECT MAX(batch) FROM m1_serial");
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_max_serial_batch(): Could not execute SQL statement[%s]: %s\n",
stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
return 0;
}
if (row[0])
aBatch = atoi(row[0]);
mysql_free_result(res);
return 1;
}
int db_add_serial(MYSQL *aDBDesc,
string aSerial,
time_t aAssignedTS, // Set to 0 for null insertion
int aBatch) // Sequential for each new batch of serial numbers added to table
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
int ind = 6;
if (aSerial.length() > 6 ||
!isalnum(aSerial[0]) || !isalnum(aSerial[1]) || !isalnum(aSerial[2]) ||
!isalnum(aSerial[3]) || !isalnum(aSerial[4]) || !isalnum(aSerial[5])) {
fprintf(stderr, "db_add_serial(%s) serial number is not in correct format\n",
aSerial.c_str());
return 0;
}
while(ind--)
aSerial[ind] = toupper(aSerial[ind]);
if (aAssignedTS != 0L)
sprintf(buf, "INSERT INTO m1_serial (serial, assigned, owner_id, batch) VALUES ('%s', FROM_UNIXTIME(%lu), 1, %d)",
aSerial.c_str(), aAssignedTS, aBatch);
else
sprintf(buf, "INSERT INTO m1_serial (serial, assigned, owner_id, batch) VALUES ('%s', NULL, 1, %d) ",
aSerial.c_str(), aBatch);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_add_serial(%s): Could not execute SQL statement[%s]: %s\n",
aSerial.c_str(), buf, mysql_error(aDBDesc));
return 0;
}
return 1;
}
long db_assign_next_serial(MYSQL *aDBDesc, string &aSerial)
{
MYSQL_RES *res;
char buf[2048];
MYSQL_ROW row;
long ser_id;
// Get first unused serial
if (mysql_query(aDBDesc, "SELECT serial, id FROM m1_serial WHERE ISNULL(ASSIGNED) ORDER BY serial ASC LIMIT 1") != 0) {
fprintf(stderr, "db_assign_next_serial(): Could not execute SQL statement[SELECT * FROM m1_serial WHERE ISNULL(ASSIGNED) ORDER BY id ASC LIMIT 1]: %s\n",
mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
if (res)
mysql_free_result(res);
fprintf(stderr, "db_assign_next_serial(): No more serial numbers are available\n");
return 0;
}
aSerial = row[0];
ser_id = atoi(row[1]);
mysql_free_result(res);
// Assign the given serial.
sprintf(buf, "UPDATE m1_serial SET assigned=NOW() WHERE id=%ld", ser_id);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_assign_next_serial(%ld): Could not execute SQL statement[%s]: %s\n",
ser_id, buf, mysql_error(aDBDesc));
return 0;
}
return ser_id;
}
long db_unassign_serial(MYSQL *aDBDesc, long aDbID)
{
char buf[2048];
sprintf(buf, "UPDATE m1_serial SET assigned=NULL WHERE id=%ld", aDbID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_assign_serial(%ld): Could not execute SQL statement[%s]: %s\n",
aDbID, buf, mysql_error(aDBDesc));
return 0;
}
return 1;
}
long db_create_part(MYSQL *aDBDesc,
string aPartNr, // Textual part nr.
string aDescription) // Description of lot.
{
CPart part;
MYSQL_RES *res;
char *stmt;
CStringContext ctx;
//
// Create build order insert statement
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO part ( "
" id, "
" description) "
"VALUES ( "
" NULL, "
" '%s')",
ctx_escape_mysql(aDBDesc, aDescription.c_str(), aDescription.size(), &ctx));
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_part:(): Failed to insert into trusted.part [%s]\n", mysql_error(aDBDesc));
return 0;
}
// Return the auto generated trusted.id column
return (long) mysql_insert_id(aDBDesc);
}
// Get all parts in the system
int db_get_all_parts(MYSQL *aDBDesc, CPartList &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
CStringContext ctx;
char *stmt;
int cnt = 0;
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" part_nr, " // 2
" description " // 3
"FROM "
" part");
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_all_parts(): Could not execute SQL statement[%s]: %s\n",
stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res) {
mysql_free_result(res);
return 0;
}
while((row = mysql_fetch_row(res))) {
aResult.push_back(CPart(atol(row[0]), row[1], row[2], 0));
cnt++;
}
mysql_free_result(res);
return cnt;
}
long db_get_part(MYSQL *aDBDesc,
long aPartID,
CPart &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
CStringContext ctx;
char *stmt;
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" part_nr, " // 1
" description " // 2
"FROM "
" part "
"WHERE "
" id = %ld ",
aPartID);
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_part(%ld): Could not execute SQL statement[%s]: %s\n",
aPartID, stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
return 0;
}
aResult.mID = atol(row[0]);
aResult.mPartNr = row[1];
aResult.mDescription = row[2];
mysql_free_result(res);
return aResult.mID;
}
long db_get_part_by_part_nr(MYSQL *aDBDesc,
string aPartNr,
CPart &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
CStringContext ctx;
char *stmt;
stmt = ctx_sprintf(&ctx,
"SELECT "
" id, " // 0
" part_nr, " // 1
" description " // 2
"FROM "
" part "
"WHERE "
" part_nr = '%s' ",
ctx_escape_mysql(aDBDesc, aPartNr.c_str(), 0, &ctx));
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_part_by_part_nr(%s): Could not execute SQL statement[%s]: %s\n",
aPartNr.c_str(), stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res || !(row = mysql_fetch_row(res))) {
mysql_free_result(res);
return 0;
}
aResult.mID = atol(row[0]);
aResult.mPartNr = row[1];
aResult.mDescription = row[2];
mysql_free_result(res);
return aResult.mID;
}
long db_create_build_order(MYSQL *aDBDesc,
CPart *aPart,
time_t aCreated,
int aStatus,
string aDescription,
int aQuantity)
{
CPart part;
MYSQL_RES *res;
char *stmt;
CStringContext ctx;
//
// Create build order insert statement
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO build_order ( "
" id, "
" part_id, "
" created, "
" quantity, "
" remaining, "
" description, "
" status) "
"VALUES ( "
" NULL, "
" %ld, "
" FROM_UNIXTIME(%lu), "
" %d, "
" %d, "
" '%s', "
" %d)",
aPart->mID,
aCreated?aCreated:time(0),
aQuantity,
aQuantity,
ctx_escape_mysql(aDBDesc, aDescription.c_str(), aDescription.size(), &ctx),
aStatus);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_build_order:(): Failed to insert into trusted.build_order [%s]\n", mysql_error(aDBDesc));
return 0;
}
// Return the auto generated trusted.id column
return (long) mysql_insert_id(aDBDesc);
}
int db_get_bom_by_id(MYSQL *aDBDesc,
long aPartID,
CPartList &aResult) // The Part we want BOM for.
{
MYSQL_RES *res;
MYSQL_ROW row;
CStringContext ctx;
char *stmt;
int cnt = 0;
stmt = ctx_sprintf(&ctx,
"SELECT "
" part.id, " // 0
" part.part_nr, " // 1
" part.description, " // 2
" bom.quantity " // 3
"FROM "
" part, "
" bom "
"WHERE "
" part.id=bom.src_part_id AND "
" bom.dst_part_id = %ld ",
aPartID);
if (mysql_query(aDBDesc, stmt) != 0) {
fprintf(stderr, "db_get_bom(%ld): Could not execute SQL statement[%s]: %s\n",
aPartID, stmt, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res) {
mysql_free_result(res);
return 0;
}
while((row = mysql_fetch_row(res))) {
aResult.push_back(CPart(atol(row[0]), // mID
row[1],
row[2],
atoi(row[3])));
cnt++;
}
mysql_free_result(res);
return cnt;
}
int db_get_bom_by_part_nr(MYSQL *aDBDesc,
string aPartNr,
CPartList &aResult) // The Part we want BOM for.
{
CPart target_part;
if (!db_get_part_by_part_nr(aDBDesc, aPartNr, target_part))
return -1;
return db_get_bom_by_id(aDBDesc, target_part.mID, aResult);
}
int db_get_build_order(MYSQL *aDBDesc,
long aPartID,
int aStatus,
CBuildOrderList &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
CStringContext ctx;
char buf[512];
int cnt = 0;
sprintf(buf,
"SELECT "
" id, " // 0
" part_id, " // 1
" created, " // 2
" quantity, " // 3
" remaining, " // 4
" description, " // 5
" status " // 6
"FROM "
" build_order ");
if (aPartID != DB_ALL)
sprintf(buf + strlen(buf), "WHERE part_id = %ld ", aPartID);
if (aStatus != DB_ALL)
sprintf(buf + strlen(buf) , "%s status = %d ", (aPartID == DB_ALL)?"WHERE":"AND", aStatus);;
strcat(buf + strlen(buf), "ORDER BY created ASC");
if (mysql_query(aDBDesc, buf) != 0 || !(res = mysql_store_result(aDBDesc))) {
fprintf(stderr, "db_get_build_order(%ld): Could not execute SQL statement[%s]: %s\n",
aPartID, buf, mysql_error(aDBDesc));
return -1;
}
while((row = mysql_fetch_row(res))) {
aResult.push_back(CBuildOrder(atol(row[0]), // mID
atol(row[1]), // mPartID,
atol(row[2]), // mCreated
atol(row[3]), // mQuantity
atol(row[4]), // mRemaining
row[5],
atoi(row[6])));
++cnt;
}
mysql_free_result(res);
return cnt;
}
//
// Decrease relevant lot count.
// May deactivate lots as needed.
// May complete a build order.
//
bool db_deplete_build_order(MYSQL *aDBDesc,
CBuildOrder *aBuildOrder,
int aQuantity) // Number of units to deplete.
{
CPartList parts;
CPart target_part;
int res;
bool finished = false;
char buf[512];
if (!db_get_part(aDBDesc, aBuildOrder->mPartID, target_part)) {
fprintf(stderr, "Could not get part [%ld]\n", aBuildOrder->mPartID);
return false;
}
res = db_get_bom_by_id(aDBDesc, target_part.mID, parts); // Retrieve the BOM
if (res <= 0) {
fprintf(stderr, "Could not get BOM for part [%ld]\n", target_part.mID);
return false;
}
//
// Deplete build_order row in db.
//
aBuildOrder->mRemaining -= aQuantity;
sprintf(buf,
"UPDATE "
" build_order "
"SET "
" remaining = %d "
"WHERE "
" id = %ld",
aBuildOrder->mRemaining,
aBuildOrder->mID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_deplete_build_order(%ld): Could not execute SQL statement[%s]: %s\n",
aBuildOrder->mID, buf, mysql_error(aDBDesc));
return false;
}
printf("%ld is made out of %d parts\n", target_part.mID, res);
//
// Walk through all parts, find the active lot for each part,
// and decrease the remaining units for that lot.
// If lot is depleted, we must deactivate that lot and the
// current build order and activate the next lot for the same
// part number and the next build order.
//
for (CPartListIterator iter = parts.begin(); iter != parts.end(); ++iter) {
CLotList lots;
int cnt = db_get_lots(aDBDesc, iter->mID, DB_STATUS_ACTIVE, lots);
int rem;
if (cnt == 0) {
printf("Part [%s] has no active lots. Zero units can be built.\n", iter->mPartNr.c_str());
return false;
}
if (cnt > 1) {
printf("Part [%s] has %d active lots. Only the first one will be used.\n", iter->mPartNr.c_str(), cnt);
return false;
}
rem = db_deplete_lot(aDBDesc, iter->mQuantity, lots.front());
if (rem <= 0) {
printf("Lot [%d - %s] depleted (%d). Deactiving\n",
lots.front().mID, lots.front().mDescription.c_str(), rem);
db_deactivate_lot(aDBDesc, lots.front().mID);
finished = true;
}
}
// If one ore more lots have been depleted, deactivate the build order.
if (finished || aBuildOrder->mRemaining == 0) {
if (aBuildOrder->mRemaining > 0)
printf("WARNING: Build order [%ld - %s] still has %d units left, but one or more lots are depleted. Deactivating\n",
aBuildOrder->mID, aBuildOrder->mDescription.c_str(), aBuildOrder->mRemaining);
db_deactivate_build_order(aDBDesc, aBuildOrder->mID);
printf("This was the last unit of old build order [%ld - %s].\n",
aBuildOrder->mID,
aBuildOrder->mDescription.c_str());
return true;
}
printf("There are [%d] units left to be built from build order [%ld - %s]\n",
aBuildOrder->mRemaining, aBuildOrder->mID, aBuildOrder->mDescription.c_str());
}
//
// Deactivate a single lot.
//
bool db_deactivate_lot(MYSQL *aDBDesc,
long aLotID)
{
char buf[512];
sprintf(buf,
"UPDATE "
" lot "
"SET "
" status = %d "
"WHERE "
" id = %ld",
DB_STATUS_COMPLETE,
aLotID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_deactivate_lot(%ld): Could not execute SQL statement[%s]: %s\n",
aLotID, buf, mysql_error(aDBDesc));
return false;
}
return true;
}
//
// Attempt to activate all lots necessary for the given part nr.
// Return number of aPartID units that can be built.
// 0 = lot shortage.
//
int db_setup_build_order_lots(MYSQL *aDBDesc,
long aPartID, // Part to setup assembly lots for
CLotList &aActiveLots) // All active lots
{
CPartList s_parts;
int bom_cnt;
int qty = -1;
//
// Retrieve the BOM for the partn
//
bom_cnt = db_get_bom_by_id(aDBDesc, aPartID, s_parts); // Retrieve the BOM for aPartNr
if (bom_cnt <= 0) {
printf("db_setup_lots(): Bill Of Material could not be retreived for part nr [%ld]\n", aPartID);
}
//
// Walk through the BOM and check that we have active ltos
// available for each included part, or can activate a lot for it.
//
while(s_parts.begin() != s_parts.end()) {
CLotList active_lots;
CLot new_active_lot;
int a_cnt = db_get_lots(aDBDesc, s_parts.front().mID, DB_STATUS_ACTIVE, active_lots);
if (a_cnt <= 0) {
// printf("BOM part [%s] has no active lot, trying to activate one.\n", s_parts.front().mPartNr.c_str());
if (!db_activate_next_lot(aDBDesc, s_parts.front().mID, new_active_lot)) {
// printf("BOM part [%s] has no more pending lots to activate.\n", s_parts.front().mPartNr.c_str());
aActiveLots.push_back(CLot(-1, s_parts.front().mID, 0, -1, -1, "", "", -1));
qty = 0;
s_parts.pop_front();
continue;
}
// printf("BOM part [%s] has new lot [%s] as its active lot with [%d] remaining units\n",
// s_parts.front().mPartNr.c_str(), new_active_lot.mPO.c_str(), new_active_lot.mRemaining);
if (qty == -1 || qty > new_active_lot.mRemaining)
qty= new_active_lot.mRemaining;
aActiveLots.push_back(new_active_lot);
s_parts.pop_front();
continue;
}
if (a_cnt > 1)
printf("WARNING: BOM part [%s] has [%d] active lots. Only one is suppsed to be active. Using the first.\n",
s_parts.front().mPartNr.c_str(), active_lots.size());
// printf("BOM part [%s] has old lot [%s] as its active lot with [%d] remaining units\n",
// s_parts.front().mPartNr.c_str(), active_lots.front().mPO.c_str(), active_lots.front().mRemaining);
if (qty == -1 || qty > active_lots.front().mRemaining)
qty= active_lots.front().mRemaining;
aActiveLots.push_back(active_lots.front());
s_parts.pop_front();
}
return qty;
}
bool db_activate_next_lot(MYSQL *aDBDesc,
long aPartID, // Part to setup assembly lots for
CLot &aNewActiveLot) // All active lots
{
char buf[512];
CLotList lst;
int lot_cnt;
lot_cnt = db_get_lots(aDBDesc,
aPartID,
DB_STATUS_PENDING,
lst);
// No more lots pending?
if (lot_cnt <= 0)
return false;
sprintf(buf,
"UPDATE "
" lot "
"SET "
" status = %d "
"WHERE "
" id = %ld",
DB_STATUS_ACTIVE,
lst.front().mID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_activate_next_lot(%ld): Could not execute SQL statement[%s]: %s\n",
lst.front().mID, buf, mysql_error(aDBDesc));
return false;
}
aNewActiveLot = lst.front();
return true;
}
//
// Deactivate a single build order.
//
bool db_deactivate_build_order(MYSQL *aDBDesc,
long aBuildOrderID)
{
char buf[512];
sprintf(buf,
"UPDATE "
" build_order "
"SET "
" status = %d "
"WHERE "
" id = %ld",
DB_STATUS_COMPLETE,
aBuildOrderID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_deactivate_build_order(%ld): Could not execute SQL statement[%s]: %s\n",
aBuildOrderID, buf, mysql_error(aDBDesc));
return false;
}
return true;
}
long db_create_lot(MYSQL *aDBDesc,
int aPartID, // Part # of lot.
time_t aCreated, // When was lot created
int aQuantity, // Quantity of aPartID in lot. remaining col will be set to this value.
string aPO, // Purchase order string. Ties into QB PO
string aDescription, // Description of lot.
int aStatus)
{
CPart part;
MYSQL_RES *res;
char *stmt;
CStringContext ctx;
//
// Create build order insert statement
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO lot ( "
" id, "
" part_id, "
" created, "
" quantity, "
" remaining, "
" po, "
" description, "
" status) "
"VALUES ( "
" NULL, "
" %ld, "
" FROM_UNIXTIME(%lu), "
" %d, "
" %d, "
" '%s', "
" '%s', "
" %d)",
aPartID,
aCreated?aCreated:time(0),
aQuantity,
aQuantity,
ctx_escape_mysql(aDBDesc, aPO.c_str(), aPO.size(), &ctx),
ctx_escape_mysql(aDBDesc, aDescription.c_str(), aDescription.size(), &ctx),
aStatus);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_build_lot:(): Failed to insert into trusted.lot [%s]\n", mysql_error(aDBDesc));
return 0;
}
// Return the auto generated trusted.id column
return (long) mysql_insert_id(aDBDesc);
}
long db_get_lots(MYSQL *aDBDesc,
long aPartID,
int aStatus,
CLotList &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
char buf[256];
int cnt = 0;
sprintf(buf,
"SELECT "
" id, " // 0
" part_id, " // 1
" UNIX_TIMESTAMP(created), " // 2
" quantity, " // 3
" remaining, " // 4
" po, " // 5
" description, " // 6
" status " // 7
"FROM "
" lot ");
if (aPartID != DB_ALL)
sprintf(buf + strlen(buf), "WHERE part_id = %ld ", aPartID);
if (aStatus != DB_ALL)
sprintf(buf + strlen(buf) , "%s status = %d ", (aPartID == DB_ALL)?"WHERE":"AND", aStatus);
strcat(buf + strlen(buf), "ORDER BY part_id ASC, created ASC");
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_get_lots(): Could not execute SQL statement[%s]: %s\n",
buf, mysql_error(aDBDesc));
return 0;
}
res = mysql_store_result(aDBDesc);
if (!res) {
mysql_free_result(res);
return 0;
}
while((row = mysql_fetch_row(res))) {
aResult.push_back(CLot(atol(row[0]), // mID
atol(row[1]), // mPartID
atol(row[2]), // mCreated
atoi(row[3]), // mQuantity
atoi(row[4]), // mRemaining
row[5], // mPO
row[6], // mDescription
atoi(row[7]))); // mStatus
cnt++;
}
mysql_free_result(res);
return cnt;
}
//
// Deplete a single lot.
// Return the number of remaining units in this lot.
//
int db_deplete_lot(MYSQL *aDBDesc,
int aQuantity,
CLot &aLot)
{
char buf[512];
aLot.mRemaining -= aQuantity;
sprintf(buf,
"UPDATE "
" lot "
"SET "
" remaining = %d "
"WHERE "
" id = %ld",
aLot.mRemaining,
aLot.mID);
if (mysql_query(aDBDesc, buf) != 0) {
fprintf(stderr, "db_deplete_lot(%ld): Could not execute SQL statement[%s]: %s\n",
aLot.mID, buf, mysql_error(aDBDesc));
return 0;
}
return aLot.mRemaining;
}
long db_create_sales_order(MYSQL *aDBDesc,
time_t aCreated,
string aTransNr,
string aOrderID,
CAccount *aAccount,
CPart *aPart,
int aQuantity,
float aPrice,
float aShippingFee,
float aTax)
{
CPart part;
MYSQL_RES *res;
char *stmt;
CStringContext ctx;
//
// Create build order insert statement
//
stmt = ctx_sprintf(&ctx,
"INSERT INTO sales_order ( "
" id, "
" created, "
" account_id, "
" trans_nr, "
" order_id, "
" quantity, "
" part_nr, "
" subtotal, "
" sh_fee, "
" tax) "
"VALUES ( "
" NULL, "
" FROM_UNIXTIME(%lu), "
" %ld, "
" '%s', "
" '%s', "
" %d, "
" '%s', "
" %f, "
" %f, "
" %f)",
aCreated?aCreated:time(0),
aAccount->mDbID,
ctx_escape_mysql(aDBDesc, aTransNr.c_str(), aTransNr.size(), &ctx),
ctx_escape_mysql(aDBDesc, aOrderID.c_str(), aOrderID.size(), &ctx),
aQuantity,
ctx_escape_mysql(aDBDesc, aPart->mPartNr.c_str(), aPart->mPartNr.size(), &ctx),
aPrice,
aShippingFee,
aTax);
if (mysql_query(aDBDesc, stmt)) {
fprintf(stderr, "db_create_sales_order:(): Failed to insert into trusted.lot [%s]\n", mysql_error(aDBDesc));
return 0;
}
// Return the auto generated trusted.id column
return (long) mysql_insert_id(aDBDesc);
}
int db_get_sale_order(MYSQL *aDBDesc,
CSalesOrderList &aResult)
{
MYSQL_RES *res;
MYSQL_ROW row;
char buf[512];
int cnt = 0;
sprintf(buf,
"SELECT "
" id, " // 0
" UNIX_TIMESTAMP(created), " // 1
" account_id, " // 2
" trans_nr, " // 3
" quantity, " // 4
" part_nr, " // 5
" subtotal, " // 6
" sh_fee, " // 7
" tax " // 8
"FROM "
" sales_order "
"ORDER BY created ASC");
if (mysql_query(aDBDesc, buf) != 0 || !(res = mysql_store_result(aDBDesc))) {
printf("db_get_sales_order(): Could not execute SQL statement[%s]: %s\n",
buf, mysql_error(aDBDesc));
return -1;
}
while((row = mysql_fetch_row(res))) {
aResult.push_back(CSalesOrder(atol(row[0]), // mID
atol(row[1]), // mCreated
atol(row[2]), // mAccountID
row[3], // mTransNr
row[5], // mPartNr
atol(row[4]), // mQuantity
atof(row[6]), // mPrice
atof(row[8]), // mTax
atof(row[7]))); // mShippingFee
++cnt;
}
mysql_free_result(res);
return cnt;
}
bool db_get_discount(MYSQL *aDBDesc,
long aAccountID,
string aPartNr,
int &aResultStartVolume,
float &aResultPercent,
float &aResultPrice)
{
MYSQL_RES *res;
MYSQL_ROW row;
int cnt = 0;
long sales_count = 0;
CPart part;
char *stmt;
CStringContext ctx;
//
// Create build order insert statement
//
stmt = ctx_sprintf(&ctx,
"SELECT "
" SUM(quantity) " // 0
"FROM "
" sales_order "
"WHERE "
" part_nr = '%s' AND "
" account_id = %ld",
ctx_escape_mysql(aDBDesc, aPartNr.c_str(), aPartNr.size(), &ctx),
aAccountID);
if (mysql_query(aDBDesc, stmt) != 0 || !(res = mysql_store_result(aDBDesc))) {
fprintf(stderr, "db_get_discount(%ld, %s): Could not execute SQL statement[%s]: %s\n",
aAccountID,
aPartNr.c_str(),
stmt, mysql_error(aDBDesc));
return false;
}
if ((row = mysql_fetch_row(res)) && row[0]) {
sales_count = atol(row[0]);
} else
sales_count = 0;
mysql_free_result(res);
fprintf(stderr, "db_get_discount(%ld, %s): %ld sales found\n", aAccountID, aPartNr.c_str(), sales_count);
stmt = ctx_sprintf(&ctx,
"SELECT "
" start_volume, " // 0
" percent, " // 1
" price " // 2
"FROM "
" discount "
"WHERE "
" part_nr = '%s' AND "
" account_id = %ld AND "
" start_volume <= %ld "
"ORDER BY start_volume DESC",
ctx_escape_mysql(aDBDesc, aPartNr.c_str(), aPartNr.size(), &ctx),
aAccountID,
sales_count);
if (mysql_query(aDBDesc, stmt) != 0 || !(res = mysql_store_result(aDBDesc))) {
fprintf(stderr, "db_get_discount(%ld, %s): Could not execute SQL statement[%s]: %s\n",
aAccountID,
aPartNr.c_str(),
stmt, mysql_error(aDBDesc));
return false;
}
if (!(row = mysql_fetch_row(res))) {
mysql_free_result(res);
fprintf(stderr, "db_get_discount(%ld, %s): No discount found\n",
aAccountID, aPartNr.c_str());
return false;
}
aResultStartVolume = atoi(row[0]);
aResultPercent = atof(row[1]);
aResultPrice = atof(row[2]);
mysql_free_result(res);
return true;
}
| mpl-2.0 |
pumasecurity/puma-scan | Puma.Security.Rules/Analyzer/Core/BinaryExpressionSyntaxAnalyzer.cs | 1558 | /*
* Copyright(c) 2016 - 2020 Puma Security, LLC (https://pumasecurity.io)
*
* Project Leads:
* Eric Johnson (eric.johnson@pumascan.com)
* Eric Mead (eric.mead@pumascan.com)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Puma.Security.Rules.Common;
namespace Puma.Security.Rules.Analyzer.Core
{
internal class BinaryExpressionSyntaxAnalyzer : BaseSyntaxNodeAnalyzer<BinaryExpressionSyntax>
{
private readonly ISyntaxNodeAnalyzer<SyntaxNode> _analyzer;
internal BinaryExpressionSyntaxAnalyzer()
{
_analyzer = new SyntaxNodeAnalyzer();
}
public override bool CanIgnore(SemanticModel model, SyntaxNode syntax)
{
var binaryExpressionSyntax = syntax as BinaryExpressionSyntax;
return _analyzer.CanIgnore(model, binaryExpressionSyntax.Right) &&
_analyzer.CanIgnore(model, binaryExpressionSyntax.Left);
}
public override bool CanSuppress(SemanticModel model, SyntaxNode syntax, DiagnosticId ruleId)
{
var binaryExpressionSyntax = syntax as BinaryExpressionSyntax;
return _analyzer.CanSuppress(model, binaryExpressionSyntax.Right, ruleId) &&
_analyzer.CanSuppress(model, binaryExpressionSyntax.Left, ruleId);
}
}
} | mpl-2.0 |
CantillatingZygote/rubiginouschanticleer | server/sessions/sessions.js | 1094 | // var db = require( '../config/db' );
// var Sequelize = require( 'sequelize' );
// var Session = db.define( 'sessions', {
// sessionName : Sequelize.STRING
// } );
// Session.sync().then( function() {
// console.log( "sessions table created" );
// } )
// .catch( function( err ) {
// console.error( err );
// } );
// module.exports = Session;
var db = require( '../config/db' );
var Sequelize = require( 'sequelize' );
// var newMovies = require('../config/db');
var Session = db.define( 'sessions', {
sessionName : Sequelize.STRING
});
var NewMovie = db.define('newMovies', {
title: Sequelize.STRING,
poster: Sequelize.STRING,
plot: Sequelize.STRING,
votes: Sequelize.INTEGER,
year: Sequelize.INTEGER,
session_id: {
type: Sequelize.INTEGER //,
//unique: 'newMovies_idx'
}
});
Session.sync().then( function() {
console.log( "sessions table created" );
NewMovie.sync();
} )
.catch( function( err ) {
console.error( err );
} );
NewMovie.belongsTo(Session, {foreignKey: 'session_id'});
module.exports = {
Session: Session,
NewMovie: NewMovie
};
| mpl-2.0 |
vikaspandeysahaj/muzima-android-2 | src/main/java/com/muzima/view/MuzimaListFragment.java | 2236 | /*
* Copyright (c) 2014. The Trustees of Indiana University.
*
* This version of the code is licensed under the MPL 2.0 Open Source license with additional
* healthcare disclaimer. If the user is an entity intending to commercialize any application
* that uses this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.view;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.muzima.R;
import com.muzima.adapters.ListAdapter;
import com.muzima.utils.Fonts;
public abstract class MuzimaListFragment extends SherlockFragment implements AdapterView.OnItemClickListener {
private static final String TAG = "MuzimaListFragment";
protected ListView list;
protected String noDataMsg;
protected String noDataTip;
protected ListAdapter listAdapter;
protected MuzimaListFragment() {
setRetainInstance(true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void setupNoDataView(View formsLayout) {
TextView noDataMsgTextView = (TextView) formsLayout.findViewById(R.id.no_data_msg);
noDataMsgTextView.setText(noDataMsg);
TextView noDataTipTextView = (TextView) formsLayout.findViewById(R.id.no_data_tip);
noDataTipTextView.setText(noDataTip);
noDataMsgTextView.setTypeface(Fonts.roboto_bold_condensed(getActivity()));
noDataTipTextView.setTypeface(Fonts.roboto_light(getActivity()));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reloadData();
}
public void reloadData() {
if(listAdapter != null){
listAdapter.reloadData();
}
}
public void unselectAllItems() {
unselectAllItems(list);
}
public void unselectAllItems(ListView listView) {
if(listView==null){
return;
}
for (int i = listView.getCount() - 1; i >= 0; i--){
listView.setItemChecked(i, false);
}
}
}
| mpl-2.0 |
gemailadam/inspirationi.github.io | comments.php | 41 | comments.php
The comments template. | mpl-2.0 |
Altrusoft/docserv | app/se/altrusoft/docserv/models/TemplateModelFactory.java | 967 | package se.altrusoft.docserv.models;
import java.util.Map;
public class TemplateModelFactory {
private Map<String, TemplateModel> templates;
public TemplateModel getTemplateModel(String templateName) {
return templates.get(templateName).getClone();
}
public Map<String, TemplateModel> getTemplates() {
return templates;
}
public void setTemplates(Map<String, TemplateModel> templates) {
this.templates = templates;
}
// public static Optional<TemplateModel> getTemaplateModelN(String name) {
// Class<? extends TemplateModel> clazz = null;
// Optional<TemplateModel> result = Optional.empty();
// try {
// clazz = Class.forName("se.altrusoft.docserv.models." + name).asSubclass(TemplateModel.class);
// result = Optional.of(clazz.newInstance());
// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return result;
// }
}
| mpl-2.0 |
barbocz/zeromq | src/test/java/guide/flcliapi.java | 11163 | package guide;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Poller;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZMsg;
import org.zeromq.ZThread;
import org.zeromq.ZThread.IAttachedRunnable;
// flcliapi class - Freelance Pattern agent class
// Implements the Freelance Protocol at http://rfc.zeromq.org/spec:10
public class flcliapi
{
// If not a single service replies within this time, give up
private static final int GLOBAL_TIMEOUT = 2500;
// PING interval for servers we think are alive
private static final int PING_INTERVAL = 2000; // msecs
// Server considered dead if silent for this long
private static final int SERVER_TTL = 6000; // msecs
// .split API structure
// This API works in two halves, a common pattern for APIs that need to
// run in the background. One half is an frontend object our application
// creates and works with; the other half is a backend "agent" that runs
// in a background thread. The frontend talks to the backend over an
// inproc pipe socket:
// Structure of our frontend class
private ZContext ctx; // Our context wrapper
private Socket pipe; // Pipe through to flcliapi agent
public flcliapi()
{
ctx = new ZContext();
FreelanceAgent agent = new FreelanceAgent();
pipe = ZThread.fork(ctx, agent);
}
public void destroy()
{
ctx.destroy();
}
// .split connect method
// To implement the connect method, the frontend object sends a multipart
// message to the backend agent. The first part is a string "CONNECT", and
// the second part is the endpoint. It waits 100msec for the connection to
// come up, which isn't pretty, but saves us from sending all requests to a
// single server, at startup time:
public void connect(String endpoint)
{
ZMsg msg = new ZMsg();
msg.add("CONNECT");
msg.add(endpoint);
msg.send(pipe);
try {
Thread.sleep(100); // Allow connection to come up
}
catch (InterruptedException e) {
}
}
// .split request method
// To implement the request method, the frontend object sends a message
// to the backend, specifying a command "REQUEST" and the request message:
public ZMsg request(ZMsg request)
{
request.push("REQUEST");
request.send(pipe);
ZMsg reply = ZMsg.recvMsg(pipe);
if (reply != null) {
String status = reply.popString();
if (status.equals("FAILED"))
reply.destroy();
}
return reply;
}
// .split backend agent
// Here we see the backend agent. It runs as an attached thread, talking
// to its parent over a pipe socket. It is a fairly complex piece of work
// so we'll break it down into pieces. First, the agent manages a set of
// servers, using our familiar class approach:
// Simple class for one server we talk to
private static class Server
{
private String endpoint; // Server identity/endpoint
private boolean alive; // 1 if known to be alive
private long pingAt; // Next ping at this time
private long expires; // Expires at this time
protected Server(String endpoint)
{
this.endpoint = endpoint;
alive = false;
pingAt = System.currentTimeMillis() + PING_INTERVAL;
expires = System.currentTimeMillis() + SERVER_TTL;
}
protected void destroy()
{
}
private void ping(Socket socket)
{
if (System.currentTimeMillis() >= pingAt) {
ZMsg ping = new ZMsg();
ping.add(endpoint);
ping.add("PING");
ping.send(socket);
pingAt = System.currentTimeMillis() + PING_INTERVAL;
}
}
private long tickless(long tickless)
{
if (tickless > pingAt)
return pingAt;
return -1;
}
}
// .split backend agent class
// We build the agent as a class that's capable of processing messages
// coming in from its various sockets:
// Simple class for one background agent
private static class Agent
{
private ZContext ctx; // Own context
private Socket pipe; // Socket to talk back to application
private Socket router; // Socket to talk to servers
private Map<String, Server> servers; // Servers we've connected to
private List<Server> actives; // Servers we know are alive
private int sequence; // Number of requests ever sent
private ZMsg request; // Current request if any
private ZMsg reply; // Current reply if any
private long expires; // Timeout for request/reply
protected Agent(ZContext ctx, Socket pipe)
{
this.ctx = ctx;
this.pipe = pipe;
router = ctx.createSocket(ZMQ.ROUTER);
servers = new HashMap<String, Server>();
actives = new ArrayList<Server>();
}
protected void destroy()
{
for (Server server : servers.values())
server.destroy();
}
// .split control messages
// This method processes one message from our frontend class
// (it's going to be CONNECT or REQUEST):
// Callback when we remove server from agent 'servers' hash table
private void controlMessage()
{
ZMsg msg = ZMsg.recvMsg(pipe);
String command = msg.popString();
if (command.equals("CONNECT")) {
String endpoint = msg.popString();
System.out.printf("I: connecting to %s...\n", endpoint);
router.connect(endpoint);
Server server = new Server(endpoint);
servers.put(endpoint, server);
actives.add(server);
server.pingAt = System.currentTimeMillis() + PING_INTERVAL;
server.expires = System.currentTimeMillis() + SERVER_TTL;
}
else if (command.equals("REQUEST")) {
assert (request == null); // Strict request-reply cycle
// Prefix request with getSequence number and empty envelope
String sequenceText = String.format("%d", ++sequence);
msg.push(sequenceText);
// Take ownership of request message
request = msg;
msg = null;
// Request expires after global timeout
expires = System.currentTimeMillis() + GLOBAL_TIMEOUT;
}
if (msg != null)
msg.destroy();
}
// .split router messages
// This method processes one message from a connected
// server:
private void routerMessage()
{
ZMsg reply = ZMsg.recvMsg(router);
// Frame 0 is server that replied
String endpoint = reply.popString();
Server server = servers.get(endpoint);
assert (server != null);
if (!server.alive) {
actives.add(server);
server.alive = true;
}
server.pingAt = System.currentTimeMillis() + PING_INTERVAL;
server.expires = System.currentTimeMillis() + SERVER_TTL;
// Frame 1 may be getSequence number for reply
String sequenceStr = reply.popString();
if (Integer.parseInt(sequenceStr) == sequence) {
reply.push("OK");
reply.send(pipe);
request.destroy();
request = null;
}
else reply.destroy();
}
}
// .split backend agent implementation
// Finally, here's the agent task itself, which polls its two sockets
// and processes incoming messages:
static private class FreelanceAgent implements IAttachedRunnable
{
@Override
public void run(Object[] args, ZContext ctx, Socket pipe)
{
Agent agent = new Agent(ctx, pipe);
Selector selector = ctx.createSelector();
Poller poller = ctx.createPoller(2);
poller.register(agent.pipe, Poller.POLLIN);
poller.register(agent.router, Poller.POLLIN);
while (!Thread.currentThread().isInterrupted()) {
// Calculate tickless timer, up to 1 hour
long tickless = System.currentTimeMillis() + 1000 * 3600;
if (agent.request != null && tickless > agent.expires)
tickless = agent.expires;
for (Server server : agent.servers.values()) {
long newTickless = server.tickless(tickless);
if (newTickless > 0)
tickless = newTickless;
}
int rc = poller.poll(tickless - System.currentTimeMillis());
if (rc == -1)
break; // Context has been shut down
if (poller.pollin(0))
agent.controlMessage();
if (poller.pollin(1))
agent.routerMessage();
// If we're processing a request, dispatch to next server
if (agent.request != null) {
if (System.currentTimeMillis() >= agent.expires) {
// Request expired, kill it
agent.pipe.send("FAILED");
agent.request.destroy();
agent.request = null;
}
else {
// Find server to talk to, remove any expired ones
while (!agent.actives.isEmpty()) {
Server server = agent.actives.get(0);
if (System.currentTimeMillis() >= server.expires) {
agent.actives.remove(0);
server.alive = false;
}
else {
ZMsg request = agent.request.duplicate();
request.push(server.endpoint);
request.send(agent.router);
break;
}
}
}
}
// Disconnect and delete any expired servers
// Send heartbeats to idle servers if needed
for (Server server : agent.servers.values())
server.ping(agent.router);
}
agent.destroy();
}
}
}
| mpl-2.0 |
birryree/servo | tests/unit/stylo/lib.rs | 519 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate app_units;
extern crate cssparser;
extern crate env_logger;
extern crate euclid;
extern crate geckoservo;
extern crate libc;
#[macro_use] extern crate log;
extern crate parking_lot;
extern crate style;
extern crate style_traits;
extern crate url;
mod sanity_checks;
mod servo_function_signatures;
| mpl-2.0 |
CPardi/Doctran | Doctran/Input/Options/OptionListAttribute.cs | 1565 | // <copyright file="OptionListAttribute.cs" company="Christopher Pardi">
// Copyright © 2015 Christopher Pardi
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// </copyright>
namespace Doctran.Input.Options
{
using System;
using System.Linq;
using ParsingElements;
using Utilitys;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class OptionListAttribute : OptionListBaseAttribute, IOptionAttribute
{
public OptionListAttribute(string name, Type initializationType)
: base(initializationType)
{
this.Name = name;
}
public string Name { get; }
public override object InformationToProperty(IInformation information, Type propertyType)
{
var infoV = information as IInformationValue;
if (infoV == null)
{
throw new OptionReaderException(information.Lines.First().Number, information.Lines.Last().Number, $"'{information.Name}' can only be a value type and not a group.");
}
try
{
return infoV.Value.Trim().ToIConvertable(propertyType);
}
catch (FormatException e)
{
throw new OptionReaderException(information.Lines.First().Number, information.Lines.Last().Number, e.Message);
}
}
}
} | mpl-2.0 |
SerhiyPetrosyuk/Github-Repository-Viewer | app/src/androidTest/java/com/mlsdev/serhiy/githubviewer/ApplicationTest.java | 361 | package com.mlsdev.serhiy.githubviewer;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mpl-2.0 |
santoshphilip/pyclearsky | original_code/csvstuff.py | 1613 | # Copyright (c) 2013 Santosh Philip
# =======================================================================
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# =======================================================================
import csv
txt = open('b.csv', 'r').read()
lines = txt.splitlines()
rows = [line.split(',') for line in lines]
rows = [[float(cell) for cell in row] for row in rows]
brows = [[row[4], row[6]] for row in rows if row[-1] == 0 and row[-2] == 0]
csv_writer = csv.writer(open('brows.csv', 'w')).writerows(brows)
drows = [[row[5], row[7]] for row in rows if row[-1] == 0 and row[-2] == 0]
csv_writer = csv.writer(open('drows.csv', 'w')).writerows(drows)
# b0rows = [row for row in brows if row[0] == 0 and row[1] == 0]
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# b0rows = [row for row in brows if row[0] != 0 and row[1] != 0]
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# b0rows = [row[0] - row[1] for row in brows if row[0] != 0 and row[1] != 0]
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# b0rows = [[row[0] - row[1]] for row in brows if row[0] != 0 and row[1] != 0]
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# b0rows = [row for row in brows if row[0] != 0 and row[1] != 0]
# csv_writer = csv.writer(open('brows.csv', 'w')).writerows(b0rows)
# hist
| mpl-2.0 |
pyoor/octo | lib/logging/console.js | 1790 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var websocket = null
var logger = (function () { // eslint-disable-line no-unused-vars
const sep = '\n/* ### NEXT TESTCASE ############################## */'
const color = {
red: '\u0033[1;31m',
green: '\u0033[1;32m',
clear: '\u0033[0m'
}
if (utils.platform.isWindows) {
color.red = ''
color.green = ''
color.clear = ''
}
function console (msg) {
if (websocket) {
websocket.send(msg)
}
if (typeof window === 'undefined') {
print(msg) // eslint-disable-line no-undef
} else if (window.dump) {
window.dump(msg)
} else if (window.console && window.console.log) {
window.console.log(msg)
} else {
throw new Error('Unable to run console logger.')
}
}
function dump (msg) {
console(msg)
}
function testcase (msg) {
dump('/*L*/ ' + JSON.stringify(msg) + '\n')
}
function dumpln (msg) {
dump(msg + '\n')
}
function error (msg) {
dumpln(color.red + msg + color.clear)
}
function JSError (msg) {
error(comment(msg))
}
function comment (msg) {
return '/* ' + msg + ' */'
}
function separator () {
dumpln(color.green + sep + color.clear)
}
function traceback () {
error('===[ Traceback ]')
try {
throw new Error()
} catch (e) {
dump(e.stack || e.stacktrace || '')
}
error('===')
}
return {
console: console,
dump: dump,
error: error,
JSError: JSError,
dumpln: dumpln,
comment: comment,
testcase: testcase,
separator: separator,
traceback: traceback
}
})()
| mpl-2.0 |
openMF/community-app | app/scripts/controllers/reports/RunReportsController.js | 20571 | (function (module) {
mifosX.controllers = _.extend(module, {
RunReportsController: function (scope, routeParams, resourceFactory, location, dateFilter, http, API_VERSION, $rootScope, $sce, $log) {
scope.isCollapsed = false; //displays options div on startup
scope.hideTable = true; //hides the results div on startup
scope.hidePentahoReport = true; //hides the results div on startup
scope.hideChart = true;
scope.piechart = false;
scope.barchart = false;
scope.formData = {};
scope.reportParams = new Array();
scope.reportDateParams = new Array();
scope.reqFields = new Array();
scope.reportTextParams = new Array();
scope.reportData = {};
scope.reportData.columnHeaders = [];
scope.reportData.data = [];
scope.baseURL = "";
scope.csvData = [];
scope.row = [];
scope.reportName = routeParams.name;
scope.reportType = routeParams.type;
scope.reportId = routeParams.reportId;
scope.pentahoReportParameters = [];
scope.type = "pie";
scope.highlight = function (id) {
var i = document.getElementById(id);
if (i.className == 'selected-row') {
i.className = 'text-pointer';
} else {
i.className = 'selected-row';
}
};
if (scope.reportType == 'Pentaho') {
scope.formData.outputType = 'HTML';
};
resourceFactory.runReportsResource.getReport({reportSource: 'FullParameterList', parameterType: true, R_reportListing: "'" + routeParams.name + "'"}, function (data) {
for (var i in data.data) {
var temp = {
name: data.data[i].row[0],
variable: data.data[i].row[1],
label: data.data[i].row[2],
displayType: data.data[i].row[3],
formatType: data.data[i].row[4],
defaultVal: data.data[i].row[5],
selectOne: data.data[i].row[6],
selectAll: data.data[i].row[7],
parentParameterName: data.data[i].row[8],
inputName: "R_" + data.data[i].row[1] //model name
};
scope.reqFields.push(temp);
if (temp.displayType == 'select' && temp.parentParameterName == null) {
intializeParams(temp, {});
} else if (temp.displayType == 'date') {
scope.reportDateParams.push(temp);
} else if (temp.displayType == 'text') {
scope.reportTextParams.push(temp);
}
}
});
if (scope.reportType == 'Pentaho') {
resourceFactory.reportsResource.get({id: scope.reportId, fields: 'reportParameters'}, function (data) {
scope.pentahoReportParameters = data.reportParameters || [];
});
}
function getSuccuessFunction(paramData) {
var tempDataObj = new Object();
var successFunction = function (data) {
var selectData = [];
var isExistedRecord = false;
for (var i in data.data) {
selectData.push({id: data.data[i].row[0], name: data.data[i].row[1]});
}
for (var j in scope.reportParams) {
if (scope.reportParams[j].name == paramData.name) {
scope.reportParams[j].selectOptions = selectData;
isExistedRecord = true;
}
}
if (!isExistedRecord) {
if(paramData.selectAll == 'Y'){
selectData.push({id: "-1", name: "All"});
}
paramData.selectOptions = selectData;
scope.reportParams.push(paramData);
}
};
return successFunction;
}
function intializeParams(paramData, params) {
scope.errorStatus = undefined;
scope.errorDetails = [];
params.reportSource = paramData.name;
params.parameterType = true;
var successFunction = getSuccuessFunction(paramData);
resourceFactory.runReportsResource.getReport(params, successFunction);
}
scope.getDependencies = function (paramData) {
for (var i = 0; i < scope.reqFields.length; i++) {
var temp = scope.reqFields[i];
if (temp.parentParameterName == paramData.name) {
if (temp.displayType == 'select') {
var parentParamValue = this.formData[paramData.inputName];
if (parentParamValue != undefined) {
eval("var params={};params." + paramData.inputName + "='" + parentParamValue + "';");
intializeParams(temp, params);
}
} else if (temp.displayType == 'date') {
scope.reportDateParams.push(temp);
}
}
}
};
scope.checkStatus = function () {
var collapsed = false;
if (scope.isCollapsed) {
collapsed = true;
}
return collapsed;
};
function invalidDate(checkDate) {
// validates for yyyy-mm-dd returns true if invalid, false is valid
var dateformat = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
if (!(dateformat.test(checkDate))) {
return true;
} else {
var dyear = checkDate.substring(0, 4);
var dmonth = checkDate.substring(5, 7) - 1;
var dday = checkDate.substring(8);
var newDate = new Date(dyear, dmonth, dday);
return !((dday == newDate.getDate()) && (dmonth == newDate.getMonth()) && (dyear == newDate.getFullYear()));
}
}
function removeErrors() {
var $inputs = $(':input');
$inputs.each(function () {
$(this).removeClass("validationerror");
});
}
function parameterValidationErrors() {
var tmpStartDate = "";
var tmpEndDate = "";
scope.errorDetails = [];
for (var i in scope.reqFields) {
var paramDetails = scope.reqFields[i];
switch (paramDetails.displayType) {
case "select":
var selectedVal = scope.formData[paramDetails.inputName];
if (selectedVal == undefined || selectedVal == 0) {
var fieldId = '#' + paramDetails.inputName;
$(fieldId).addClass("validationerror");
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.parameter.required';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
}
break;
case "date":
var tmpDate = scope.formData[paramDetails.inputName];
if (tmpDate == undefined || !(tmpDate > "")) {
var fieldId = '#' + paramDetails.inputName;
$(fieldId).addClass("validationerror");
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.parameter.required';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
}
if (tmpDate && invalidDate(tmpDate) == true) {
var fieldId = '#' + paramDetails.inputName;
$(fieldId).addClass("validationerror");
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.invalid.value.for.parameter';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
}
if (paramDetails.variable == "startDate") tmpStartDate = tmpDate;
if (paramDetails.variable == "endDate") tmpEndDate = tmpDate;
break;
case "text":
var selectedVal = scope.formData[paramDetails.inputName];
if (selectedVal == undefined || selectedVal == 0) {
var fieldId = '#' + paramDetails.inputName;
$(fieldId).addClass("validationerror");
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.parameter.required';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
}
break;
default:
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.parameter.invalid';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
break;
}
}
if (tmpStartDate > "" && tmpEndDate > "") {
if (tmpStartDate > tmpEndDate) {
var errorObj = new Object();
errorObj.field = paramDetails.inputName;
errorObj.code = 'error.message.report.incorrect.values.for.date.fields';
errorObj.args = {params: []};
errorObj.args.params.push({value: paramDetails.label});
scope.errorDetails.push(errorObj);
}
}
}
function buildReportParms() {
var paramCount = 1;
var reportParams = "";
for (var i = 0; i < scope.reqFields.length; i++) {
var reqField = scope.reqFields[i];
for (var j = 0; j < scope.pentahoReportParameters.length; j++) {
var tempParam = scope.pentahoReportParameters[j];
if (reqField.name == tempParam.parameterName) {
var paramName = "R_" + tempParam.reportParameterName;
if (paramCount > 1) reportParams += "&"
reportParams += encodeURIComponent(paramName) + "=" + encodeURIComponent(scope.formData[scope.reqFields[i].inputName]);
paramCount = paramCount + 1;
}
}
}
return reportParams;
}
scope.xFunction = function () {
return function (d) {
return d.key;
};
};
scope.yFunction = function () {
return function (d) {
return d.values;
};
};
scope.setTypePie = function () {
if (scope.type == 'bar') {
scope.type = 'pie';
}
};
scope.setTypeBar = function () {
if (scope.type == 'pie') {
scope.type = 'bar';
}
};
scope.colorFunctionPie = function () {
return function (d, i) {
return colorArrayPie[i];
};
};
scope.isDecimal = function(index){
if(scope.reportData.columnHeaders && scope.reportData.columnHeaders.length > 0){
for(var i=0; i<scope.reportData.columnHeaders.length; i++){
if(scope.reportData.columnHeaders[index].columnType == 'DECIMAL'){
return true;
}
}
}
return false;
};
scope.runReport = function () {
//clear the previous errors
scope.errorDetails = [];
removeErrors();
//update date fields with proper dateformat
for (var i in scope.reportDateParams) {
if (scope.formData[scope.reportDateParams[i].inputName]) {
scope.formData[scope.reportDateParams[i].inputName] = dateFilter(scope.formData[scope.reportDateParams[i].inputName], 'yyyy-MM-dd');
}
}
//Custom validation for report parameters
parameterValidationErrors();
if (scope.errorDetails.length == 0) {
scope.isCollapsed = true;
switch (scope.reportType) {
case "Table":
case "SMS":
scope.hideTable = false;
scope.hidePentahoReport = true;
scope.hideChart = true;
scope.formData.reportSource = scope.reportName;
resourceFactory.runReportsResource.getReport(scope.formData, function (data) {
//clear the csvData array for each request
scope.csvData = [];
scope.reportData.columnHeaders = data.columnHeaders;
scope.reportData.data = data.data;
for (var i in data.columnHeaders) {
scope.row.push(data.columnHeaders[i].columnName);
}
scope.csvData.push(scope.row);
for (var k in data.data) {
scope.csvData.push(data.data[k].row);
}
});
break;
case "Pentaho":
scope.hideTable = true;
scope.hidePentahoReport = false;
scope.hideChart = true;
var reportURL = $rootScope.hostUrl + API_VERSION + "/runreports/" + encodeURIComponent(scope.reportName);
reportURL += "?output-type=" + encodeURIComponent(scope.formData.outputType) + "&tenantIdentifier=" + $rootScope.tenantIdentifier + "&locale=" + scope.optlang.code + "&dateFormat=" + scope.df;
var inQueryParameters = buildReportParms();
if (inQueryParameters > "") reportURL += "&" + inQueryParameters;
// Allow untrusted urls for the ajax request.
// http://docs.angularjs.org/error/$sce/insecurl
reportURL = $sce.trustAsResourceUrl(reportURL);
reportURL = $sce.valueOf(reportURL);
http.get(reportURL, {responseType: 'arraybuffer'})
.then(function(response) {
let data = response.data;
let status = response.status;
let headers = response.headers;
let config = response.config;
var contentType = headers('Content-Type');
var file = new Blob([data], {type: contentType});
var fileContent = URL.createObjectURL(file);
// Pass the form data to the iframe as a data url.
scope.baseURL = $sce.trustAsResourceUrl(fileContent);
})
.catch(function(error){
$log.error(`Error loading ${scope.reportType} report`);
$log.error(error);
});
break;
case "Chart":
scope.hideTable = true;
scope.hidePentahoReport = true;
scope.hideChart = false;
scope.formData.reportSource = scope.reportName;
resourceFactory.runReportsResource.getReport(scope.formData, function (data) {
scope.reportData.columnHeaders = data.columnHeaders;
scope.reportData.data = data.data;
scope.chartData = [];
scope.barData = [];
var l = data.data.length;
for (var i = 0; i < l; i++) {
scope.row = {};
scope.row.key = data.data[i].row[0];
scope.row.values = data.data[i].row[1];
scope.chartData.push(scope.row);
}
var x = {};
x.key = "summary";
x.values = [];
for (var m = 0; m < l; m++) {
var inner = [data.data[m].row[0], data.data[m].row[1]];
x.values.push(inner);
}
scope.barData.push(x);
});
break;
default:
var errorObj = new Object();
errorObj.field = scope.reportType;
errorObj.code = 'error.message.report.type.is.invalid';
errorObj.args = {params: []};
errorObj.args.params.push({value: scope.reportType});
scope.errorDetails.push(errorObj);
break;
}
}
};
}
});
mifosX.ng.application.controller('RunReportsController', ['$scope', '$routeParams', 'ResourceFactory', '$location', 'dateFilter', '$http', 'API_VERSION', '$rootScope', '$sce', '$log', mifosX.controllers.RunReportsController]).run(function ($log) {
$log.info("RunReportsController initialized");
});
}(mifosX.controllers || {}));
| mpl-2.0 |
adrienlauer/seed | core/src/it/java/org/seedstack/seed/core/fixtures/el/PreEL.java | 711 | /**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.core.fixtures.el;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* EL executed before the annotated method.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PreEL {
/**
* @return expression language
*/
String value();
}
| mpl-2.0 |
burdandrei/nomad | command/agent/config.go | 62408 | package agent
import (
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
sockaddr "github.com/hashicorp/go-sockaddr"
"github.com/hashicorp/go-sockaddr/template"
client "github.com/hashicorp/nomad/client/config"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/hashicorp/nomad/version"
)
// Config is the configuration for the Nomad agent.
//
// time.Duration values have two parts:
// - a string field tagged with an hcl:"foo" and json:"-"
// - a time.Duration field in the same struct and a call to duration
// in config_parse.go ParseConfigFile
//
// All config structs should have an ExtraKeysHCL field to check for
// unexpected keys
type Config struct {
// Region is the region this agent is in. Defaults to global.
Region string `hcl:"region"`
// Datacenter is the datacenter this agent is in. Defaults to dc1
Datacenter string `hcl:"datacenter"`
// NodeName is the name we register as. Defaults to hostname.
NodeName string `hcl:"name"`
// DataDir is the directory to store our state in
DataDir string `hcl:"data_dir"`
// PluginDir is the directory to lookup plugins.
PluginDir string `hcl:"plugin_dir"`
// LogLevel is the level of the logs to put out
LogLevel string `hcl:"log_level"`
// LogJson enables log output in a JSON format
LogJson bool `hcl:"log_json"`
// LogFile enables logging to a file
LogFile string `hcl:"log_file"`
// LogRotateDuration is the time period that logs should be rotated in
LogRotateDuration string `hcl:"log_rotate_duration"`
// LogRotateBytes is the max number of bytes that should be written to a file
LogRotateBytes int `hcl:"log_rotate_bytes"`
// LogRotateMaxFiles is the max number of log files to keep
LogRotateMaxFiles int `hcl:"log_rotate_max_files"`
// BindAddr is the address on which all of nomad's services will
// be bound. If not specified, this defaults to 127.0.0.1.
BindAddr string `hcl:"bind_addr"`
// EnableDebug is used to enable debugging HTTP endpoints
EnableDebug bool `hcl:"enable_debug"`
// Ports is used to control the network ports we bind to.
Ports *Ports `hcl:"ports"`
// Addresses is used to override the network addresses we bind to.
//
// Use normalizedAddrs if you need the host+port to bind to.
Addresses *Addresses `hcl:"addresses"`
// normalizedAddr is set to the Address+Port by normalizeAddrs()
normalizedAddrs *Addresses
// AdvertiseAddrs is used to control the addresses we advertise.
AdvertiseAddrs *AdvertiseAddrs `hcl:"advertise"`
// Client has our client related settings
Client *ClientConfig `hcl:"client"`
// Server has our server related settings
Server *ServerConfig `hcl:"server"`
// ACL has our acl related settings
ACL *ACLConfig `hcl:"acl"`
// Telemetry is used to configure sending telemetry
Telemetry *Telemetry `hcl:"telemetry"`
// LeaveOnInt is used to gracefully leave on the interrupt signal
LeaveOnInt bool `hcl:"leave_on_interrupt"`
// LeaveOnTerm is used to gracefully leave on the terminate signal
LeaveOnTerm bool `hcl:"leave_on_terminate"`
// EnableSyslog is used to enable sending logs to syslog
EnableSyslog bool `hcl:"enable_syslog"`
// SyslogFacility is used to control the syslog facility used.
SyslogFacility string `hcl:"syslog_facility"`
// DisableUpdateCheck is used to disable the periodic update
// and security bulletin checking.
DisableUpdateCheck *bool `hcl:"disable_update_check"`
// DisableAnonymousSignature is used to disable setting the
// anonymous signature when doing the update check and looking
// for security bulletins
DisableAnonymousSignature bool `hcl:"disable_anonymous_signature"`
// Consul contains the configuration for the Consul Agent and
// parameters necessary to register services, their checks, and
// discover the current Nomad servers.
Consul *config.ConsulConfig `hcl:"consul"`
// Vault contains the configuration for the Vault Agent and
// parameters necessary to derive tokens.
Vault *config.VaultConfig `hcl:"vault"`
// NomadConfig is used to override the default config.
// This is largely used for testing purposes.
NomadConfig *nomad.Config `hcl:"-" json:"-"`
// ClientConfig is used to override the default config.
// This is largely used for testing purposes.
ClientConfig *client.Config `hcl:"-" json:"-"`
// DevMode is set by the -dev CLI flag.
DevMode bool `hcl:"-"`
// Version information is set at compilation time
Version *version.VersionInfo
// List of config files that have been loaded (in order)
Files []string `hcl:"-"`
// TLSConfig provides TLS related configuration for the Nomad server and
// client
TLSConfig *config.TLSConfig `hcl:"tls"`
// HTTPAPIResponseHeaders allows users to configure the Nomad http agent to
// set arbitrary headers on API responses
HTTPAPIResponseHeaders map[string]string `hcl:"http_api_response_headers"`
// Sentinel holds sentinel related settings
Sentinel *config.SentinelConfig `hcl:"sentinel"`
// Autopilot contains the configuration for Autopilot behavior.
Autopilot *config.AutopilotConfig `hcl:"autopilot"`
// Plugins is the set of configured plugins
Plugins []*config.PluginConfig `hcl:"plugin"`
// Limits contains the configuration for timeouts.
Limits config.Limits `hcl:"limits"`
// Audit contains the configuration for audit logging.
Audit *config.AuditConfig `hcl:"audit"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// ClientConfig is configuration specific to the client mode
type ClientConfig struct {
// Enabled controls if we are a client
Enabled bool `hcl:"enabled"`
// StateDir is the state directory
StateDir string `hcl:"state_dir"`
// AllocDir is the directory for storing allocation data
AllocDir string `hcl:"alloc_dir"`
// Servers is a list of known server addresses. These are as "host:port"
Servers []string `hcl:"servers"`
// NodeClass is used to group the node by class
NodeClass string `hcl:"node_class"`
// Options is used for configuration of nomad internals,
// like fingerprinters and drivers. The format is:
//
// namespace.option = value
Options map[string]string `hcl:"options"`
// Metadata associated with the node
Meta map[string]string `hcl:"meta"`
// A mapping of directories on the host OS to attempt to embed inside each
// task's chroot.
ChrootEnv map[string]string `hcl:"chroot_env"`
// Interface to use for network fingerprinting
NetworkInterface string `hcl:"network_interface"`
// NetworkSpeed is used to override any detected or default network link
// speed.
NetworkSpeed int `hcl:"network_speed"`
// CpuCompute is used to override any detected or default total CPU compute.
CpuCompute int `hcl:"cpu_total_compute"`
// MemoryMB is used to override any detected or default total memory.
MemoryMB int `hcl:"memory_total_mb"`
// ReservableCores is used to override detected reservable cpu cores.
ReserveableCores string `hcl:"reservable_cores"`
// MaxKillTimeout allows capping the user-specifiable KillTimeout.
MaxKillTimeout string `hcl:"max_kill_timeout"`
// ClientMaxPort is the upper range of the ports that the client uses for
// communicating with plugin subsystems
ClientMaxPort int `hcl:"client_max_port"`
// ClientMinPort is the lower range of the ports that the client uses for
// communicating with plugin subsystems
ClientMinPort int `hcl:"client_min_port"`
// Reserved is used to reserve resources from being used by Nomad. This can
// be used to target a certain utilization or to prevent Nomad from using a
// particular set of ports.
Reserved *Resources `hcl:"reserved"`
// GCInterval is the time interval at which the client triggers garbage
// collection
GCInterval time.Duration
GCIntervalHCL string `hcl:"gc_interval" json:"-"`
// GCParallelDestroys is the number of parallel destroys the garbage
// collector will allow.
GCParallelDestroys int `hcl:"gc_parallel_destroys"`
// GCDiskUsageThreshold is the disk usage threshold given as a percent
// beyond which the Nomad client triggers GC of terminal allocations
GCDiskUsageThreshold float64 `hcl:"gc_disk_usage_threshold"`
// GCInodeUsageThreshold is the inode usage threshold beyond which the Nomad
// client triggers GC of the terminal allocations
GCInodeUsageThreshold float64 `hcl:"gc_inode_usage_threshold"`
// GCMaxAllocs is the maximum number of allocations a node can have
// before garbage collection is triggered.
GCMaxAllocs int `hcl:"gc_max_allocs"`
// NoHostUUID disables using the host's UUID and will force generation of a
// random UUID.
NoHostUUID *bool `hcl:"no_host_uuid"`
// DisableRemoteExec disables remote exec targeting tasks on this client
DisableRemoteExec bool `hcl:"disable_remote_exec"`
// TemplateConfig includes configuration for template rendering
TemplateConfig *ClientTemplateConfig `hcl:"template"`
// ServerJoin contains information that is used to attempt to join servers
ServerJoin *ServerJoin `hcl:"server_join"`
// HostVolumes contains information about the volumes an operator has made
// available to jobs running on this node.
HostVolumes []*structs.ClientHostVolumeConfig `hcl:"host_volume"`
// CNIPath is the path to search for CNI plugins, multiple paths can be
// specified colon delimited
CNIPath string `hcl:"cni_path"`
// CNIConfigDir is the directory where CNI network configuration is located. The
// client will use this path when fingerprinting CNI networks.
CNIConfigDir string `hcl:"cni_config_dir"`
// BridgeNetworkName is the name of the bridge to create when using the
// bridge network mode
BridgeNetworkName string `hcl:"bridge_network_name"`
// BridgeNetworkSubnet is the subnet to allocate IP addresses from when
// creating allocations with bridge networking mode. This range is local to
// the host
BridgeNetworkSubnet string `hcl:"bridge_network_subnet"`
// HostNetworks describes the different host networks available to the host
// if the host uses multiple interfaces
HostNetworks []*structs.ClientHostNetworkConfig `hcl:"host_network"`
// BindWildcardDefaultHostNetwork toggles if when there are no host networks,
// should the port mapping rules match the default network address (false) or
// matching any destination address (true). Defaults to true
BindWildcardDefaultHostNetwork bool `hcl:"bind_wildcard_default_host_network"`
// CgroupParent sets the parent cgroup for subsystems managed by Nomad. If the cgroup
// doest not exist Nomad will attempt to create it during startup. Defaults to '/nomad'
CgroupParent string `hcl:"cgroup_parent"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// ClientTemplateConfig is configuration on the client specific to template
// rendering
type ClientTemplateConfig struct {
// FunctionDenylist disables functions in consul-template that
// are unsafe because they expose information from the client host.
FunctionDenylist []string `hcl:"function_denylist"`
// Deprecated: COMPAT(1.0) consul-template uses inclusive language from
// v0.25.0 - function_blacklist is kept for compatibility
FunctionBlacklist []string `hcl:"function_blacklist"`
// DisableSandbox allows templates to access arbitrary files on the
// client host. By default templates can access files only within
// the task directory.
DisableSandbox bool `hcl:"disable_file_sandbox"`
}
// ACLConfig is configuration specific to the ACL system
type ACLConfig struct {
// Enabled controls if we are enforce and manage ACLs
Enabled bool `hcl:"enabled"`
// TokenTTL controls how long we cache ACL tokens. This controls
// how stale they can be when we are enforcing policies. Defaults
// to "30s". Reducing this impacts performance by forcing more
// frequent resolution.
TokenTTL time.Duration
TokenTTLHCL string `hcl:"token_ttl" json:"-"`
// PolicyTTL controls how long we cache ACL policies. This controls
// how stale they can be when we are enforcing policies. Defaults
// to "30s". Reducing this impacts performance by forcing more
// frequent resolution.
PolicyTTL time.Duration
PolicyTTLHCL string `hcl:"policy_ttl" json:"-"`
// ReplicationToken is used by servers to replicate tokens and policies
// from the authoritative region. This must be a valid management token
// within the authoritative region.
ReplicationToken string `hcl:"replication_token"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// ServerConfig is configuration specific to the server mode
type ServerConfig struct {
// Enabled controls if we are a server
Enabled bool `hcl:"enabled"`
// AuthoritativeRegion is used to control which region is treated as
// the source of truth for global tokens and ACL policies.
AuthoritativeRegion string `hcl:"authoritative_region"`
// BootstrapExpect tries to automatically bootstrap the Consul cluster,
// by withholding peers until enough servers join.
BootstrapExpect int `hcl:"bootstrap_expect"`
// DataDir is the directory to store our state in
DataDir string `hcl:"data_dir"`
// ProtocolVersion is the protocol version to speak. This must be between
// ProtocolVersionMin and ProtocolVersionMax.
ProtocolVersion int `hcl:"protocol_version"`
// RaftProtocol is the Raft protocol version to speak. This must be from [1-3].
RaftProtocol int `hcl:"raft_protocol"`
// RaftMultiplier scales the Raft timing parameters
RaftMultiplier *int `hcl:"raft_multiplier"`
// NumSchedulers is the number of scheduler thread that are run.
// This can be as many as one per core, or zero to disable this server
// from doing any scheduling work.
NumSchedulers *int `hcl:"num_schedulers"`
// EnabledSchedulers controls the set of sub-schedulers that are
// enabled for this server to handle. This will restrict the evaluations
// that the workers dequeue for processing.
EnabledSchedulers []string `hcl:"enabled_schedulers"`
// NodeGCThreshold controls how "old" a node must be to be collected by GC.
// Age is not the only requirement for a node to be GCed but the threshold
// can be used to filter by age.
NodeGCThreshold string `hcl:"node_gc_threshold"`
// JobGCInterval controls how often we dispatch a job to GC jobs that are
// available for garbage collection.
JobGCInterval string `hcl:"job_gc_interval"`
// JobGCThreshold controls how "old" a job must be to be collected by GC.
// Age is not the only requirement for a Job to be GCed but the threshold
// can be used to filter by age.
JobGCThreshold string `hcl:"job_gc_threshold"`
// EvalGCThreshold controls how "old" an eval must be to be collected by GC.
// Age is not the only requirement for a eval to be GCed but the threshold
// can be used to filter by age.
EvalGCThreshold string `hcl:"eval_gc_threshold"`
// DeploymentGCThreshold controls how "old" a deployment must be to be
// collected by GC. Age is not the only requirement for a deployment to be
// GCed but the threshold can be used to filter by age.
DeploymentGCThreshold string `hcl:"deployment_gc_threshold"`
// CSIVolumeClaimGCThreshold controls how "old" a CSI volume must be to
// have its claims collected by GC. Age is not the only requirement for
// a volume to be GCed but the threshold can be used to filter by age.
CSIVolumeClaimGCThreshold string `hcl:"csi_volume_claim_gc_threshold"`
// CSIPluginGCThreshold controls how "old" a CSI plugin must be to be
// collected by GC. Age is not the only requirement for a plugin to be
// GCed but the threshold can be used to filter by age.
CSIPluginGCThreshold string `hcl:"csi_plugin_gc_threshold"`
// HeartbeatGrace is the grace period beyond the TTL to account for network,
// processing delays and clock skew before marking a node as "down".
HeartbeatGrace time.Duration
HeartbeatGraceHCL string `hcl:"heartbeat_grace" json:"-"`
// MinHeartbeatTTL is the minimum time between heartbeats. This is used as
// a floor to prevent excessive updates.
MinHeartbeatTTL time.Duration
MinHeartbeatTTLHCL string `hcl:"min_heartbeat_ttl" json:"-"`
// MaxHeartbeatsPerSecond is the maximum target rate of heartbeats
// being processed per second. This allows the TTL to be increased
// to meet the target rate.
MaxHeartbeatsPerSecond float64 `hcl:"max_heartbeats_per_second"`
// StartJoin is a list of addresses to attempt to join when the
// agent starts. If Serf is unable to communicate with any of these
// addresses, then the agent will error and exit.
// Deprecated in Nomad 0.10
StartJoin []string `hcl:"start_join"`
// RetryJoin is a list of addresses to join with retry enabled.
// Deprecated in Nomad 0.10
RetryJoin []string `hcl:"retry_join"`
// RetryMaxAttempts specifies the maximum number of times to retry joining a
// host on startup. This is useful for cases where we know the node will be
// online eventually.
// Deprecated in Nomad 0.10
RetryMaxAttempts int `hcl:"retry_max"`
// RetryInterval specifies the amount of time to wait in between join
// attempts on agent start. The minimum allowed value is 1 second and
// the default is 30s.
// Deprecated in Nomad 0.10
RetryInterval time.Duration
RetryIntervalHCL string `hcl:"retry_interval" json:"-"`
// RejoinAfterLeave controls our interaction with the cluster after leave.
// When set to false (default), a leave causes Consul to not rejoin
// the cluster until an explicit join is received. If this is set to
// true, we ignore the leave, and rejoin the cluster on start.
RejoinAfterLeave bool `hcl:"rejoin_after_leave"`
// (Enterprise-only) NonVotingServer is whether this server will act as a
// non-voting member of the cluster to help provide read scalability.
NonVotingServer bool `hcl:"non_voting_server"`
// (Enterprise-only) RedundancyZone is the redundancy zone to use for this server.
RedundancyZone string `hcl:"redundancy_zone"`
// (Enterprise-only) UpgradeVersion is the custom upgrade version to use when
// performing upgrade migrations.
UpgradeVersion string `hcl:"upgrade_version"`
// Encryption key to use for the Serf communication
EncryptKey string `hcl:"encrypt" json:"-"`
// ServerJoin contains information that is used to attempt to join servers
ServerJoin *ServerJoin `hcl:"server_join"`
// DefaultSchedulerConfig configures the initial scheduler config to be persisted in Raft.
// Once the cluster is bootstrapped, and Raft persists the config (from here or through API),
// This value is ignored.
DefaultSchedulerConfig *structs.SchedulerConfiguration `hcl:"default_scheduler_config"`
// EnableEventBroker configures whether this server's state store
// will generate events for its event stream.
EnableEventBroker *bool `hcl:"enable_event_broker"`
// EventBufferSize configure the amount of events to be held in memory.
// If EnableEventBroker is set to true, the minimum allowable value
// for the EventBufferSize is 1.
EventBufferSize *int `hcl:"event_buffer_size"`
// LicensePath is the path to search for an enterprise license.
LicensePath string `hcl:"license_path"`
// LicenseEnv is the full enterprise license. If NOMAD_LICENSE
// is set, LicenseEnv will be set to the value at startup.
LicenseEnv string
// licenseAdditionalPublicKeys is an internal-only field used to
// setup test licenses.
licenseAdditionalPublicKeys []string
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
Search *Search `hcl:"search"`
// DeploymentQueryRateLimit is in queries per second and is used by the
// DeploymentWatcher to throttle the amount of simultaneously deployments
DeploymentQueryRateLimit float64 `hcl:"deploy_query_rate_limit"`
}
// Search is used in servers to configure search API options.
type Search struct {
// FuzzyEnabled toggles whether the FuzzySearch API is enabled. If not
// enabled, requests to /v1/search/fuzzy will reply with a 404 response code.
//
// Default: enabled.
FuzzyEnabled bool `hcl:"fuzzy_enabled"`
// LimitQuery limits the number of objects searched in the FuzzySearch API.
// The results are indicated as truncated if the limit is reached.
//
// Lowering this value can reduce resource consumption of Nomad server when
// the FuzzySearch API is enabled.
//
// Default value: 20.
LimitQuery int `hcl:"limit_query"`
// LimitResults limits the number of results provided by the FuzzySearch API.
// The results are indicated as truncate if the limit is reached.
//
// Lowering this value can reduce resource consumption of Nomad server per
// fuzzy search request when the FuzzySearch API is enabled.
//
// Default value: 100.
LimitResults int `hcl:"limit_results"`
// MinTermLength is the minimum length of Text required before the FuzzySearch
// API will return results.
//
// Increasing this value can avoid resource consumption on Nomad server by
// reducing searches with less meaningful results.
//
// Default value: 2.
MinTermLength int `hcl:"min_term_length"`
}
// ServerJoin is used in both clients and servers to bootstrap connections to
// servers
type ServerJoin struct {
// StartJoin is a list of addresses to attempt to join when the
// agent starts. If Serf is unable to communicate with any of these
// addresses, then the agent will error and exit.
StartJoin []string `hcl:"start_join"`
// RetryJoin is a list of addresses to join with retry enabled, or a single
// value to find multiple servers using go-discover syntax.
RetryJoin []string `hcl:"retry_join"`
// RetryMaxAttempts specifies the maximum number of times to retry joining a
// host on startup. This is useful for cases where we know the node will be
// online eventually.
RetryMaxAttempts int `hcl:"retry_max"`
// RetryInterval specifies the amount of time to wait in between join
// attempts on agent start. The minimum allowed value is 1 second and
// the default is 30s.
RetryInterval time.Duration
RetryIntervalHCL string `hcl:"retry_interval" json:"-"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
func (s *ServerJoin) Merge(b *ServerJoin) *ServerJoin {
if s == nil {
return b
}
result := *s
if b == nil {
return &result
}
if len(b.StartJoin) != 0 {
result.StartJoin = b.StartJoin
}
if len(b.RetryJoin) != 0 {
result.RetryJoin = b.RetryJoin
}
if b.RetryMaxAttempts != 0 {
result.RetryMaxAttempts = b.RetryMaxAttempts
}
if b.RetryInterval != 0 {
result.RetryInterval = b.RetryInterval
}
return &result
}
// EncryptBytes returns the encryption key configured.
func (s *ServerConfig) EncryptBytes() ([]byte, error) {
return base64.StdEncoding.DecodeString(s.EncryptKey)
}
// Telemetry is the telemetry configuration for the server
type Telemetry struct {
StatsiteAddr string `hcl:"statsite_address"`
StatsdAddr string `hcl:"statsd_address"`
DataDogAddr string `hcl:"datadog_address"`
DataDogTags []string `hcl:"datadog_tags"`
PrometheusMetrics bool `hcl:"prometheus_metrics"`
DisableHostname bool `hcl:"disable_hostname"`
UseNodeName bool `hcl:"use_node_name"`
CollectionInterval string `hcl:"collection_interval"`
collectionInterval time.Duration `hcl:"-"`
PublishAllocationMetrics bool `hcl:"publish_allocation_metrics"`
PublishNodeMetrics bool `hcl:"publish_node_metrics"`
// PrefixFilter allows for filtering out metrics from being collected
PrefixFilter []string `hcl:"prefix_filter"`
// FilterDefault controls whether to allow metrics that have not been specified
// by the filter
FilterDefault *bool `hcl:"filter_default"`
// DisableDispatchedJobSummaryMetrics allows ignoring dispatched jobs when
// publishing Job summary metrics. This is useful in environments that produce
// high numbers of single count dispatch jobs as the metrics for each take up
// a small memory overhead.
DisableDispatchedJobSummaryMetrics bool `hcl:"disable_dispatched_job_summary_metrics"`
// Circonus: see https://github.com/circonus-labs/circonus-gometrics
// for more details on the various configuration options.
// Valid configuration combinations:
// - CirconusAPIToken
// metric management enabled (search for existing check or create a new one)
// - CirconusSubmissionUrl
// metric management disabled (use check with specified submission_url,
// broker must be using a public SSL certificate)
// - CirconusAPIToken + CirconusCheckSubmissionURL
// metric management enabled (use check with specified submission_url)
// - CirconusAPIToken + CirconusCheckID
// metric management enabled (use check with specified id)
// CirconusAPIToken is a valid API Token used to create/manage check. If provided,
// metric management is enabled.
// Default: none
CirconusAPIToken string `hcl:"circonus_api_token"`
// CirconusAPIApp is an app name associated with API token.
// Default: "nomad"
CirconusAPIApp string `hcl:"circonus_api_app"`
// CirconusAPIURL is the base URL to use for contacting the Circonus API.
// Default: "https://api.circonus.com/v2"
CirconusAPIURL string `hcl:"circonus_api_url"`
// CirconusSubmissionInterval is the interval at which metrics are submitted to Circonus.
// Default: 10s
CirconusSubmissionInterval string `hcl:"circonus_submission_interval"`
// CirconusCheckSubmissionURL is the check.config.submission_url field from a
// previously created HTTPTRAP check.
// Default: none
CirconusCheckSubmissionURL string `hcl:"circonus_submission_url"`
// CirconusCheckID is the check id (not check bundle id) from a previously created
// HTTPTRAP check. The numeric portion of the check._cid field.
// Default: none
CirconusCheckID string `hcl:"circonus_check_id"`
// CirconusCheckForceMetricActivation will force enabling metrics, as they are encountered,
// if the metric already exists and is NOT active. If check management is enabled, the default
// behavior is to add new metrics as they are encountered. If the metric already exists in the
// check, it will *NOT* be activated. This setting overrides that behavior.
// Default: "false"
CirconusCheckForceMetricActivation string `hcl:"circonus_check_force_metric_activation"`
// CirconusCheckInstanceID serves to uniquely identify the metrics coming from this "instance".
// It can be used to maintain metric continuity with transient or ephemeral instances as
// they move around within an infrastructure.
// Default: hostname:app
CirconusCheckInstanceID string `hcl:"circonus_check_instance_id"`
// CirconusCheckSearchTag is a special tag which, when coupled with the instance id, helps to
// narrow down the search results when neither a Submission URL or Check ID is provided.
// Default: service:app (e.g. service:nomad)
CirconusCheckSearchTag string `hcl:"circonus_check_search_tag"`
// CirconusCheckTags is a comma separated list of tags to apply to the check. Note that
// the value of CirconusCheckSearchTag will always be added to the check.
// Default: none
CirconusCheckTags string `hcl:"circonus_check_tags"`
// CirconusCheckDisplayName is the name for the check which will be displayed in the Circonus UI.
// Default: value of CirconusCheckInstanceID
CirconusCheckDisplayName string `hcl:"circonus_check_display_name"`
// CirconusBrokerID is an explicit broker to use when creating a new check. The numeric portion
// of broker._cid. If metric management is enabled and neither a Submission URL nor Check ID
// is provided, an attempt will be made to search for an existing check using Instance ID and
// Search Tag. If one is not found, a new HTTPTRAP check will be created.
// Default: use Select Tag if provided, otherwise, a random Enterprise Broker associated
// with the specified API token or the default Circonus Broker.
// Default: none
CirconusBrokerID string `hcl:"circonus_broker_id"`
// CirconusBrokerSelectTag is a special tag which will be used to select a broker when
// a Broker ID is not provided. The best use of this is to as a hint for which broker
// should be used based on *where* this particular instance is running.
// (e.g. a specific geo location or datacenter, dc:sfo)
// Default: none
CirconusBrokerSelectTag string `hcl:"circonus_broker_select_tag"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// PrefixFilters parses the PrefixFilter field and returns a list of allowed and blocked filters
func (t *Telemetry) PrefixFilters() (allowed, blocked []string, err error) {
for _, rule := range t.PrefixFilter {
if rule == "" {
continue
}
switch rule[0] {
case '+':
allowed = append(allowed, rule[1:])
case '-':
blocked = append(blocked, rule[1:])
default:
return nil, nil, fmt.Errorf("Filter rule must begin with either '+' or '-': %q", rule)
}
}
return allowed, blocked, nil
}
// Ports encapsulates the various ports we bind to for network services. If any
// are not specified then the defaults are used instead.
type Ports struct {
HTTP int `hcl:"http"`
RPC int `hcl:"rpc"`
Serf int `hcl:"serf"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// Addresses encapsulates all of the addresses we bind to for various
// network services. Everything is optional and defaults to BindAddr.
type Addresses struct {
HTTP string `hcl:"http"`
RPC string `hcl:"rpc"`
Serf string `hcl:"serf"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// AdvertiseAddrs is used to control the addresses we advertise out for
// different network services. All are optional and default to BindAddr and
// their default Port.
type AdvertiseAddrs struct {
HTTP string `hcl:"http"`
RPC string `hcl:"rpc"`
Serf string `hcl:"serf"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
type Resources struct {
CPU int `hcl:"cpu"`
MemoryMB int `hcl:"memory"`
DiskMB int `hcl:"disk"`
ReservedPorts string `hcl:"reserved_ports"`
Cores string `hcl:"cores"`
// ExtraKeysHCL is used by hcl to surface unexpected keys
ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
}
// devModeConfig holds the config for the -dev and -dev-connect flags
type devModeConfig struct {
// mode flags are set at the command line via -dev and -dev-connect
defaultMode bool
connectMode bool
bindAddr string
iface string
}
// newDevModeConfig parses the optional string value of the -dev flag
func newDevModeConfig(devMode, connectMode bool) (*devModeConfig, error) {
if !devMode && !connectMode {
return nil, nil
}
mode := &devModeConfig{}
mode.defaultMode = devMode
if connectMode {
if runtime.GOOS != "linux" {
// strictly speaking -dev-connect only binds to the
// non-localhost interface, but given its purpose
// is to support a feature with network namespaces
// we'll return an error here rather than let the agent
// come up and fail unexpectedly to run jobs
return nil, fmt.Errorf("-dev-connect is only supported on linux.")
}
u, err := user.Current()
if err != nil {
return nil, fmt.Errorf(
"-dev-connect uses network namespaces and is only supported for root: %v", err)
}
if u.Uid != "0" {
return nil, fmt.Errorf(
"-dev-connect uses network namespaces and is only supported for root.")
}
// Ensure Consul is on PATH
if _, err := exec.LookPath("consul"); err != nil {
return nil, fmt.Errorf("-dev-connect requires a 'consul' binary in Nomad's $PATH")
}
mode.connectMode = true
}
err := mode.networkConfig()
if err != nil {
return nil, err
}
return mode, nil
}
func (mode *devModeConfig) networkConfig() error {
if runtime.GOOS == "windows" {
mode.bindAddr = "127.0.0.1"
mode.iface = "Loopback Pseudo-Interface 1"
return nil
}
if runtime.GOOS == "darwin" {
mode.bindAddr = "127.0.0.1"
mode.iface = "lo0"
return nil
}
if mode != nil && mode.connectMode {
// if we hit either of the errors here we're in a weird situation
// where syscalls to get the list of network interfaces are failing.
// rather than throwing errors, we'll fall back to the default.
ifAddrs, err := sockaddr.GetDefaultInterfaces()
errMsg := "-dev=connect uses network namespaces: %v"
if err != nil {
return fmt.Errorf(errMsg, err)
}
if len(ifAddrs) < 1 {
return fmt.Errorf(errMsg, "could not find public network interface")
}
iface := ifAddrs[0].Name
mode.iface = iface
mode.bindAddr = "0.0.0.0" // allows CLI to "just work"
return nil
}
mode.bindAddr = "127.0.0.1"
mode.iface = "lo"
return nil
}
// DevConfig is a Config that is used for dev mode of Nomad.
func DevConfig(mode *devModeConfig) *Config {
if mode == nil {
mode = &devModeConfig{defaultMode: true}
mode.networkConfig()
}
conf := DefaultConfig()
conf.BindAddr = mode.bindAddr
conf.LogLevel = "DEBUG"
conf.Client.Enabled = true
conf.Server.Enabled = true
conf.DevMode = true
conf.Server.BootstrapExpect = 1
conf.EnableDebug = true
conf.DisableAnonymousSignature = true
conf.Consul.AutoAdvertise = helper.BoolToPtr(true)
conf.Client.NetworkInterface = mode.iface
conf.Client.Options = map[string]string{
"driver.raw_exec.enable": "true",
"driver.docker.volumes": "true",
}
conf.Client.GCInterval = 10 * time.Minute
conf.Client.GCDiskUsageThreshold = 99
conf.Client.GCInodeUsageThreshold = 99
conf.Client.GCMaxAllocs = 50
conf.Client.TemplateConfig = &ClientTemplateConfig{
FunctionDenylist: []string{"plugin"},
DisableSandbox: false,
}
conf.Client.BindWildcardDefaultHostNetwork = true
conf.Telemetry.PrometheusMetrics = true
conf.Telemetry.PublishAllocationMetrics = true
conf.Telemetry.PublishNodeMetrics = true
return conf
}
// DefaultConfig is a the baseline configuration for Nomad
func DefaultConfig() *Config {
return &Config{
LogLevel: "INFO",
Region: "global",
Datacenter: "dc1",
BindAddr: "0.0.0.0",
Ports: &Ports{
HTTP: 4646,
RPC: 4647,
Serf: 4648,
},
Addresses: &Addresses{},
AdvertiseAddrs: &AdvertiseAddrs{},
Consul: config.DefaultConsulConfig(),
Vault: config.DefaultVaultConfig(),
Client: &ClientConfig{
Enabled: false,
MaxKillTimeout: "30s",
ClientMinPort: 14000,
ClientMaxPort: 14512,
Reserved: &Resources{},
GCInterval: 1 * time.Minute,
GCParallelDestroys: 2,
GCDiskUsageThreshold: 80,
GCInodeUsageThreshold: 70,
GCMaxAllocs: 50,
NoHostUUID: helper.BoolToPtr(true),
DisableRemoteExec: false,
ServerJoin: &ServerJoin{
RetryJoin: []string{},
RetryInterval: 30 * time.Second,
RetryMaxAttempts: 0,
},
TemplateConfig: &ClientTemplateConfig{
FunctionDenylist: []string{"plugin"},
DisableSandbox: false,
},
BindWildcardDefaultHostNetwork: true,
},
Server: &ServerConfig{
Enabled: false,
EnableEventBroker: helper.BoolToPtr(true),
EventBufferSize: helper.IntToPtr(100),
StartJoin: []string{},
ServerJoin: &ServerJoin{
RetryJoin: []string{},
RetryInterval: 30 * time.Second,
RetryMaxAttempts: 0,
},
Search: &Search{
FuzzyEnabled: true,
LimitQuery: 20,
LimitResults: 100,
MinTermLength: 2,
},
},
ACL: &ACLConfig{
Enabled: false,
TokenTTL: 30 * time.Second,
PolicyTTL: 30 * time.Second,
},
SyslogFacility: "LOCAL0",
Telemetry: &Telemetry{
CollectionInterval: "1s",
collectionInterval: 1 * time.Second,
},
TLSConfig: &config.TLSConfig{},
Sentinel: &config.SentinelConfig{},
Version: version.GetVersion(),
Autopilot: config.DefaultAutopilotConfig(),
Audit: &config.AuditConfig{},
DisableUpdateCheck: helper.BoolToPtr(false),
Limits: config.DefaultLimits(),
}
}
// Listener can be used to get a new listener using a custom bind address.
// If the bind provided address is empty, the BindAddr is used instead.
func (c *Config) Listener(proto, addr string, port int) (net.Listener, error) {
if addr == "" {
addr = c.BindAddr
}
// Do our own range check to avoid bugs in package net.
//
// golang.org/issue/11715
// golang.org/issue/13447
//
// Both of the above bugs were fixed by golang.org/cl/12447 which will be
// included in Go 1.6. The error returned below is the same as what Go 1.6
// will return.
if 0 > port || port > 65535 {
return nil, &net.OpError{
Op: "listen",
Net: proto,
Err: &net.AddrError{Err: "invalid port", Addr: fmt.Sprint(port)},
}
}
return net.Listen(proto, net.JoinHostPort(addr, strconv.Itoa(port)))
}
// Merge merges two configurations.
func (c *Config) Merge(b *Config) *Config {
result := *c
if b.Region != "" {
result.Region = b.Region
}
if b.Datacenter != "" {
result.Datacenter = b.Datacenter
}
if b.NodeName != "" {
result.NodeName = b.NodeName
}
if b.DataDir != "" {
result.DataDir = b.DataDir
}
if b.PluginDir != "" {
result.PluginDir = b.PluginDir
}
if b.LogLevel != "" {
result.LogLevel = b.LogLevel
}
if b.LogJson {
result.LogJson = true
}
if b.LogFile != "" {
result.LogFile = b.LogFile
}
if b.LogRotateDuration != "" {
result.LogRotateDuration = b.LogRotateDuration
}
if b.LogRotateBytes != 0 {
result.LogRotateBytes = b.LogRotateBytes
}
if b.LogRotateMaxFiles != 0 {
result.LogRotateMaxFiles = b.LogRotateMaxFiles
}
if b.BindAddr != "" {
result.BindAddr = b.BindAddr
}
if b.EnableDebug {
result.EnableDebug = true
}
if b.LeaveOnInt {
result.LeaveOnInt = true
}
if b.LeaveOnTerm {
result.LeaveOnTerm = true
}
if b.EnableSyslog {
result.EnableSyslog = true
}
if b.SyslogFacility != "" {
result.SyslogFacility = b.SyslogFacility
}
if b.DisableUpdateCheck != nil {
result.DisableUpdateCheck = helper.BoolToPtr(*b.DisableUpdateCheck)
}
if b.DisableAnonymousSignature {
result.DisableAnonymousSignature = true
}
// Apply the telemetry config
if result.Telemetry == nil && b.Telemetry != nil {
telemetry := *b.Telemetry
result.Telemetry = &telemetry
} else if b.Telemetry != nil {
result.Telemetry = result.Telemetry.Merge(b.Telemetry)
}
// Apply the TLS Config
if result.TLSConfig == nil && b.TLSConfig != nil {
result.TLSConfig = b.TLSConfig.Copy()
} else if b.TLSConfig != nil {
result.TLSConfig = result.TLSConfig.Merge(b.TLSConfig)
}
// Apply the client config
if result.Client == nil && b.Client != nil {
client := *b.Client
result.Client = &client
} else if b.Client != nil {
result.Client = result.Client.Merge(b.Client)
}
// Apply the server config
if result.Server == nil && b.Server != nil {
server := *b.Server
result.Server = &server
} else if b.Server != nil {
result.Server = result.Server.Merge(b.Server)
}
// Apply the acl config
if result.ACL == nil && b.ACL != nil {
server := *b.ACL
result.ACL = &server
} else if b.ACL != nil {
result.ACL = result.ACL.Merge(b.ACL)
}
// Apply the Audit config
if result.Audit == nil && b.Audit != nil {
audit := *b.Audit
result.Audit = &audit
} else if b.ACL != nil {
result.Audit = result.Audit.Merge(b.Audit)
}
// Apply the ports config
if result.Ports == nil && b.Ports != nil {
ports := *b.Ports
result.Ports = &ports
} else if b.Ports != nil {
result.Ports = result.Ports.Merge(b.Ports)
}
// Apply the address config
if result.Addresses == nil && b.Addresses != nil {
addrs := *b.Addresses
result.Addresses = &addrs
} else if b.Addresses != nil {
result.Addresses = result.Addresses.Merge(b.Addresses)
}
// Apply the advertise addrs config
if result.AdvertiseAddrs == nil && b.AdvertiseAddrs != nil {
advertise := *b.AdvertiseAddrs
result.AdvertiseAddrs = &advertise
} else if b.AdvertiseAddrs != nil {
result.AdvertiseAddrs = result.AdvertiseAddrs.Merge(b.AdvertiseAddrs)
}
// Apply the Consul Configuration
if result.Consul == nil && b.Consul != nil {
result.Consul = b.Consul.Copy()
} else if b.Consul != nil {
result.Consul = result.Consul.Merge(b.Consul)
}
// Apply the Vault Configuration
if result.Vault == nil && b.Vault != nil {
vaultConfig := *b.Vault
result.Vault = &vaultConfig
} else if b.Vault != nil {
result.Vault = result.Vault.Merge(b.Vault)
}
// Apply the sentinel config
if result.Sentinel == nil && b.Sentinel != nil {
server := *b.Sentinel
result.Sentinel = &server
} else if b.Sentinel != nil {
result.Sentinel = result.Sentinel.Merge(b.Sentinel)
}
if result.Autopilot == nil && b.Autopilot != nil {
autopilot := *b.Autopilot
result.Autopilot = &autopilot
} else if b.Autopilot != nil {
result.Autopilot = result.Autopilot.Merge(b.Autopilot)
}
if len(result.Plugins) == 0 && len(b.Plugins) != 0 {
copy := make([]*config.PluginConfig, len(b.Plugins))
for i, v := range b.Plugins {
copy[i] = v.Copy()
}
result.Plugins = copy
} else if len(b.Plugins) != 0 {
result.Plugins = config.PluginConfigSetMerge(result.Plugins, b.Plugins)
}
// Merge config files lists
result.Files = append(result.Files, b.Files...)
// Add the http API response header map values
if result.HTTPAPIResponseHeaders == nil {
result.HTTPAPIResponseHeaders = make(map[string]string)
}
for k, v := range b.HTTPAPIResponseHeaders {
result.HTTPAPIResponseHeaders[k] = v
}
result.Limits = c.Limits.Merge(b.Limits)
return &result
}
// normalizeAddrs normalizes Addresses and AdvertiseAddrs to always be
// initialized and have reasonable defaults.
func (c *Config) normalizeAddrs() error {
if c.BindAddr != "" {
ipStr, err := parseSingleIPTemplate(c.BindAddr)
if err != nil {
return fmt.Errorf("Bind address resolution failed: %v", err)
}
c.BindAddr = ipStr
}
addr, err := normalizeBind(c.Addresses.HTTP, c.BindAddr)
if err != nil {
return fmt.Errorf("Failed to parse HTTP address: %v", err)
}
c.Addresses.HTTP = addr
addr, err = normalizeBind(c.Addresses.RPC, c.BindAddr)
if err != nil {
return fmt.Errorf("Failed to parse RPC address: %v", err)
}
c.Addresses.RPC = addr
addr, err = normalizeBind(c.Addresses.Serf, c.BindAddr)
if err != nil {
return fmt.Errorf("Failed to parse Serf address: %v", err)
}
c.Addresses.Serf = addr
c.normalizedAddrs = &Addresses{
HTTP: net.JoinHostPort(c.Addresses.HTTP, strconv.Itoa(c.Ports.HTTP)),
RPC: net.JoinHostPort(c.Addresses.RPC, strconv.Itoa(c.Ports.RPC)),
Serf: net.JoinHostPort(c.Addresses.Serf, strconv.Itoa(c.Ports.Serf)),
}
addr, err = normalizeAdvertise(c.AdvertiseAddrs.HTTP, c.Addresses.HTTP, c.Ports.HTTP, c.DevMode)
if err != nil {
return fmt.Errorf("Failed to parse HTTP advertise address (%v, %v, %v, %v): %v", c.AdvertiseAddrs.HTTP, c.Addresses.HTTP, c.Ports.HTTP, c.DevMode, err)
}
c.AdvertiseAddrs.HTTP = addr
addr, err = normalizeAdvertise(c.AdvertiseAddrs.RPC, c.Addresses.RPC, c.Ports.RPC, c.DevMode)
if err != nil {
return fmt.Errorf("Failed to parse RPC advertise address: %v", err)
}
c.AdvertiseAddrs.RPC = addr
// Skip serf if server is disabled
if c.Server != nil && c.Server.Enabled {
addr, err = normalizeAdvertise(c.AdvertiseAddrs.Serf, c.Addresses.Serf, c.Ports.Serf, c.DevMode)
if err != nil {
return fmt.Errorf("Failed to parse Serf advertise address: %v", err)
}
c.AdvertiseAddrs.Serf = addr
}
// Skip network_interface evaluation if not a client
if c.Client != nil && c.Client.Enabled && c.Client.NetworkInterface != "" {
parsed, err := parseSingleInterfaceTemplate(c.Client.NetworkInterface)
if err != nil {
return fmt.Errorf("Failed to parse network-interface: %v", err)
}
c.Client.NetworkInterface = parsed
}
return nil
}
// parseSingleInterfaceTemplate parses a go-sockaddr template and returns an
// error if it doesn't result in a single value.
func parseSingleInterfaceTemplate(tpl string) (string, error) {
out, err := template.Parse(tpl)
if err != nil {
// Typically something like:
// unable to parse template "{{printfl \"en50\"}}": template: sockaddr.Parse:1: function "printfl" not defined
return "", err
}
// Remove any extra empty space around the rendered result and check if the
// result is also not empty if the user provided a template.
out = strings.TrimSpace(out)
if tpl != "" && out == "" {
return "", fmt.Errorf("template %q evaluated to empty result", tpl)
}
// `template.Parse` returns a space-separated list of results, but on
// Windows network interfaces are allowed to have spaces, so there is no
// guaranteed separators that we can use to test if the template returned
// multiple interfaces.
// The test below checks if the template results to a single valid interface.
_, err = net.InterfaceByName(out)
if err != nil {
return "", fmt.Errorf("invalid interface name %q", out)
}
return out, nil
}
// parseSingleIPTemplate is used as a helper function to parse out a single IP
// address from a config parameter.
func parseSingleIPTemplate(ipTmpl string) (string, error) {
out, err := template.Parse(ipTmpl)
if err != nil {
return "", fmt.Errorf("Unable to parse address template %q: %v", ipTmpl, err)
}
ips := strings.Split(out, " ")
switch len(ips) {
case 0:
return "", errors.New("No addresses found, please configure one.")
case 1:
return ips[0], nil
default:
return "", fmt.Errorf("Multiple addresses found (%q), please configure one.", out)
}
}
// normalizeBind returns a normalized bind address.
//
// If addr is set it is used, if not the default bind address is used.
func normalizeBind(addr, bind string) (string, error) {
if addr == "" {
return bind, nil
}
return parseSingleIPTemplate(addr)
}
// normalizeAdvertise returns a normalized advertise address.
//
// If addr is set, it is used and the default port is appended if no port is
// set.
//
// If addr is not set and bind is a valid address, the returned string is the
// bind+port.
//
// If addr is not set and bind is not a valid advertise address, the hostname
// is resolved and returned with the port.
//
// Loopback is only considered a valid advertise address in dev mode.
func normalizeAdvertise(addr string, bind string, defport int, dev bool) (string, error) {
addr, err := parseSingleIPTemplate(addr)
if err != nil {
return "", fmt.Errorf("Error parsing advertise address template: %v", err)
}
if addr != "" {
// Default to using manually configured address
_, _, err = net.SplitHostPort(addr)
if err != nil {
if !isMissingPort(err) && !isTooManyColons(err) {
return "", fmt.Errorf("Error parsing advertise address %q: %v", addr, err)
}
// missing port, append the default
return net.JoinHostPort(addr, strconv.Itoa(defport)), nil
}
return addr, nil
}
// Fallback to bind address first, and then try resolving the local hostname
ips, err := net.LookupIP(bind)
if err != nil {
return "", fmt.Errorf("Error resolving bind address %q: %v", bind, err)
}
// Return the first non-localhost unicast address
for _, ip := range ips {
if ip.IsLinkLocalUnicast() || ip.IsGlobalUnicast() {
return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
}
if ip.IsLoopback() {
if dev {
// loopback is fine for dev mode
return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
}
return "", fmt.Errorf("Defaulting advertise to localhost is unsafe, please set advertise manually")
}
}
// Bind is not localhost but not a valid advertise IP, use first private IP
addr, err = parseSingleIPTemplate("{{ GetPrivateIP }}")
if err != nil {
return "", fmt.Errorf("Unable to parse default advertise address: %v", err)
}
return net.JoinHostPort(addr, strconv.Itoa(defport)), nil
}
// isMissingPort returns true if an error is a "missing port" error from
// net.SplitHostPort.
func isMissingPort(err error) bool {
// matches error const in net/ipsock.go
const missingPort = "missing port in address"
return err != nil && strings.Contains(err.Error(), missingPort)
}
// isTooManyColons returns true if an error is a "too many colons" error from
// net.SplitHostPort.
func isTooManyColons(err error) bool {
// matches error const in net/ipsock.go
const tooManyColons = "too many colons in address"
return err != nil && strings.Contains(err.Error(), tooManyColons)
}
// Merge is used to merge two ACL configs together. The settings from the input always take precedence.
func (a *ACLConfig) Merge(b *ACLConfig) *ACLConfig {
result := *a
if b.Enabled {
result.Enabled = true
}
if b.TokenTTL != 0 {
result.TokenTTL = b.TokenTTL
}
if b.TokenTTLHCL != "" {
result.TokenTTLHCL = b.TokenTTLHCL
}
if b.PolicyTTL != 0 {
result.PolicyTTL = b.PolicyTTL
}
if b.PolicyTTLHCL != "" {
result.PolicyTTLHCL = b.PolicyTTLHCL
}
if b.ReplicationToken != "" {
result.ReplicationToken = b.ReplicationToken
}
return &result
}
// Merge is used to merge two server configs together
func (a *ServerConfig) Merge(b *ServerConfig) *ServerConfig {
result := *a
if b.Enabled {
result.Enabled = true
}
if b.AuthoritativeRegion != "" {
result.AuthoritativeRegion = b.AuthoritativeRegion
}
if b.BootstrapExpect > 0 {
result.BootstrapExpect = b.BootstrapExpect
}
if b.DataDir != "" {
result.DataDir = b.DataDir
}
if b.ProtocolVersion != 0 {
result.ProtocolVersion = b.ProtocolVersion
}
if b.RaftProtocol != 0 {
result.RaftProtocol = b.RaftProtocol
}
if b.RaftMultiplier != nil {
c := *b.RaftMultiplier
result.RaftMultiplier = &c
}
if b.NumSchedulers != nil {
result.NumSchedulers = helper.IntToPtr(*b.NumSchedulers)
}
if b.NodeGCThreshold != "" {
result.NodeGCThreshold = b.NodeGCThreshold
}
if b.JobGCInterval != "" {
result.JobGCInterval = b.JobGCInterval
}
if b.JobGCThreshold != "" {
result.JobGCThreshold = b.JobGCThreshold
}
if b.EvalGCThreshold != "" {
result.EvalGCThreshold = b.EvalGCThreshold
}
if b.DeploymentGCThreshold != "" {
result.DeploymentGCThreshold = b.DeploymentGCThreshold
}
if b.CSIVolumeClaimGCThreshold != "" {
result.CSIVolumeClaimGCThreshold = b.CSIVolumeClaimGCThreshold
}
if b.CSIPluginGCThreshold != "" {
result.CSIPluginGCThreshold = b.CSIPluginGCThreshold
}
if b.HeartbeatGrace != 0 {
result.HeartbeatGrace = b.HeartbeatGrace
}
if b.HeartbeatGraceHCL != "" {
result.HeartbeatGraceHCL = b.HeartbeatGraceHCL
}
if b.MinHeartbeatTTL != 0 {
result.MinHeartbeatTTL = b.MinHeartbeatTTL
}
if b.MinHeartbeatTTLHCL != "" {
result.MinHeartbeatTTLHCL = b.MinHeartbeatTTLHCL
}
if b.MaxHeartbeatsPerSecond != 0.0 {
result.MaxHeartbeatsPerSecond = b.MaxHeartbeatsPerSecond
}
if b.RetryMaxAttempts != 0 {
result.RetryMaxAttempts = b.RetryMaxAttempts
}
if b.RetryInterval != 0 {
result.RetryInterval = b.RetryInterval
}
if b.RetryIntervalHCL != "" {
result.RetryIntervalHCL = b.RetryIntervalHCL
}
if b.RejoinAfterLeave {
result.RejoinAfterLeave = true
}
if b.NonVotingServer {
result.NonVotingServer = true
}
if b.RedundancyZone != "" {
result.RedundancyZone = b.RedundancyZone
}
if b.UpgradeVersion != "" {
result.UpgradeVersion = b.UpgradeVersion
}
if b.EncryptKey != "" {
result.EncryptKey = b.EncryptKey
}
if b.ServerJoin != nil {
result.ServerJoin = result.ServerJoin.Merge(b.ServerJoin)
}
if b.LicensePath != "" {
result.LicensePath = b.LicensePath
}
if b.EnableEventBroker != nil {
result.EnableEventBroker = b.EnableEventBroker
}
if b.EventBufferSize != nil {
result.EventBufferSize = b.EventBufferSize
}
if b.DefaultSchedulerConfig != nil {
c := *b.DefaultSchedulerConfig
result.DefaultSchedulerConfig = &c
}
if b.DeploymentQueryRateLimit != 0 {
result.DeploymentQueryRateLimit = b.DeploymentQueryRateLimit
}
if b.Search != nil {
result.Search = &Search{FuzzyEnabled: b.Search.FuzzyEnabled}
if b.Search.LimitQuery > 0 {
result.Search.LimitQuery = b.Search.LimitQuery
}
if b.Search.LimitResults > 0 {
result.Search.LimitResults = b.Search.LimitResults
}
if b.Search.MinTermLength > 0 {
result.Search.MinTermLength = b.Search.MinTermLength
}
}
// Add the schedulers
result.EnabledSchedulers = append(result.EnabledSchedulers, b.EnabledSchedulers...)
// Copy the start join addresses
result.StartJoin = make([]string, 0, len(a.StartJoin)+len(b.StartJoin))
result.StartJoin = append(result.StartJoin, a.StartJoin...)
result.StartJoin = append(result.StartJoin, b.StartJoin...)
// Copy the retry join addresses
result.RetryJoin = make([]string, 0, len(a.RetryJoin)+len(b.RetryJoin))
result.RetryJoin = append(result.RetryJoin, a.RetryJoin...)
result.RetryJoin = append(result.RetryJoin, b.RetryJoin...)
return &result
}
// Merge is used to merge two client configs together
func (a *ClientConfig) Merge(b *ClientConfig) *ClientConfig {
result := *a
if b.Enabled {
result.Enabled = true
}
if b.StateDir != "" {
result.StateDir = b.StateDir
}
if b.AllocDir != "" {
result.AllocDir = b.AllocDir
}
if b.NodeClass != "" {
result.NodeClass = b.NodeClass
}
if b.NetworkInterface != "" {
result.NetworkInterface = b.NetworkInterface
}
if b.NetworkSpeed != 0 {
result.NetworkSpeed = b.NetworkSpeed
}
if b.CpuCompute != 0 {
result.CpuCompute = b.CpuCompute
}
if b.MemoryMB != 0 {
result.MemoryMB = b.MemoryMB
}
if b.MaxKillTimeout != "" {
result.MaxKillTimeout = b.MaxKillTimeout
}
if b.ClientMaxPort != 0 {
result.ClientMaxPort = b.ClientMaxPort
}
if b.ClientMinPort != 0 {
result.ClientMinPort = b.ClientMinPort
}
if result.Reserved == nil && b.Reserved != nil {
reserved := *b.Reserved
result.Reserved = &reserved
} else if b.Reserved != nil {
result.Reserved = result.Reserved.Merge(b.Reserved)
}
if b.GCInterval != 0 {
result.GCInterval = b.GCInterval
}
if b.GCIntervalHCL != "" {
result.GCIntervalHCL = b.GCIntervalHCL
}
if b.GCParallelDestroys != 0 {
result.GCParallelDestroys = b.GCParallelDestroys
}
if b.GCDiskUsageThreshold != 0 {
result.GCDiskUsageThreshold = b.GCDiskUsageThreshold
}
if b.GCInodeUsageThreshold != 0 {
result.GCInodeUsageThreshold = b.GCInodeUsageThreshold
}
if b.GCMaxAllocs != 0 {
result.GCMaxAllocs = b.GCMaxAllocs
}
// NoHostUUID defaults to true, merge if false
if b.NoHostUUID != nil {
result.NoHostUUID = b.NoHostUUID
}
if b.DisableRemoteExec {
result.DisableRemoteExec = b.DisableRemoteExec
}
if b.TemplateConfig != nil {
result.TemplateConfig = b.TemplateConfig
}
// Add the servers
result.Servers = append(result.Servers, b.Servers...)
// Add the options map values
if result.Options == nil {
result.Options = make(map[string]string)
}
for k, v := range b.Options {
result.Options[k] = v
}
// Add the meta map values
if result.Meta == nil {
result.Meta = make(map[string]string)
}
for k, v := range b.Meta {
result.Meta[k] = v
}
// Add the chroot_env map values
if result.ChrootEnv == nil {
result.ChrootEnv = make(map[string]string)
}
for k, v := range b.ChrootEnv {
result.ChrootEnv[k] = v
}
if b.ServerJoin != nil {
result.ServerJoin = result.ServerJoin.Merge(b.ServerJoin)
}
if len(a.HostVolumes) == 0 && len(b.HostVolumes) != 0 {
result.HostVolumes = structs.CopySliceClientHostVolumeConfig(b.HostVolumes)
} else if len(b.HostVolumes) != 0 {
result.HostVolumes = structs.HostVolumeSliceMerge(a.HostVolumes, b.HostVolumes)
}
if b.CNIPath != "" {
result.CNIPath = b.CNIPath
}
if b.CNIConfigDir != "" {
result.CNIConfigDir = b.CNIConfigDir
}
if b.BridgeNetworkName != "" {
result.BridgeNetworkName = b.BridgeNetworkName
}
if b.BridgeNetworkSubnet != "" {
result.BridgeNetworkSubnet = b.BridgeNetworkSubnet
}
result.HostNetworks = a.HostNetworks
if len(b.HostNetworks) != 0 {
result.HostNetworks = append(result.HostNetworks, b.HostNetworks...)
}
if b.BindWildcardDefaultHostNetwork {
result.BindWildcardDefaultHostNetwork = true
}
return &result
}
// Merge is used to merge two telemetry configs together
func (a *Telemetry) Merge(b *Telemetry) *Telemetry {
result := *a
if b.StatsiteAddr != "" {
result.StatsiteAddr = b.StatsiteAddr
}
if b.StatsdAddr != "" {
result.StatsdAddr = b.StatsdAddr
}
if b.DataDogAddr != "" {
result.DataDogAddr = b.DataDogAddr
}
if b.DataDogTags != nil {
result.DataDogTags = b.DataDogTags
}
if b.PrometheusMetrics {
result.PrometheusMetrics = b.PrometheusMetrics
}
if b.DisableHostname {
result.DisableHostname = true
}
if b.UseNodeName {
result.UseNodeName = true
}
if b.CollectionInterval != "" {
result.CollectionInterval = b.CollectionInterval
}
if b.collectionInterval != 0 {
result.collectionInterval = b.collectionInterval
}
if b.PublishNodeMetrics {
result.PublishNodeMetrics = true
}
if b.PublishAllocationMetrics {
result.PublishAllocationMetrics = true
}
if b.CirconusAPIToken != "" {
result.CirconusAPIToken = b.CirconusAPIToken
}
if b.CirconusAPIApp != "" {
result.CirconusAPIApp = b.CirconusAPIApp
}
if b.CirconusAPIURL != "" {
result.CirconusAPIURL = b.CirconusAPIURL
}
if b.CirconusCheckSubmissionURL != "" {
result.CirconusCheckSubmissionURL = b.CirconusCheckSubmissionURL
}
if b.CirconusSubmissionInterval != "" {
result.CirconusSubmissionInterval = b.CirconusSubmissionInterval
}
if b.CirconusCheckID != "" {
result.CirconusCheckID = b.CirconusCheckID
}
if b.CirconusCheckForceMetricActivation != "" {
result.CirconusCheckForceMetricActivation = b.CirconusCheckForceMetricActivation
}
if b.CirconusCheckInstanceID != "" {
result.CirconusCheckInstanceID = b.CirconusCheckInstanceID
}
if b.CirconusCheckSearchTag != "" {
result.CirconusCheckSearchTag = b.CirconusCheckSearchTag
}
if b.CirconusCheckTags != "" {
result.CirconusCheckTags = b.CirconusCheckTags
}
if b.CirconusCheckDisplayName != "" {
result.CirconusCheckDisplayName = b.CirconusCheckDisplayName
}
if b.CirconusBrokerID != "" {
result.CirconusBrokerID = b.CirconusBrokerID
}
if b.CirconusBrokerSelectTag != "" {
result.CirconusBrokerSelectTag = b.CirconusBrokerSelectTag
}
if b.PrefixFilter != nil {
result.PrefixFilter = b.PrefixFilter
}
if b.FilterDefault != nil {
result.FilterDefault = b.FilterDefault
}
if b.DisableDispatchedJobSummaryMetrics {
result.DisableDispatchedJobSummaryMetrics = b.DisableDispatchedJobSummaryMetrics
}
return &result
}
// Merge is used to merge two port configurations.
func (a *Ports) Merge(b *Ports) *Ports {
result := *a
if b.HTTP != 0 {
result.HTTP = b.HTTP
}
if b.RPC != 0 {
result.RPC = b.RPC
}
if b.Serf != 0 {
result.Serf = b.Serf
}
return &result
}
// Merge is used to merge two address configs together.
func (a *Addresses) Merge(b *Addresses) *Addresses {
result := *a
if b.HTTP != "" {
result.HTTP = b.HTTP
}
if b.RPC != "" {
result.RPC = b.RPC
}
if b.Serf != "" {
result.Serf = b.Serf
}
return &result
}
// Merge merges two advertise addrs configs together.
func (a *AdvertiseAddrs) Merge(b *AdvertiseAddrs) *AdvertiseAddrs {
result := *a
if b.RPC != "" {
result.RPC = b.RPC
}
if b.Serf != "" {
result.Serf = b.Serf
}
if b.HTTP != "" {
result.HTTP = b.HTTP
}
return &result
}
func (r *Resources) Merge(b *Resources) *Resources {
result := *r
if b.CPU != 0 {
result.CPU = b.CPU
}
if b.MemoryMB != 0 {
result.MemoryMB = b.MemoryMB
}
if b.DiskMB != 0 {
result.DiskMB = b.DiskMB
}
if b.ReservedPorts != "" {
result.ReservedPorts = b.ReservedPorts
}
if b.Cores != "" {
result.Cores = b.Cores
}
return &result
}
// LoadConfig loads the configuration at the given path, regardless if its a file or
// directory. Called for each -config to build up the runtime config value. Do not apply any
// default values, defaults should be added once in DefaultConfig
func LoadConfig(path string) (*Config, error) {
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
if fi.IsDir() {
return LoadConfigDir(path)
}
cleaned := filepath.Clean(path)
config, err := ParseConfigFile(cleaned)
if err != nil {
return nil, fmt.Errorf("Error loading %s: %s", cleaned, err)
}
config.Files = append(config.Files, cleaned)
return config, nil
}
// LoadConfigDir loads all the configurations in the given directory
// in alphabetical order.
func LoadConfigDir(dir string) (*Config, error) {
f, err := os.Open(dir)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf(
"configuration path must be a directory: %s", dir)
}
var files []string
err = nil
for err != io.EOF {
var fis []os.FileInfo
fis, err = f.Readdir(128)
if err != nil && err != io.EOF {
return nil, err
}
for _, fi := range fis {
// Ignore directories
if fi.IsDir() {
continue
}
// Only care about files that are valid to load.
name := fi.Name()
skip := true
if strings.HasSuffix(name, ".hcl") {
skip = false
} else if strings.HasSuffix(name, ".json") {
skip = false
}
if skip || isTemporaryFile(name) {
continue
}
path := filepath.Join(dir, name)
files = append(files, path)
}
}
// Fast-path if we have no files
if len(files) == 0 {
return &Config{}, nil
}
sort.Strings(files)
var result *Config
for _, f := range files {
config, err := ParseConfigFile(f)
if err != nil {
return nil, fmt.Errorf("Error loading %s: %s", f, err)
}
config.Files = append(config.Files, f)
if result == nil {
result = config
} else {
result = result.Merge(config)
}
}
return result, nil
}
// isTemporaryFile returns true or false depending on whether the
// provided file name is a temporary file for the following editors:
// emacs or vim.
func isTemporaryFile(name string) bool {
return strings.HasSuffix(name, "~") || // vim
strings.HasPrefix(name, ".#") || // emacs
(strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#")) // emacs
}
| mpl-2.0 |
wx1988/strabon | generaldb/src/main/java/org/openrdf/sail/generaldb/schema/TripleTable.java | 6779 | /*
* Copyright Aduna (http://www.aduna-software.com/) (c) 2008.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.sail.generaldb.schema;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.openrdf.sail.rdbms.schema.RdbmsTable;
import org.openrdf.sail.rdbms.schema.ValueTypes;
import org.openrdf.sail.rdbms.schema.ValueType;
/**
* Manages the life-cycle of the rows in a single predicate table.
*
* @author James Leigh
*
*/
public class TripleTable {
public static int tables_created;
public static int total_st;
public static final boolean UNIQUE_INDEX_TRIPLES = true;
private static final String[] PKEY = { "obj", "subj", "ctx", "expl" };
private static final String[] SUBJ_INDEX = { "subj" };
private static final String[] CTX_INDEX = { "ctx" };
private static final String[] PRED_PKEY = { "obj", "subj", "pred", "ctx", "expl" };
private static final String[] PRED_INDEX = { "pred" };
private static final String[] EXPL_INDEX = { "expl" };
private RdbmsTable table;
private ValueTypes objTypes = new ValueTypes();
private ValueTypes subjTypes = new ValueTypes();
private boolean initialize;
private boolean predColumnPresent;
private boolean indexed;
private IdSequence ids;
public TripleTable(RdbmsTable table) {
this.table = table;
}
public void setIdSequence(IdSequence ids) {
this.ids = ids;
}
public boolean isPredColumnPresent() {
return predColumnPresent;
}
public void setPredColumnPresent(boolean present) {
predColumnPresent = present;
}
public void setIndexed(boolean indexingTriples) {
indexed = true;
}
public synchronized void initTable()
throws SQLException
{
if (initialize)
return;
table.createTransactionalTable(buildTableColumns());
tables_created++;
total_st++;
if (UNIQUE_INDEX_TRIPLES) {
if (isPredColumnPresent()) {
table.primaryIndex(PRED_PKEY);
total_st++;
}
else {
table.primaryIndex(PKEY);
total_st++;
}
}
if (indexed) {
createIndex();
}
initialize = true;
}
public void reload()
throws SQLException
{
table.count();
if (table.size() > 0) {
ValueType[] values = ValueType.values();
String[] OBJ_CONTAINS = new String[values.length];
String[] SUBJ_CONTAINS = new String[values.length];
StringBuilder sb = new StringBuilder();
for (int i = 0, n = values.length; i < n; i++) {
sb.delete(0, sb.length());
ValueType code = values[i];
sb.append("MAX(CASE WHEN obj BETWEEN ").append(ids.minId(code));
sb.append(" AND ").append(ids.maxId(code));
sb.append(" THEN 1 ELSE 0 END)");
OBJ_CONTAINS[i] = sb.toString();
sb.delete(0, sb.length());
sb.append("MAX(CASE WHEN subj BETWEEN ").append(ids.minId(code));
sb.append(" AND ").append(ids.maxId(code));
sb.append(" THEN 1 ELSE 0 END)");
SUBJ_CONTAINS[i] = sb.toString();
}
int[] aggregate = table.aggregate(OBJ_CONTAINS);
for (int i = 0; i < aggregate.length; i++) {
if (aggregate[i] == 1) {
objTypes.add(values[i]);
}
}
aggregate = table.aggregate(SUBJ_CONTAINS);
for (int i = 0; i < aggregate.length; i++) {
if (aggregate[i] == 1) {
subjTypes.add(values[i]);
}
}
}
initialize = true;
}
public void close()
throws SQLException
{
table.close();
}
public boolean isIndexed()
throws SQLException
{
return table.getIndexes().size() > 1;
}
public void createIndex()
throws SQLException
{
// if (isPredColumnPresent()) {
// table.index(PRED_INDEX);
// total_st++;
// }
// table.index(SUBJ_INDEX);
// total_st++;
// table.index(CTX_INDEX);
// total_st++;
// table.index(EXPL_INDEX);
// total_st++;
///////
if (isPredColumnPresent()) {
String[] PRED_OBJ_SUBJ_INDEX = {"pred", "obj", "subj"};
table.index(PRED_OBJ_SUBJ_INDEX);
total_st++;
String[] PRED_SUBJ_OBJ_INDEX = {"pred", "subj", "obj"};
table.index(PRED_SUBJ_OBJ_INDEX);
total_st++;
String[] OBJ_PRED_SUBJ_INDEX = { "obj", "pred", "subj"};
table.index(OBJ_PRED_SUBJ_INDEX);
total_st++;
String[] OBJ_SUBJ_PRED_INDEX = { "obj", "subj", "pred"};
table.index(OBJ_SUBJ_PRED_INDEX);
total_st++;
String[] SUBJ_OBJ_PRED_INDEX = {"subj", "obj", "pred"};
table.index(SUBJ_OBJ_PRED_INDEX);
total_st++;
String[] SUBJ_PRED_OBJ_INDEX = {"subj", "pred", "obj"};
table.index(SUBJ_PRED_OBJ_INDEX);
total_st++;
} else {
// String[] OBJ_SUBJ_INDEX = {"obj", "subj"};
// table.index(OBJ_SUBJ_INDEX);
// total_st++;
String[] SUBJ_OBJ_INDEX = {"subj", "obj"};
table.index(SUBJ_OBJ_INDEX);
total_st++;
}
//////
}
public void dropIndex()
throws SQLException
{
for (Map.Entry<String, List<String>> e : table.getIndexes().entrySet()) {
if (!e.getValue().contains("OBJ") && !e.getValue().contains("obj")) {
table.dropIndex(e.getKey());
}
}
}
public boolean isReady() {
return initialize;
}
public void blockUntilReady()
throws SQLException
{
if (initialize)
return;
initTable();
}
public String getName()
throws SQLException
{
return table.getName();
}
public String getNameWhenReady()
throws SQLException
{
blockUntilReady();
return table.getName();
}
public ValueTypes getObjTypes() {
return objTypes;
}
public void setObjTypes(ValueTypes valueTypes) {
this.objTypes.merge(valueTypes);
}
public ValueTypes getSubjTypes() {
return subjTypes;
}
public void setSubjTypes(ValueTypes valueTypes) {
this.subjTypes.merge(valueTypes);
}
public void modified(int addedCount, int removedCount)
throws SQLException
{
blockUntilReady();
table.modified(addedCount, removedCount);
table.optimize();
if (isEmpty()) {
objTypes.reset();
subjTypes.reset();
}
}
public boolean isEmpty()
throws SQLException
{
blockUntilReady();
return table.size() == 0;
}
@Override
public String toString() {
return table.getName();
}
public void drop()
throws SQLException
{
blockUntilReady();
table.drop();
}
protected CharSequence buildTableColumns() {
StringBuilder sb = new StringBuilder();
sb.append(" ctx ").append(ids.getSqlType()).append(" NOT NULL,\n");
sb.append(" subj ").append(ids.getSqlType()).append(" NOT NULL,\n");
if (isPredColumnPresent()) {
sb.append(" pred ").append(ids.getSqlType()).append(" NOT NULL,\n");
}
sb.append(" obj ").append(ids.getSqlType()).append(" NOT NULL,\n");
// sb.append(" expl ").append("BOOL").append(" NOT NULL,\n");
sb.append(" expl ").append("BOOL").append(" NOT NULL\n");
//FIXME
// sb.append(" interval_start ").append("TIMESTAMP DEFAULT NULL").append(",\n");
// sb.append(" interval_end ").append("TIMESTAMP DEFAULT NULL").append("\n");
return sb;
}
}
| mpl-2.0 |
tmhorne/celtx | intl/uconv/src/nsISO88591ToUnicode.cpp | 2300 | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsUCConstructors.h"
#include "nsISO88591ToUnicode.h"
//----------------------------------------------------------------------
// Global functions and data [declaration]
static const PRUint16 g_utMappingTable[] = {
#include "cp1252.ut"
};
NS_METHOD
nsISO88591ToUnicodeConstructor(nsISupports *aOuter, REFNSIID aIID,
void **aResult)
{
return CreateOneByteDecoder((uMappingTable*) &g_utMappingTable,
aOuter, aIID, aResult);
}
| mpl-2.0 |
hashicorp/consul | agent/auto-config/auto_config_oss_test.go | 172 | //go:build !consulent
// +build !consulent
package autoconf
import (
"testing"
)
func newEnterpriseConfig(t *testing.T) EnterpriseConfig {
return EnterpriseConfig{}
}
| mpl-2.0 |
wombatant/nostalgia | deps/buildcore/scripts/pybb.py | 2497 | #! /usr/bin/env python3
#
# Copyright 2016 - 2021 gary@drinkingtea.net
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# "Python Busy Box" - adds cross platform equivalents to Unix commands that
# don't translate well to that other operating system
import os
import shutil
import subprocess
import sys
def cat(path):
try:
with open(path) as f:
data = f.read()
print(data)
return 0
except FileNotFoundError:
sys.stderr.write('cat: {}: no such file or directory\n'.format(path))
return 1
def mkdir(path):
if not os.path.exists(path) and os.path.isdir(path):
os.mkdir(path)
return 0
# this exists because Windows is utterly incapable of providing a proper rm -rf
def rm(path):
if (os.path.exists(path) or os.path.islink(path)) and not os.path.isdir(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
return 0
def ctest_all():
base_path = sys.argv[2]
if not os.path.isdir(base_path):
# no generated projects
return 0
args = ['ctest'] + sys.argv[3:]
orig_dir = os.getcwd()
for d in os.listdir(base_path):
os.chdir(os.path.join(orig_dir, base_path, d))
err = subprocess.run(args).returncode
if err != 0:
return err
return 0
def cmake_build(base_path, target):
if not os.path.isdir(base_path):
# nothing to build
return 0
for d in os.listdir(base_path):
args = ['cmake', '--build', os.path.join(base_path, d)]
if target is not None:
args.extend(['--target', target])
err = subprocess.run(args).returncode
if err != 0:
return err
return 0
def main():
if sys.argv[1] == 'mkdir':
mkdir(sys.argv[2])
elif sys.argv[1] == 'rm':
for i in range(2, len(sys.argv)):
rm(sys.argv[i])
elif sys.argv[1] == 'ctest-all':
err = ctest_all()
sys.exit(err)
elif sys.argv[1] == 'cmake-build':
err = cmake_build(sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else None)
sys.exit(err)
elif sys.argv[1] == 'cat':
err = cat(sys.argv[2])
sys.exit(err)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.exit(1)
| mpl-2.0 |
terraform-providers/terraform-provider-google | google/resource_compute_shared_vpc_host_project.go | 2448 | package google
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceComputeSharedVpcHostProject() *schema.Resource {
return &schema.Resource{
Create: resourceComputeSharedVpcHostProjectCreate,
Read: resourceComputeSharedVpcHostProjectRead,
Delete: resourceComputeSharedVpcHostProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The ID of the project that will serve as a Shared VPC host project`,
},
},
}
}
func resourceComputeSharedVpcHostProjectCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
hostProject := d.Get("project").(string)
op, err := config.clientComputeBeta.Projects.EnableXpnHost(hostProject).Do()
if err != nil {
return fmt.Errorf("Error enabling Shared VPC Host %q: %s", hostProject, err)
}
d.SetId(hostProject)
err = computeOperationWaitTime(config, op, hostProject, "Enabling Shared VPC Host", d.Timeout(schema.TimeoutCreate))
if err != nil {
d.SetId("")
return err
}
return nil
}
func resourceComputeSharedVpcHostProjectRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
hostProject := d.Id()
project, err := config.clientComputeBeta.Projects.Get(hostProject).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Project data for project %q", hostProject))
}
if project.XpnProjectStatus != "HOST" {
log.Printf("[WARN] Removing Shared VPC host resource %q because it's not enabled server-side", hostProject)
d.SetId("")
}
d.Set("project", hostProject)
return nil
}
func resourceComputeSharedVpcHostProjectDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
hostProject := d.Get("project").(string)
op, err := config.clientComputeBeta.Projects.DisableXpnHost(hostProject).Do()
if err != nil {
return fmt.Errorf("Error disabling Shared VPC Host %q: %s", hostProject, err)
}
err = computeOperationWaitTime(config, op, hostProject, "Disabling Shared VPC Host", d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
d.SetId("")
return nil
}
| mpl-2.0 |
joyent/manta-muskie | test/integration/mpu-other.test.js | 1669 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright 2020 Joyent, Inc.
*/
// Other MPU-related tests.
var test = require('tap').test;
var helper = require('../helper');
///--- Globals
var assertMantaRes = helper.assertMantaRes;
var enableMPU = Boolean(require('../../etc/config.json').enableMPU);
var testOpts = {
skip: !enableMPU && 'MPU is not enabled (enableMPU in config)'
};
///--- Tests
test('mpu other', testOpts, function (suite) {
var client;
var testAccount;
var testOperAccount;
suite.test('setup: test account', function (t) {
helper.ensureTestAccounts(t, function (err, accounts) {
t.ifError(err, 'no error loading/creating test accounts');
testAccount = accounts.regular;
t.ok(testAccount, 'have regular test account: ' +
testAccount.login);
testOperAccount = accounts.operator;
t.ok(testOperAccount,
'have operator test account: ' + testOperAccount.login);
client = helper.mantaClientFromAccountInfo(testAccount);
t.end();
});
});
suite.test('rmdir /:login/uploads should fail', function (t) {
var uploadsDir = '/' + client.user + '/uploads';
client.unlink(uploadsDir, function (err, res) {
t.ok(err);
t.equal(err.name, 'OperationNotAllowedOnRootDirectoryError');
assertMantaRes(t, res, 400);
t.end();
});
});
suite.end();
});
| mpl-2.0 |
AkashaProject/ipfs-connector | tests.ts | 5770 | import { IpfsConnector } from './index';
import * as path from 'path';
import * as fs from 'fs';
import { expect } from 'chai';
import * as rimraf from 'rimraf';
import * as constants from './src/constants';
const bigObject = require('./tests/stubs/bigObject.json');
let binTarget = path.join(__dirname, 'tests', 'bin');
let filePath = path.join(__dirname, 'tests', 'stubs', 'example.json');
const file = fs.readFileSync(filePath);
let bigObjHash: any, nodeHash: any;
const logger = {
info: function () {
},
error: function (msg) {
console.error(msg);
},
warn: function (msg) {
console.warn(msg);
},
debug: function () {
},
};
describe('IpfsConnector', function () {
let instance = IpfsConnector.getInstance();
this.timeout(90000);
before(function (done) {
instance.setBinPath(binTarget);
rimraf(binTarget, function () {
done();
});
});
beforeEach(function (done) {
setTimeout(done, 2500);
});
it('prevents multiple instances', function () {
const newInstance = () => new IpfsConnector(Symbol());
expect(newInstance).to.throw(Error);
});
it('should set .ipfs init folder', function () {
const target = path.join(binTarget, 'ipfsTest');
instance.setIpfsFolder(target);
expect(instance.options.extra.env.IPFS_PATH).to.equal(target);
});
it('should set a different logger', function () {
instance.setLogger(logger);
expect(instance.logger).to.deep.equal(logger);
});
it('should check for binaries', function () {
let downloading = false;
// this is important for DOWNLOAD_EVENTS
instance.enableDownloadEvents();
instance.once(constants.events.DOWNLOAD_STARTED, () => {
downloading = true;
});
instance.once(constants.events.DOWNLOAD_PROGRESS, (data) => {
expect(downloading).to.be.true;
expect(data).to.exist;
});
return instance.checkExecutable();
});
it('should start ipfs daemon', function () {
let inited = false;
IpfsConnector.getInstance().once(constants.events.IPFS_INITING, function () {
inited = true;
});
return instance.start().then(function (api) {
expect(api).to.have.ownProperty('ipfsApi');
expect(inited).to.be.true;
});
});
it('checks ipfs version', function () {
return instance.checkVersion().then((res: any) => {
expect(res).to.exist;
});
});
it('should get ipfs config addresses', function () {
expect(instance.api).to.exist;
return instance.getPorts().then((ports) => {
expect(ports.api).to.exist;
});
});
it('should set ipfs GATEWAY port', function () {
return instance.setPorts({ gateway: 8092 }).then((ports) => {
expect(ports).to.exist;
});
});
it('should set ipfs API port', function () {
return instance.setPorts({ api: 5043 }).then((ports) => {
expect(ports).to.exist;
});
});
it('should set ipfs SWARM port', function () {
return instance.setPorts({ swarm: 4043 }).then((ports) => {
expect(ports).to.exist;
});
});
it('restarts after setting ports', function () {
return instance.setPorts({ api: 5041, swarm: 4041, gateway: 8040 }, true)
.then((ports) => {
expect(instance.options.apiAddress).to.equal('/ip4/127.0.0.1/tcp/5041');
expect(ports).to.exist;
});
});
it('adds an object to ipfs', function () {
return instance.api.add({ data: '{}' })
.then((node) => {
expect(node.multihash).to.exist;
instance.api.get(node, '/').then((data1: any) => {
expect(data1.value).to.have.property('data');
expect(data1.value.data).to.equal('{}');
});
});
});
it('gets ports without an api', function () {
return instance.stop().then(() => instance.getPorts()).then((ports) => {
expect(ports.api).to.exist;
});
});
it('sets ports without an api', function () {
return instance.setPorts({ gateway: '8051', api: '5033', swarm: '4041' })
.then(() => {
return instance.staticGetPorts();
})
.then((ports) => {
expect(ports).to.eql({ gateway: '8051', api: '5033', swarm: '4041' });
});
});
it('sets and get config without an api', function () {
return instance.staticSetConfig('Config.That.Does.Not.Exist', 'expectedValue')
.then(() => {
return instance.staticGetConfig('Config.That.Does.Not.Exist');
})
.then((value) => {
expect(value).to.eql('expectedValue');
});
});
it('run raw cli commands', function () {
return instance.runCommand('id')
.then((stdout: string) => {
expect(stdout).to.exist;
})
.catch(() => {
throw new Error('Should not fail');
});
});
it('fail running a raw cli commands properly', function () {
return instance.runCommand('doesnotexist')
.then(() => {
throw new Error('Should not succed');
})
.catch((stderr: string) => {
expect(stderr).to.exist;
});
});
it('doesn`t throw when calling multiple start', function () {
return IpfsConnector.getInstance().start().then(() => IpfsConnector.getInstance().start());
});
it('doesn`t throw when calling multiple stop', function () {
return IpfsConnector.getInstance().stop().then(() => IpfsConnector.getInstance().stop());
});
it('sets an option', function () {
IpfsConnector.getInstance().setOption('retry', false);
expect(IpfsConnector.getInstance().options.retry).to.be.false;
});
it('removes ipfs binary file', function (done) {
instance.downloadManager.deleteBin().then(() => done());
});
after(function (done) {
instance.stop().then(() => {
rimraf(binTarget, function () {
done();
});
});
});
}); | mpl-2.0 |
pumasecurity/puma-scan | Puma.Security.Rules/Core/ConfigurationFiles/ConfigurationFileTransformCommand.cs | 2551 | /*
* Copyright(c) 2016 - 2020 Puma Security, LLC (https://pumasecurity.io)
*
* Project Leads:
* Eric Johnson (eric.johnson@pumascan.com)
* Eric Mead (eric.mead@pumascan.com)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System.IO;
using System.Xml;
using Microsoft.Web.XmlTransform;
namespace Puma.Security.Rules.Core.ConfigurationFiles
{
internal interface IConfigurationFileTransformCommand
{
void Execute(Model.ConfigurationFile file);
}
public class ConfigurationFileTransformCommand : IConfigurationFileTransformCommand
{
public void Execute(Model.ConfigurationFile file)
{
var fiProductionConfigurationPath = new FileInfo(file.ProductionConfigurationPath);
//Remove old file if one exists
if (fiProductionConfigurationPath.Exists)
fiProductionConfigurationPath.Delete();
XmlTransformableDocument doc = null;
try
{
//Apply the transform and save to disk
doc = transformConfigurationFile(file.BaseConfigurationPath, file.ProductionTransformPath);
doc.Save(file.ProductionConfigurationPath);
}
finally
{
doc?.Dispose();
}
}
private XmlTransformableDocument transformConfigurationFile(string baseConfigurationPath, string transformFilePath)
{
XmlTransformableDocument doc = new XmlTransformableDocument();
//Disable DTD's and external entities
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
doc.PreserveWhitespace = true;
doc.XmlResolver = null;
XmlReader reader = null;
try
{
//Configure reader settings
reader = XmlReader.Create(baseConfigurationPath, settings);
//Load the document
doc.Load(reader);
//Transform the doc
using (XmlTransformation transform = new XmlTransformation(transformFilePath))
{
var success = transform.Apply(doc);
}
}
finally
{
reader?.Dispose();
}
return doc;
}
}
} | mpl-2.0 |
willkg/socorro-collector | collector/lib/task_manager.py | 9109 | import time
import threading
import os
from configman import RequiredConfig, Namespace
from configman.converters import class_converter
#------------------------------------------------------------------------------
def default_task_func(a_param):
"""This default consumer function just doesn't do anything. It is a
placeholder just to demonstrate the api and not really for any other
purpose"""
pass
#------------------------------------------------------------------------------
def default_iterator():
"""This default producer's iterator yields the integers 0 through 9 and
then yields none forever thereafter. It is a placeholder to demonstrate
the api and not used for anything in a real system."""
for x in range(10):
yield ((x,), {})
while True:
yield None
#------------------------------------------------------------------------------
def respond_to_SIGTERM(signal_number, frame, target=None):
""" these classes are instrumented to respond to a KeyboardInterrupt by
cleanly shutting down. This function, when given as a handler to for
a SIGTERM event, will make the program respond to a SIGTERM as neatly
as it responds to ^C.
This function is used in registering a signal handler from the signal
module. It should be registered for any signal for which the desired
behavior is to kill the application:
signal.signal(signal.SIGTERM, respondToSIGTERM)
signal.signal(signal.SIGHUP, respondToSIGTERM)
parameters:
signal_number - unused in this function but required by the api.
frame - unused in this function but required by the api.
target - an instance of a class that has a member called 'task_manager'
that is a derivative of the TaskManager class below.
"""
if target:
target.config.logger.info('detected SIGTERM')
# by setting the quit flag to true, any calls to the 'quit_check'
# method that is so liberally passed around in this framework will
# result in raising the quit exception. The current quit exception
# is KeyboardInterrupt
target.task_manager.quit = True
else:
raise KeyboardInterrupt
#==============================================================================
class TaskManager(RequiredConfig):
required_config = Namespace()
required_config.add_option(
'idle_delay',
default=7,
doc='the delay in seconds if no job is found'
)
required_config.add_option(
'quit_on_empty_queue',
default=False,
doc='stop if the queue is empty'
)
#--------------------------------------------------------------------------
def __init__(self, config,
job_source_iterator=default_iterator,
task_func=default_task_func):
"""
parameters:
job_source_iterator - an iterator to serve as the source of data.
it can be of the form of a generator or
iterator; a function that returns an
iterator; a instance of an iterable object;
or a class that when instantiated with a
config object can be iterated. The iterator
must yield a tuple consisting of a
function's tuple of args and, optionally, a
mapping of kwargs.
Ex: (('a', 17), {'x': 23})
task_func - a function that will accept the args and kwargs yielded
by the job_source_iterator"""
super(TaskManager, self).__init__()
self.config = config
self._pid = os.getpid()
self.logger = config.logger
self.job_param_source_iter = job_source_iterator
self.task_func = task_func
self.quit = False
self.logger.debug('TaskManager finished init')
#--------------------------------------------------------------------------
def quit_check(self):
"""this is the polling function that the threads periodically look at.
If they detect that the quit flag is True, then a KeyboardInterrupt
is raised which will result in the threads dying peacefully"""
if self.quit:
raise KeyboardInterrupt
#--------------------------------------------------------------------------
def _get_iterator(self):
"""The iterator passed in can take several forms: a class that can be
instantiated and then iterated over; a function that when called
returns an iterator; an actual iterator/generator or an iterable
collection. This function sorts all that out and returns an iterator
that can be used"""
try:
return self.job_param_source_iter(self.config)
except TypeError:
try:
return self.job_param_source_iter()
except TypeError:
return self.job_param_source_iter
#--------------------------------------------------------------------------
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''):
"""When there is litte work to do, the queuing thread sleeps a lot.
It can't sleep for too long without checking for the quit flag and/or
logging about why it is sleeping.
parameters:
seconds - the number of seconds to sleep
wait_log_interval - while sleeping, it is helpful if the thread
periodically announces itself so that we
know that it is still alive. This number is
the time in seconds between log entries.
wait_reason - the is for the explaination of why the thread is
sleeping. This is likely to be a message like:
'there is no work to do'.
This was also partially motivated by old versions' of Python inability
to KeyboardInterrupt out of a long sleep()."""
for x in xrange(int(seconds)):
self.quit_check()
if wait_log_interval and not x % wait_log_interval:
self.logger.info('%s: %dsec of %dsec',
wait_reason,
x,
seconds)
self.quit_check()
time.sleep(1.0)
#--------------------------------------------------------------------------
def blocking_start(self, waiting_func=None):
"""this function starts the task manager running to do tasks. The
waiting_func is normally used to do something while other threads
are running, but here we don't have other threads. So the waiting
func will never get called. I can see wanting this function to be
called at least once after the end of the task loop."""
self.logger.debug('threadless start')
try:
for job_params in self._get_iterator(): # may never raise
# StopIteration
self.config.logger.debug('received %r', job_params)
self.quit_check()
if job_params is None:
if self.config.quit_on_empty_queue:
raise KeyboardInterrupt
self.logger.info("there is nothing to do. Sleeping "
"for %d seconds" %
self.config.idle_delay)
self._responsive_sleep(self.config.idle_delay)
continue
self.quit_check()
try:
args, kwargs = job_params
except ValueError:
args = job_params
kwargs = {}
try:
self.task_func(*args, **kwargs)
except Exception:
self.config.logger.error("Error in processing a job",
exc_info=True)
except KeyboardInterrupt:
self.logger.debug('queuingThread gets quit request')
finally:
self.quit = True
self.logger.debug("ThreadlessTaskManager dies quietly")
#--------------------------------------------------------------------------
def executor_identity(self):
"""this function is likely to be called via the configuration parameter
'executor_identity' at the root of the self.config attribute of the
application. It is most frequently used in the Pooled
ConnectionContext classes to ensure that connections aren't shared
between threads, greenlets, or whatever the unit of execution is.
This is useful for maintaining transactional integrity on a resource
connection."""
return "%s-%s" % (self._pid, threading.currentThread().getName())
| mpl-2.0 |
neolao/php | classes/Neolao/Site/Helper/ViewInterface.php | 586 | <?php
namespace Neolao\Site\Helper;
use \Neolao\Site\View;
/**
* Interface for a view helper
*
* The helper must contain a method named "main"
*/
interface ViewInterface
{
/**
* The main function
*
* @param mixed $argument The argument
*/
function main($argument);
/**
* Set the view
*
* @param \Neolao\Site\View $view View instance
*/
function setView(View $view);
/**
* Get the view
*
* @return \Neolao\Site\View View instance
*/
function getView();
}
| mpl-2.0 |