repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
darioizzo/pagmo
src/algorithm/snopt.cpp
12424
/***************************************************************************** * Copyright (C) 2004-2015 The PaGMO development team, * * Advanced Concepts Team (ACT), European Space Agency (ESA) * * http://apps.sourceforge.net/mediawiki/pagmo * * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Developers * * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Credits * * act@esa.int * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * *****************************************************************************/ #include "../exceptions.h" #include "../population.h" #include "../problem/base.h" #include "../types.h" #include <limits.h> #include "base.h" #include "snopt.h" #include "snopt_cpp_wrapper/snopt_PAGMO.h" #include "snopt_cpp_wrapper/snfilewrapper_PAGMO.h" #include "snopt_cpp_wrapper/snoptProblem_PAGMO.h" //These are here to solve a possible problem with the shared f2c libraries during linking extern "C"{ void MAIN_(){} void MAIN__(){} void _MAIN_(){} } //This is a static function that is used to wrap the snopt libraries. It has the propotype that is required //and uses the memory location pointed by cu to read all informations about the PaGMO problem. static int snopt_function_(integer *Status, integer *n, doublereal *x, integer *needF, integer *neF, doublereal *F, integer *needG, integer *neG, doublereal *G, char *cu, integer *lencu, integer *iu, integer *leniu, doublereal *ru, integer *lenru ) { (void)n; (void)needF; (void)neF; (void)needG; (void)neG; (void)G; (void)lencu; (void)iu; (void)leniu; (void)lenru; //1 - We retrieve the pointer to the base problem (PaGMO) we have 'hidden' in *cu pagmo::problem::base *prob; prob = (pagmo::problem::base*)cu; //2 - We retrieve the pointer to the allocated memory area containing the std::vector where //to copy the snopt x[] array pagmo::algorithm::snopt::preallocated_memory* preallocated = (pagmo::algorithm::snopt::preallocated_memory*)ru; for (size_t i = 0;i < ( prob->get_dimension() - prob->get_i_dimension() );i++) (preallocated->x)[i] = x[i]; //1 - to F[0] (the objective function) the value returned by the problem try { prob->objfun(preallocated->f,preallocated->x); F[0] = preallocated->f[0]; } catch (value_error) { *Status = -1; //signals to snopt that the evaluation of the objective function had numerical difficulties } //2 - and to F[.] the constraint values (equalities first) try{ prob->compute_constraints(preallocated->c, preallocated->x); for (pagmo::problem::base::size_type i=0;i<prob->get_c_dimension();++i) F[i+1] = preallocated->c[i]; } catch (value_error) { *Status = -1; //signals to snopt that the evaluation of the objective function had numerical difficulties } return 0; } namespace pagmo { namespace algorithm { /// Constructor. /** * Allows to specify some of the parameters of the SNOPT solver. * * @param[in] major Number of major iterations (refer to SNOPT manual). * @param[in] feas Feasibility tolerance (refer to SNOPT manual). * @param[in] opt Optimality tolerance (refer to SNOPT manual). * @throws value_error if major is not positive, and feas,opt are not in \f$]0,1[\f$ */ snopt::snopt(const int major,const double feas, const double opt) : m_major(major),m_feas(feas),m_opt(opt), m_file_out(false) { if (major < 0) { pagmo_throw(value_error,"number of major iterations cannot be negative"); } if (feas < 0 || feas > 1) { pagmo_throw(value_error,"feasibility cireria "); } if (opt < 0 || opt > 1) { pagmo_throw(value_error,"number of major iterations cannot be negative"); } } /// Clone method. base_ptr snopt::clone() const { return base_ptr(new snopt(*this)); } /// Evolve implementation. /** * Run SNOPT with the parameters specified in the constructor * At the end velocity is updated * * @param[in,out] pop input/output pagmo::population to be evolved. */ void snopt::evolve(population &pop) const { // Let's store some useful variables. const problem::base &prob = pop.problem(); const problem::base::size_type D = prob.get_dimension(), prob_i_dimension = prob.get_i_dimension(), prob_c_dimension = prob.get_c_dimension(), prob_f_dimension = prob.get_f_dimension(); const decision_vector &lb = prob.get_lb(), &ub = prob.get_ub(); const population::size_type NP = pop.size(); const problem::base::size_type Dc = D - prob_i_dimension; const std::vector<double>::size_type D_ineqc = prob.get_ic_dimension(); const std::vector<double>::size_type D_eqc = prob_c_dimension - D_ineqc; const std::string name = prob.get_name(); //We perform some checks to determine wether the problem/population are suitable for SNOPT if ( prob_i_dimension != 0 ) { pagmo_throw(value_error,"No integer part allowed yet...."); } if ( Dc == 0 ) { pagmo_throw(value_error,"No continuous part...."); } if ( prob_f_dimension != 1 ) { pagmo_throw(value_error,"The problem is not single objective and SNOPT is not suitable to solve it"); } // Get out if there is nothing to do. if (NP == 0 || m_major == 0) { return; } // We allocate memory for the decision vector that will be used in the snopt_function_ di_comodo.x.resize(Dc); di_comodo.c.resize(prob_c_dimension); di_comodo.f.resize(prob_f_dimension); // We construct a SnoptProblem_PAGMO passing the pointers to the problem and the allocated //memory area for the di_comodo vector snoptProblem_PAGMO SnoptProblem(prob, &di_comodo); // Allocate and initialize; integer n = Dc; // Box-constrained non-linear optimization integer neF = 1 + prob_c_dimension; //Memory sizing of A integer lenA = Dc * (1 + prob_c_dimension); //overestimate integer *iAfun = new integer[lenA]; integer *jAvar = new integer[lenA]; doublereal *A = new doublereal[lenA]; //Memory sizing of G int lenG =Dc * (1 + prob_c_dimension); //overestimate integer *iGfun = new integer[lenG]; integer *jGvar = new integer[lenG]; //Decision vector memory allocation doublereal *x = new doublereal[n]; doublereal *xlow = new doublereal[n]; doublereal *xupp = new doublereal[n]; doublereal *xmul = new doublereal[n]; integer *xstate = new integer[n]; //Objective function memory allocation doublereal *F = new doublereal[neF]; doublereal *Flow = new doublereal[neF]; doublereal *Fupp = new doublereal[neF]; doublereal *Fmul = new doublereal[neF]; integer *Fstate = new integer[neF]; integer nxnames = 1; integer nFnames = 1; char *xnames = new char[nxnames*8]; char *Fnames = new char[nFnames*8]; integer ObjRow = 0; doublereal ObjAdd = 0; // Set the upper and lower bounds. And The initial Guess int bestidx = pop.get_best_idx(); for (pagmo::problem::base::size_type i = 0; i < Dc; i++){ xlow[i] = lb[i]; xupp[i] = ub[i]; xstate[i] = 0; x[i] = pop.get_individual(bestidx).cur_x[i]; } // Set the bounds for objective, equality and inequality constraints // 1 - Objective function Flow[0] = -std::numeric_limits<double>::max(); Fupp[0] = std::numeric_limits<double>::max(); F[0] = pop.get_individual(bestidx).cur_f[0]; // 2 - Equality constraints for (pagmo::problem::base::size_type i=0;i<D_eqc;++i) { Flow[i+1] = 0; Fupp[i+1] = 0; } // 3 - Inequality constraints for (pagmo::problem::base::size_type i=0;i<D_ineqc;++i) { Flow[i+1+D_eqc] = -std::numeric_limits<double>::max(); Fupp[i+1+D_eqc] = 0; } // Load the data for SnoptProblem ... SnoptProblem.setProblemSize( n, neF ); SnoptProblem.setNeG( lenG ); SnoptProblem.setNeA( lenA ); SnoptProblem.setA ( lenA, iAfun, jAvar, A ); SnoptProblem.setG ( lenG, iGfun, jGvar ); SnoptProblem.setObjective ( ObjRow, ObjAdd ); SnoptProblem.setX ( x, xlow, xupp, xmul, xstate ); SnoptProblem.setF ( F, Flow, Fupp, Fmul, Fstate ); SnoptProblem.setXNames ( xnames, nxnames ); SnoptProblem.setFNames ( Fnames, nFnames ); SnoptProblem.setProbName ( name.c_str() ); //This is limited to be 8 characters!!! SnoptProblem.setUserFun ( snopt_function_ ); //We set some parameters if (m_screen_output) SnoptProblem.setIntParameter("Summary file",6); if (m_file_out) SnoptProblem.setPrintFile ( name.c_str() ); SnoptProblem.setIntParameter ( "Derivative option", 0 ); SnoptProblem.setIntParameter ( "Major iterations limit", m_major); SnoptProblem.setIntParameter ( "Iterations limit",100000); SnoptProblem.setRealParameter( "Major feasibility tolerance", m_feas); SnoptProblem.setRealParameter( "Major optimality tolerance", m_opt); //We set the sparsity structure int neG; try { std::vector<int> iGfun_vect, jGvar_vect; prob.set_sparsity(neG,iGfun_vect,jGvar_vect); for (int i=0;i < neG;i++) { iGfun[i] = iGfun_vect[i]; jGvar[i] = jGvar_vect[i]; } SnoptProblem.setNeG( neG ); SnoptProblem.setNeA( 0 ); SnoptProblem.setG( lenG, iGfun, jGvar ); } //the user did implement the sparsity in the problem catch (not_implemented_error) { SnoptProblem.computeJac(); neG = SnoptProblem.getNeG(); } //the user did not implement the sparsity in the problem if (m_screen_output) { std::cout << "PaGMO 4 SNOPT:" << std::endl << std::endl; std::cout << "Sparsity pattern set, NeG = " << neG << std::endl; std::cout << "iGfun: ["; for (int i=0; i<neG-1; ++i) std::cout << iGfun[i] << ","; std::cout << iGfun[neG-1] << "]" << std::endl; std::cout << "jGvar: ["; for (int i=0; i<neG-1; ++i) std::cout << jGvar[i] << ","; std::cout << jGvar[neG-1] << "]" << std::endl; } integer Cold = 0; //HERE WE CALL snoptA routine!!!!! SnoptProblem.solve( Cold ); //Save the final point making sure it is within the linear bounds std::copy(x,x+n,di_comodo.x.begin()); decision_vector newx = di_comodo.x; std::transform(di_comodo.x.begin(), di_comodo.x.end(), pop.get_individual(bestidx).cur_x.begin(), di_comodo.x.begin(),std::minus<double>()); for (integer i=0;i<n;i++) { newx[i] = std::min(std::max(lb[i],newx[i]),ub[i]); } pop.set_x(bestidx,newx); pop.set_v(bestidx,di_comodo.x); //Clean up memory allocated to call the snoptA routine delete []iAfun; delete []jAvar; delete []A; delete []iGfun; delete []jGvar; delete []x; delete []xlow; delete []xupp; delete []xmul; delete []xstate; delete []F; delete []Flow; delete []Fupp; delete []Fmul; delete []Fstate; delete []xnames; delete []Fnames; } /// Activate file output /** * Activate SNOPT screen output by setting iPrint to 15 and setting the file name to the problem typeid * * @param[in] p true or false */ void snopt::file_output(const bool p) {m_file_out = p;} /// Algorithm name std::string snopt::get_name() const { return "SNOPT"; } /// Extra human readable algorithm info. /** * @return a formatted string displaying the parameters of the algorithm. */ std::string snopt::human_readable_extra() const { std::ostringstream s; s << "major_iter:" << m_major << " feas_tol: "<<m_feas<< " opt_tol: "<<m_opt << std::endl; return s.str(); } }} //namespaces BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::algorithm::snopt)
gpl-3.0
phenix-factory/fci-obedience
plugins-dist/sites/lang/sites_bg.php
11962
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://trad.spip.org/tradlang_module/sites?lang_cible=bg // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) return; $GLOBALS[$GLOBALS['idx_lang']] = array( // A 'articles_dispo' => 'En attente', # NEW 'articles_meme_auteur' => 'Tous les articles de cet auteur', # NEW 'articles_off' => 'Bloqués', # NEW 'articles_publie' => 'Publiés', # NEW 'articles_refuse' => 'Supprimés', # NEW 'articles_tous' => 'Tous', # NEW 'aucun_article_syndic' => 'Aucun article syndiqué', # NEW 'avis_echec_syndication_01' => 'Обединението пропадна: или избраната крайна точка не се чете, или там няма статия.', 'avis_echec_syndication_02' => 'Обединението пропадна: няма връзка с информацията от сайта', 'avis_site_introuvable' => 'Страницата не е намерена', 'avis_site_syndique_probleme' => 'Предупреждение: проблем при обединението на сайта; в следствие на това системата е временно прекъсната. Моля, проверете файла за обединяване (<b>@url_syndic@</b>) и опитайте отново да възстановите информацията. ', # MODIF 'avis_sites_probleme_syndication' => 'Проблем при обединението на сайтовете', 'avis_sites_syndiques_probleme' => 'Проблем при обединяването на сайтовете', // B 'bouton_exporter' => 'Exporter', # NEW 'bouton_importer' => 'Importer', # NEW 'bouton_radio_modere_posteriori' => 'последваща модерация', # MODIF 'bouton_radio_modere_priori' => 'предварителна модерация', # MODIF 'bouton_radio_non_syndication' => 'Без обединяване', 'bouton_radio_syndication' => 'Обединеняване на сайтове:', // C 'confirmer_purger_syndication' => 'Êtes-vous certain de vouloir supprimer tous les articles syndiqués de ce site ?', # NEW // E 'entree_adresse_fichier_syndication' => 'Адрес на файла за обединяване:', 'entree_adresse_site' => '<b>Уеб-адрес (URL) на сайта</b> [Задължително]', 'entree_description_site' => 'Описание на сайта', 'erreur_fichier_format_inconnu' => 'Le format du fichier @fichier@ n\'est pas pris en charge.', # NEW 'erreur_fichier_incorrect' => 'Impossible de lire le fichier.', # NEW // F 'form_prop_nom_site' => 'Име на сайта', // I 'icone_article_syndic' => 'Article syndiqué', # NEW 'icone_articles_syndic' => 'Articles syndiqués', # NEW 'icone_controler_syndication' => 'Publication des articles syndiqués', # NEW 'icone_modifier_site' => 'Промяна на страницата', 'icone_referencer_nouveau_site' => 'Свързване на нов сайт', 'icone_site_reference' => 'Sites référencés', # NEW 'icone_supprimer_article' => 'Supprimer cet article', # NEW 'icone_supprimer_articles' => 'Supprimer ces articles', # NEW 'icone_valider_article' => 'Valider cet article', # NEW 'icone_valider_articles' => 'Valider ces articles', # NEW 'icone_voir_sites_references' => 'Показване на свързани сайтове', 'info_1_site_importe' => '1 site a été importé', # NEW 'info_a_valider' => '[за одобрение]', 'info_aucun_site_importe' => 'Aucun site n\'a pu être importé', # NEW 'info_bloquer' => 'блокиране', 'info_bloquer_lien' => 'блокиране на препратката', 'info_derniere_syndication' => 'Последното обединяване на този сайт бе на', 'info_liens_syndiques_1' => 'обединени връзки', 'info_liens_syndiques_2' => 'очакват одобрение.', 'info_nb_sites_importes' => '@nb@ sites ont été importés', # NEW 'info_nom_site_2' => '<b>Име на сайта</b> [Задължително]', 'info_panne_site_syndique' => 'Обединеният сайт не работи', 'info_probleme_grave' => 'грешка с', 'info_question_proposer_site' => 'Кой може да предложи свързани сайтове?', 'info_retablir_lien' => 'възстановяване на препратката', 'info_site_attente' => 'Сайт очакващ одобрение', 'info_site_propose' => 'Сайтът е изпратен на:', 'info_site_reference' => 'Свързани сайтове', 'info_site_refuse' => 'Интернет страницата е отхвърлена', 'info_site_syndique' => 'Този сайт е обединен.', # MODIF 'info_site_valider' => 'Сайтове, очакващи одобрение за публикуване', 'info_sites_referencer' => 'Свързване на сайт', 'info_sites_refuses' => 'Отхвърлени сайтове', 'info_statut_site_1' => 'Сайтът е:', 'info_statut_site_2' => 'Публикуван', 'info_statut_site_3' => 'Изпратен', 'info_statut_site_4' => 'За изтриване', # MODIF 'info_syndication' => 'обединение:', 'info_syndication_articles' => 'статия (статии)', 'item_bloquer_liens_syndiques' => 'Блокиране на обединените връзки за одобрение', 'item_gerer_annuaire_site_web' => 'Управление на директорията на уеб сайта', 'item_non_bloquer_liens_syndiques' => 'Без блокиране на връзките - следствия от обединяване', 'item_non_gerer_annuaire_site_web' => 'Деактивиране на директорията на уеб сайта', 'item_non_utiliser_syndication' => 'Без използване на автоматично обединяване', 'item_utiliser_syndication' => 'Използване на автоматично обединяване', // L 'label_exporter_avec_mots_cles_1' => 'Exporter les mots-clés sous forme de tags', # NEW 'label_exporter_id_parent' => 'Exporter les sites de la rubrique', # NEW 'label_exporter_publie_seulement_1' => 'Exporter uniquement les sites publiés', # NEW 'label_fichier_import' => 'Fichier HTML', # NEW 'label_importer_les_tags_1' => 'Importer les tags sous forme de mot-clé', # NEW 'label_importer_statut_publie_1' => 'Publier automatiquement les sites', # NEW 'lien_mise_a_jour_syndication' => 'Актуализация', 'lien_nouvelle_recuperation' => 'Опитайте да направите ново възстановяване на данните ', 'lien_purger_syndication' => 'Effacer tous les articles syndiqués', # NEW // N 'nombre_articles_syndic' => '@nb@ articles syndiqués', # NEW // S 'statut_off' => 'Supprimé', # NEW 'statut_prop' => 'En attente', # NEW 'statut_publie' => 'Publié', # NEW 'syndic_choix_moderation' => 'Какво да се направи със следващите препратки от сайта?', 'syndic_choix_oublier' => 'Какво да се направи с препратките, които вече не присъстват във файла за обединение?', 'syndic_choix_resume' => 'Някои сайтове предлагат пълен текст на статиите. Когато се предлага пълен текст, искате ли да направите обединение:', 'syndic_lien_obsolete' => 'излязла от употреба препратка', 'syndic_option_miroir' => 'автоматично да се блокират', 'syndic_option_oubli' => 'автоматично да се изтриват (след @mois@ месец(а))', 'syndic_option_resume_non' => 'пълно съдържание на статиите (във формат HTML)', 'syndic_option_resume_oui' => 'само резюме (текстов формат)', 'syndic_options' => 'Опции за обединение:', // T 'texte_expliquer_export_bookmarks' => 'Vous pouvez exporter une liste de sites au format Marque-page HTML, pour vous permettre ensuite de l\'importer dans votre navigateur ou dans un service en ligne', # NEW 'texte_expliquer_import_bookmarks' => 'Vous pouvez importer une liste de sites au format Marque-page HTML, en provenance de votre navigateur ou d\'un service en ligne de gestion des Marques-pages.', # NEW 'texte_liens_sites_syndiques' => 'Препратките, идващи от обединените сайтове може да бъдат предварително блокирани. Следната настройка показва обединените сайтове след тяхното създаване в обичаен вид След това е възможно да се блокира индивидуално всяка препратка поотделно или да се избере от всеки сайт, да се блокира препратката, идваща от него.', # MODIF 'texte_messages_publics' => 'Публични съобщения към статията:', 'texte_non_fonction_referencement' => 'Можете да изберете да не използвате автоматичното свойство и да въвжедате ръчно елементите, свързани със сайта.', # MODIF 'texte_referencement_automatique' => '<b>Автоматично свързване на сайт</b><br />Можете лесно да свъжетете уеб страници чрез обозначаване по-долу на желания URL на страницата или адресът на нейния файл за обединение. СПИП автоматично ще събере нужната информация, отнасяща се до сайта (наименование, описание и т.н.).', # MODIF 'texte_referencement_automatique_verifier' => 'Veuillez vérifier les informations fournies par <tt>@url@</tt> avant d\'enregistrer.', # NEW 'texte_syndication' => 'Ако сайтът го позволява, възможно е автоматично да възстановява списъка с най-новия материал. За да постигнете това, нужно е да активирате обединяване. <blockquote><i>Някои доставчици деактивират тази функция; ако случаят е този, няма да можете да използвате обединяването на съдържание от Вашия сайт.</i></blockquote>', # MODIF 'titre_articles_syndiques' => 'Обединени статии, изтеглени от този сайт', 'titre_dernier_article_syndique' => 'Най-новите обединени статии', 'titre_exporter_bookmarks' => 'Exporter des Marques-pages', # NEW 'titre_importer_bookmarks' => 'Importer des Marques-pages', # NEW 'titre_importer_exporter_bookmarks' => 'Importer et Exporter des Marques-pages', # NEW 'titre_page_sites_tous' => 'Свързани сайтове', 'titre_referencement_sites' => 'Свързване и обединение на сайтове', 'titre_site_numero' => 'НОМЕР НА СТРАНИЦАТА:', 'titre_sites_proposes' => 'Изпратени сайтове', 'titre_sites_references_rubrique' => 'Свързани сайтове в рубриката', 'titre_sites_syndiques' => 'Обединени сайтове', 'titre_sites_tous' => 'Свързани сайтове', 'titre_syndication' => 'Обединяване на сайтовете', 'tout_voir' => 'Voir tous les articles syndiqués', # NEW // U 'un_article_syndic' => '1 article syndiqué' # NEW ); ?>
gpl-3.0
raddreher/CometVisu
source/test/karma/ui/structure/pure/Slide-spec.js
2163
/* Slide-spec.js * * copyright (c) 2010-2016, Christian Mayer and the CometVisu contributers. * * 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 the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /** * Unit tests for slide widget * */ describe("testing a slide widget", function() { // disabled until jquery dep has been removed it("should test the slide creator", function() { var res = this.createTestWidgetString("slide", {}, '<label>Test</label>'); var widget = qx.bom.Html.clean([res[1]])[0]; expect(res[0].getPath()).toBe("id_0"); expect(widget).toHaveClass('slide'); expect(widget).toHaveLabel('Test'); }); it("should test the min/max and step settings", function() { var widgetInstance = this.createTestElement("slide", {min: 30, max: 130, step: 5}); expect(widgetInstance.getMin()).toBe(30); expect(widgetInstance.getMax()).toBe(130); expect(widgetInstance.getStep()).toBe(5); }); it("should test the min/max settings from transform", function() { var widgetInstance = this.createTestElement("slide", {}, null, null, {transform: 'DPT:5.004'}); expect(widgetInstance.getMin()).toBe(0.0); expect(widgetInstance.getMax()).toBe(255.0); }); it("should test incoming data", function() { var widgetInstance = this.createTestElement("slide", {}, null, "Test_slide", {transform: 'DPT:5.004'}); this.initWidget(widgetInstance); widgetInstance.update("Test_slide", "64"); // 0x64 == 100 expect(widgetInstance.__slider.getValue()).toBe(100); }); });
gpl-3.0
Jochen1980/lacshop
application/controllers/compare.php
12404
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @copyright (C) OXID eSales AG 2003-2014 * @version OXID eShop CE */ /** * Comparing Products. * Takes a few products and show attribute values to compare them. */ class Compare extends oxUBase { /** * Number of possible compare pages. * @var integer */ protected $_iCntPages = 1; /** * Number of user's orders. * @var integer */ protected $_iOrderCnt = null; /** * Number of articles per page. * @var integer */ protected $_iArticlesPerPage = 3; /** * Number of user's orders. * @var integer */ protected $_iCompItemsCnt = null; /** * Items which are currently to show in comparison. * @var array */ protected $_aCompItems = null; /** * Article list in comparison. * @var object */ protected $_oArtList = null; /** * Article attribute list in comparison. * @var object */ protected $_oAttributeList = null; /** * Recomendation list * @var object */ protected $_oRecommList = null; /** * Page navigation * @var object */ protected $_oPageNavigation = null; /** * Sign if to load and show bargain action * @var bool */ protected $_blBargainAction = true; /** * Show tags cloud * @var bool */ protected $_blShowTagCloud = false; /** * Current class template name. * @var string */ protected $_sThisTemplate = 'page/compare/compare.tpl'; /** * Array of id to form recommendation list. * * @var array */ protected $_aSimilarRecommListIds = null; /** * moves current article to the left in compare items array * * @return null */ public function moveLeft() //#777C { $sArticleId = oxConfig::getParameter( 'aid' ); if ( $sArticleId && ( $aItems = $this->getCompareItems() ) ) { $sPrevArticleId = null; $blFound = false; foreach ( $aItems as $sOxid => $sVal ) { if ( $sOxid == $sArticleId ) { $blFound = true; } if ( !$blFound ) { $sPrevArticleId = $sOxid; } } if ( $sPrevArticleId ) { $aNewItems = array(); foreach ( $aItems as $sOxid => $sVal ) { if ( $sOxid == $sPrevArticleId ) { $aNewItems[$sArticleId] = true; } elseif ( $sOxid == $sArticleId ) { $aNewItems[$sPrevArticleId] = true; } else { $aNewItems[$sOxid] = true; } } $this->setCompareItems($aNewItems); } } } /** * moves current article to the right in compare items array * * @return null */ public function moveRight() //#777C { $sArticleId = oxConfig::getParameter( 'aid' ); if ( $sArticleId && ( $aItems = $this->getCompareItems() ) ) { $sNextArticleId = 0; $blFound = false; foreach ( $aItems as $sOxid => $sVal ) { if ( $blFound ) { $sNextArticleId = $sOxid; $blFound = false; } if ( $sOxid == $sArticleId ) { $blFound = true; } } if ( $sNextArticleId ) { $aNewItems = array(); foreach ( $aItems as $sOxid => $sVal ) { if ( $sOxid == $sArticleId ) { $aNewItems[$sNextArticleId] = true; } elseif ( $sOxid == $sNextArticleId ) { $aNewItems[$sArticleId] = true; } else { $aNewItems[$sOxid] = true; } } $this->setCompareItems($aNewItems); } } } /** * changes default template for compare in popup * * @return null */ public function inPopup() // #777C { $this->_sThisTemplate = 'compare_popup.tpl'; $this->_iArticlesPerPage = -1; } /** * Articlelist count in comparison setter * * @param integer $iCount compare items count * * @return integer */ public function setCompareItemsCnt( $iCount ) { $this->_iCompItemsCnt = $iCount; } /** * Template variable getter. Returns article list count in comparison * * @return integer */ public function getCompareItemsCnt() { if ( $this->_iCompItemsCnt === null ) { $this->_iCompItemsCnt = 0; if ( $aItems = $this->getCompareItems() ) { $this->_iCompItemsCnt = count( $aItems ); } } return $this->_iCompItemsCnt; } /** * Compare item $_aCompItems getter * * @return null */ public function getCompareItems() { if ( $this->_aCompItems === null ) { $aItems = oxSession::getVar( 'aFiltcompproducts' ); if ( is_array($aItems) && count($aItems) ) { $this->_aCompItems = $aItems; } } return $this->_aCompItems; } /** * Compare item $_aCompItems setter * * @param array $aItems compare items i new order * * @return null */ public function setCompareItems( $aItems) { $this->_aCompItems = $aItems; oxSession::setVar( 'aFiltcompproducts', $aItems ); } /** * $_iArticlesPerPage setter * * @param int $iNumber article count in compare page * * @return null */ protected function _setArticlesPerPage( $iNumber) { $this->_iArticlesPerPage = $iNumber; } /** * turn off paging * * @return null */ public function setNoPaging() { $this->_setArticlesPerPage(0); } /** * Template variable getter. Returns comparison's article * list in order per page * * @return object */ public function getCompArtList() { if ( $this->_oArtList === null ) { if ( ( $aItems = $this->getCompareItems() ) ) { // counts how many pages $oList = oxNew( 'oxarticlelist' ); $oList->loadIds( array_keys( $aItems ) ); // cut page articles if ( $this->_iArticlesPerPage > 0 ) { $this->_iCntPages = round( $oList->count() / $this->_iArticlesPerPage + 0.49 ); $aItems = $this->_removeArticlesFromPage( $aItems, $oList ); } $this->_oArtList = $this->_changeArtListOrder( $aItems, $oList ); } } return $this->_oArtList; } /** * Template variable getter. Returns attribute list * * @return object */ public function getAttributeList() { if ( $this->_oAttributeList === null ) { $this->_oAttributeList = false; if ( $oArtList = $this->getCompArtList()) { $oAttributeList = oxNew( 'oxattributelist' ); $this->_oAttributeList = $oAttributeList->loadAttributesByIds( array_keys( $oArtList ) ); } } return $this->_oAttributeList; } /** * Return array of id to form recommend list. * * @return array */ public function getSimilarRecommListIds() { if ( $this->_aSimilarRecommListIds === null ) { $this->_aSimilarRecommListIds = false; if ( $oArtList = $this->getCompArtList() ) { $this->_aSimilarRecommListIds = array_keys( $oArtList ); } } return $this->_aSimilarRecommListIds; } /** * Template variable getter. Returns page navigation * * @return object */ public function getPageNavigation() { if ( $this->_oPageNavigation === null ) { $this->_oPageNavigation = false; $this->_oPageNavigation = $this->generatePageNavigation(); } return $this->_oPageNavigation; } /** * Cuts page articles * * @param array $aItems article array * @param object $oList article list array * * @return array $aNewItems */ protected function _removeArticlesFromPage( $aItems, $oList ) { //#1106S $aItems changed to $oList. //2006-08-10 Alfonsas, compare arrows fixed, array position is very important here, preserve it. $aListKeys = $oList->arrayKeys(); $aItemKeys = array_keys($aItems); $aKeys = array_intersect( $aItemKeys, $aListKeys ); $aNewItems = array(); $iActPage = $this->getActPage(); for ( $i = $this->_iArticlesPerPage * $iActPage; $i < $this->_iArticlesPerPage * $iActPage + $this->_iArticlesPerPage; $i++ ) { if ( !isset($aKeys[$i])) { break; } $aNewItems[$aKeys[$i]] = & $aItems[$aKeys[$i]]; } return $aNewItems; } /** * Changes order of list elements * * @param array $aItems article array * @param object $oList article list array * * @return array $oNewList */ protected function _changeArtListOrder( $aItems, $oList ) { // #777C changing order of list elements, according to $aItems $oNewList = array(); $iCnt = 0; $iActPage = $this->getActPage(); foreach ( $aItems as $sOxid => $sVal ) { //#4391T, skipping non loaded products if (!isset ($oList[$sOxid]) ) { continue; } $iCnt++; $oNewList[$sOxid] = $oList[$sOxid]; // hide arrow if article is first in the list $oNewList[$sOxid]->hidePrev = false; if ( $iActPage == 0 && $iCnt==1 ) { $oNewList[$sOxid]->hidePrev = true; } // hide arrow if article is last in the list $oNewList[$sOxid]->hideNext = false; if ( ( $iActPage + 1 ) == $this->_iCntPages && $iCnt == count( $aItems ) ) { $oNewList[$sOxid]->hideNext = true; } } return $oNewList; } /** * changes default template for compare in popup * * @return null */ public function getOrderCnt() { if ( $this->_iOrderCnt === null ) { $this->_iOrderCnt = 0; if ( $oUser = $this->getUser() ) { $this->_iOrderCnt = $oUser->getOrderCount(); } } return $this->_iOrderCnt; } /** * Returns Bread Crumb - you are here page1/page2/page3... * * @return array */ public function getBreadCrumb() { $aPaths = array(); $aPath = array(); $aPath['title'] = oxRegistry::getLang()->translateString( 'MY_ACCOUNT', oxRegistry::getLang()->getBaseLanguage(), false ); $aPath['link'] = oxRegistry::get("oxSeoEncoder")->getStaticUrl( $this->getViewConfig()->getSelfLink() . 'cl=account' ); $aPaths[] = $aPath; $aPath['title'] = oxRegistry::getLang()->translateString( 'PRODUCT_COMPARISON', oxRegistry::getLang()->getBaseLanguage(), false ); $aPath['link'] = $this->getLink(); $aPaths[] = $aPath; return $aPaths; } }
gpl-3.0
dlazz/ansible
lib/ansible/modules/cloud/google/gcp_bigquery_table_facts.py
18836
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_bigquery_table_facts description: - Gather facts for GCP Table short_description: Gather facts for GCP Table version_added: 2.8 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: dataset: description: - Name of the dataset. required: false extends_documentation_fragment: gcp ''' EXAMPLES = ''' - name: a table facts gcp_bigquery_table_facts: dataset: example_dataset project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' items: description: List of items returned: always type: complex contains: tableReference: description: - Reference describing the ID of this table. returned: success type: complex contains: datasetId: description: - The ID of the dataset containing this table. returned: success type: str projectId: description: - The ID of the project containing this table. returned: success type: str tableId: description: - The ID of the the table. returned: success type: str creationTime: description: - The time when this dataset was created, in milliseconds since the epoch. returned: success type: int description: description: - A user-friendly description of the dataset. returned: success type: str friendlyName: description: - A descriptive name for this table. returned: success type: str id: description: - An opaque ID uniquely identifying the table. returned: success type: str labels: description: - The labels associated with this dataset. You can use these to organize and group your datasets . returned: success type: dict lastModifiedTime: description: - The time when this table was last modified, in milliseconds since the epoch. returned: success type: int location: description: - The geographic location where the table resides. This value is inherited from the dataset. returned: success type: str name: description: - Name of the table. returned: success type: str numBytes: description: - The size of this table in bytes, excluding any data in the streaming buffer. returned: success type: int numLongTermBytes: description: - The number of bytes in the table that are considered "long-term storage". returned: success type: int numRows: description: - The number of rows of data in this table, excluding any data in the streaming buffer. returned: success type: int type: description: - Describes the table type. returned: success type: str view: description: - The view definition. returned: success type: complex contains: useLegacySql: description: - Specifies whether to use BigQuery's legacy SQL for this view . returned: success type: bool userDefinedFunctionResources: description: - Describes user-defined function resources used in the query. returned: success type: complex contains: inlineCode: description: - An inline resource that contains code for a user-defined function (UDF). Providing a inline code resource is equivalent to providing a URI for a file containing the same code. returned: success type: str resourceUri: description: - A code resource to load from a Google Cloud Storage URI (gs://bucket/path). returned: success type: str timePartitioning: description: - If specified, configures time-based partitioning for this table. returned: success type: complex contains: expirationMs: description: - Number of milliseconds for which to keep the storage for a partition. returned: success type: int type: description: - The only type supported is DAY, which will generate one partition per day. returned: success type: str streamingBuffer: description: - Contains information regarding this table's streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer. returned: success type: complex contains: estimatedBytes: description: - A lower-bound estimate of the number of bytes currently in the streaming buffer. returned: success type: int estimatedRows: description: - A lower-bound estimate of the number of rows currently in the streaming buffer. returned: success type: int oldestEntryTime: description: - Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available. returned: success type: int schema: description: - Describes the schema of this table. returned: success type: complex contains: fields: description: - Describes the fields in a table. returned: success type: complex contains: description: description: - The field description. The maximum length is 1,024 characters. returned: success type: str fields: description: - Describes the nested schema fields if the type property is set to RECORD. returned: success type: list mode: description: - The field mode. returned: success type: str name: description: - The field name. returned: success type: str type: description: - The field data type. returned: success type: str encryptionConfiguration: description: - Custom encryption configuration. returned: success type: complex contains: kmsKeyName: description: - Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table. The BigQuery Service Account associated with your project requires access to this encryption key. returned: success type: str expirationTime: description: - The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. returned: success type: int externalDataConfiguration: description: - Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. returned: success type: complex contains: autodetect: description: - Try to detect schema and format options automatically. Any option specified explicitly will be honored. returned: success type: bool compression: description: - The compression type of the data source. returned: success type: str ignoreUnknownValues: description: - Indicates if BigQuery should allow extra values that are not represented in the table schema . returned: success type: bool maxBadRecords: description: - The maximum number of bad records that BigQuery can ignore when reading data . returned: success type: int sourceFormat: description: - The data format. returned: success type: str sourceUris: description: - 'The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one ''*'' wildcard character and it must come after the ''bucket'' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified. Also, the ''*'' wildcard character is not allowed.' returned: success type: list schema: description: - The schema for the data. Schema is required for CSV and JSON formats. returned: success type: complex contains: fields: description: - Describes the fields in a table. returned: success type: complex contains: description: description: - The field description. returned: success type: str fields: description: - Describes the nested schema fields if the type property is set to RECORD . returned: success type: list mode: description: - Field mode. returned: success type: str name: description: - Field name. returned: success type: str type: description: - Field data type. returned: success type: str googleSheetsOptions: description: - Additional options if sourceFormat is set to GOOGLE_SHEETS. returned: success type: complex contains: skipLeadingRows: description: - The number of rows at the top of a Google Sheet that BigQuery will skip when reading the data. returned: success type: int csvOptions: description: - Additional properties to set if sourceFormat is set to CSV. returned: success type: complex contains: allowJaggedRows: description: - Indicates if BigQuery should accept rows that are missing trailing optional columns . returned: success type: bool allowQuotedNewlines: description: - Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file . returned: success type: bool encoding: description: - The character encoding of the data. returned: success type: str fieldDelimiter: description: - The separator for fields in a CSV file. returned: success type: str quote: description: - The value that is used to quote data sections in a CSV file. returned: success type: str skipLeadingRows: description: - The number of rows at the top of a CSV file that BigQuery will skip when reading the data. returned: success type: int bigtableOptions: description: - Additional options if sourceFormat is set to BIGTABLE. returned: success type: complex contains: ignoreUnspecifiedColumnFamilies: description: - If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema . returned: success type: bool readRowkeyAsString: description: - If field is true, then the rowkey column families will be read and converted to string. returned: success type: bool columnFamilies: description: - List of column families to expose in the table schema along with their types. returned: success type: complex contains: columns: description: - Lists of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. returned: success type: complex contains: encoding: description: - The encoding of the values when the type is not STRING. returned: success type: str fieldName: description: - If the qualifier is not a valid BigQuery field identifier, a valid identifier must be provided as the column field name and is used as field name in queries. returned: success type: str onlyReadLatest: description: - If this is set, only the latest version of value in this column are exposed . returned: success type: bool qualifierString: description: - Qualifier of the column. returned: success type: str type: description: - The type to convert the value in cells of this column. returned: success type: str encoding: description: - The encoding of the values when the type is not STRING. returned: success type: str familyId: description: - Identifier of the column family. returned: success type: str onlyReadLatest: description: - If this is set only the latest version of value are exposed for all columns in this column family . returned: success type: bool type: description: - The type to convert the value in cells of this column family. returned: success type: str dataset: description: - Name of the dataset. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule( argument_spec=dict( dataset=dict(type='str') ) ) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/bigquery'] items = fetch_list(module, collection(module)) if items.get('tables'): items = items.get('tables') else: items = [] return_value = { 'items': items } module.exit_json(**return_value) def collection(module): return "https://www.googleapis.com/bigquery/v2/projects/{project}/datasets/{dataset}/tables".format(**module.params) def fetch_list(module, link): auth = GcpSession(module, 'bigquery') response = auth.get(link) return return_if_object(module, response) def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
gpl-3.0
HelgePlaschke/slims5_meranti
admin/modules/system/backup.php
4143
<?php /** * * Copyright (C) 2007,2008 Arie Nugraha (dicarve@yahoo.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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /* Backup Management section */ // key to authenticate define('INDEX_AUTH', '1'); // main system configuration require '../../../sysconfig.inc.php'; // IP based access limitation require_once LIB_DIR.'ip_based_access.inc.php'; do_checkIP('smc'); do_checkIP('smc-system'); // start the session require SENAYAN_BASE_DIR.'admin/default/session.inc.php'; require SENAYAN_BASE_DIR.'admin/default/session_check.inc.php'; require SIMBIO_BASE_DIR.'simbio_GUI/table/simbio_table.inc.php'; require SIMBIO_BASE_DIR.'simbio_GUI/paging/simbio_paging.inc.php'; require SIMBIO_BASE_DIR.'simbio_DB/datagrid/simbio_dbgrid.inc.php'; // create token in session $_SESSION['token'] = utility::createRandomString(32); // privileges checking $can_read = utility::havePrivilege('system', 'r'); $can_write = utility::havePrivilege('system', 'w'); if (!($can_read AND $can_write)) { die('<div class="errorBox">'.__('You don\'t have enough privileges to view this section').'</div>'); } /* search form */ ?> <fieldset class="menuBox"> <div class="menuBoxInner backupIcon"> <div class="per_title"> <h2><?php echo __('Database Backup'); ?></h2> </div> <div class="sub_section"> <div class="action_button"> <input type="button" onclick="$('#createBackup').submit()" class="button notAJAX" value="<?php echo __('Start New Backup'); ?>" /> </div> <form name="search" action="<?php echo MODULES_WEB_ROOT_DIR; ?>system/backup_proc.php" id="search" method="get" style="display: inline;"><?php echo __('Search'); ?> : <input type="text" name="keywords" size="30" /> <input type="submit" id="doSearch" value="<?php echo __('Search'); ?>" class="button" /> </form> <form name="createBackup" id="createBackup" target="blindSubmit" action="<?php echo MODULES_WEB_ROOT_DIR; ?>system/backup_proc.php" method="post" style="display: inline; visibility: hidden;"> <input type="hidden" name="start" value="true" /> <input type="hidden" name="tkn" value="<?php echo $_SESSION['token']; ?>" /> </form> </div> </div> </fieldset> <?php /* BACKUP LOG LIST */ // table spec $table_spec = 'backup_log AS bl LEFT JOIN user AS u ON bl.user_id=u.user_id'; // create datagrid $datagrid = new simbio_datagrid(); $datagrid->setSQLColumn('u.realname AS \'Backup Executor\'', 'bl.backup_time AS \'Backup Time\'', 'bl.backup_file AS \'Backup File Location\''); $datagrid->setSQLorder('backup_time DESC'); // is there any search if (isset($_GET['keywords']) AND $_GET['keywords']) { $keywords = $dbs->escape_string($_GET['keywords']); $datagrid->setSQLCriteria("bl.backup_time LIKE '%$keywords%' OR bl.backup_file LIKE '%$keywords%'"); } // set table and table header attributes $datagrid->table_attr = 'align="center" id="dataList" cellpadding="5" cellspacing="0"'; $datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"'; // set delete proccess URL $datagrid->delete_URL = $_SERVER['PHP_SELF']; // put the result into variables $datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, false); if (isset($_GET['keywords']) AND $_GET['keywords']) { $msg = str_replace('{result->num_rows}', $datagrid->num_rows, __('Found <strong>{result->num_rows}</strong> from your keywords')); //mfc echo '<div class="infoBox">'.$msg.' : "'.$_GET['keywords'].'"</div>'; } echo $datagrid_result;
gpl-3.0
ljacqu/AuthMeReloaded
src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java
4602
package fr.xephi.authme.datasource; import ch.jalu.configme.properties.Property; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Integration test for {@link SQLite}. */ public class SQLiteIntegrationTest extends AbstractDataSourceIntegrationTest { /** Mock of a settings instance. */ private static Settings settings; /** Collection of SQL statements to execute for initialization of a test. */ private static String[] sqlInitialize; /** Connection to the SQLite test database. */ private Connection con; /** * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ @BeforeClass public static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an implementation for SQLite Class.forName("org.sqlite.JDBC"); settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); set(DatabaseSettings.MYSQL_DATABASE, "sqlite-test"); set(DatabaseSettings.MYSQL_TABLE, "authme"); TestHelper.setRealLogger(); Path sqlInitFile = TestHelper.getJarPath(TestHelper.PROJECT_ROOT + "datasource/sql-initialize.sql"); // Note ljacqu 20160221: It appears that we can only run one statement per Statement.execute() so we split // the SQL file by ";\n" as to get the individual statements sqlInitialize = new String(Files.readAllBytes(sqlInitFile)).split(";(\\r?)\\n"); } @Before public void initializeConnectionAndTable() throws SQLException { Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:"); try (Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS authme"); for (String statement : sqlInitialize) { st.execute(statement); } } con = connection; } @After public void closeConnection() { silentClose(con); } @Test public void shouldSetUpTableIfMissing() throws SQLException { // given Statement st = con.createStatement(); // table is absent st.execute("DROP TABLE authme"); SQLite sqLite = new SQLite(settings, null, con); // when sqLite.setup(); // then // Save some player to verify database is operational sqLite.saveAuth(PlayerAuth.builder().name("Name").build()); assertThat(sqLite.getAllAuths(), hasSize(1)); } @Test public void shouldCreateMissingColumns() throws SQLException { // given Statement st = con.createStatement(); // drop table and create one with only some of the columns: SQLite doesn't support ALTER TABLE t DROP COLUMN c st.execute("DROP TABLE authme"); st.execute("CREATE TABLE authme (" + "id bigint, " + "username varchar(255) unique, " + "password varchar(255) not null, " + "primary key (id));"); SQLite sqLite = new SQLite(settings, null, con); // when sqLite.setup(); // then // Save some player to verify database is operational sqLite.saveAuth(PlayerAuth.builder().name("Name").build()); assertThat(sqLite.getAllAuths(), hasSize(1)); } @Override protected DataSource getDataSource(String saltColumn) { when(settings.getProperty(DatabaseSettings.MYSQL_COL_SALT)).thenReturn(saltColumn); return new SQLite(settings, null, con); } private static <T> void set(Property<T> property, T value) { when(settings.getProperty(property)).thenReturn(value); } private static void silentClose(Connection con) { if (con != null) { try { if (!con.isClosed()) { con.close(); } } catch (SQLException e) { // silent } } } }
gpl-3.0
DROPCitizenShip/opencongress
features/support/env.rb
3357
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. # It is recommended to regenerate this file in the future when you upgrade to a # newer version of cucumber-rails. Consider adding your own code to a new file # instead of editing this one. Cucumber will automatically load all features/**/*.rb # files. ENV["RAILS_ENV"] ||= "cucumber" require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support require 'cucumber/rails/world' require 'cucumber/rails/active_record' require 'cucumber/web/tableish' require 'webrat' require 'webrat/core/matchers' Webrat.configure do |config| config.mode = :rails config.open_error_files = false # Set to true if you want error pages to pop up in the browser end # If you set this to false, any error raised from within your app will bubble # up to your step definition and out to cucumber unless you catch it somewhere # on the way. You can make Rails rescue errors and render error pages on a # per-scenario basis by tagging a scenario or feature with the @allow-rescue tag. # # If you set this to true, Rails will rescue all errors and render error # pages, more or less in the same way your application would behave in the # default production environment. It's not recommended to do this for all # of your scenarios, as this makes it hard to discover errors in your application. ActionController::Base.allow_rescue = false # If you set this to true, each scenario will run in a database transaction. # You can still turn off transactions on a per-scenario basis, simply tagging # a feature or scenario with the @no-txn tag. If you are using Capybara, # tagging with @culerity or @javascript will also turn transactions off. # # If you set this to false, transactions will be off for all scenarios, # regardless of whether you use @no-txn or not. # # Beware that turning transactions off will leave data in your database # after each scenario, which can lead to hard-to-debug failures in # subsequent scenarios. If you do this, we recommend you create a Before # block that will explicitly put your database in a known state. #Cucumber::Rails::World.use_transactional_fixtures = true # How to clean your database when transactions are turned off. See # http://github.com/bmabey/database_cleaner for more info. if defined?(ActiveRecord::Base) begin require 'database_cleaner' DatabaseCleaner.strategy = :truncation rescue LoadError => ignore_if_database_cleaner_not_present end end Fixtures.create_fixtures("features/fixtures", "actions") Fixtures.create_fixtures("features/fixtures", "amendments") Fixtures.create_fixtures("features/fixtures", "articles") Fixtures.create_fixtures("features/fixtures", "bills") Fixtures.create_fixtures("features/fixtures", "hot_bill_categories") Fixtures.create_fixtures("features/fixtures", "people") Fixtures.create_fixtures("features/fixtures", "roles") Fixtures.create_fixtures("features/fixtures", "taggings") Fixtures.create_fixtures("features/fixtures", "tags") Fixtures.create_fixtures("features/fixtures", "bills") Fixtures.create_fixtures("features/fixtures", "user_roles") Fixtures.create_fixtures("features/fixtures", "users") Fixtures.create_fixtures("features/fixtures", "zipcode_districts")
gpl-3.0
care2x/2.7
help/sr/help_sr_system_admin.php
219
<font face="Verdana, Arial" size=3 color="#0000cc"> <b>System Admin</b></font> <p> <font size=2 face="verdana,arial" > <form> Note</b> <ul> Be careful in configuring the system. </ul> </font> </form>
gpl-3.0
likr/emogdf
ogdf/src/coin/Clp/ClpMessage.cpp
9410
/* $Id: ClpMessage.cpp 1753 2011-06-19 16:27:26Z stefan $ */ // Copyright (C) 2000, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include "CoinPragma.hpp" #include "ClpMessage.hpp" /// Structure for use by ClpMessage.cpp typedef struct { CLP_Message internalNumber; int externalNumber; // or continuation char detail; const char * message; } Clp_message; static Clp_message clp_us_english[] = { {CLP_SIMPLEX_FINISHED, 0, 1, "Optimal - objective value %g"}, {CLP_SIMPLEX_INFEASIBLE, 1, 1, "Primal infeasible - objective value %g"}, {CLP_SIMPLEX_UNBOUNDED, 2, 1, "Dual infeasible - objective value %g"}, {CLP_SIMPLEX_STOPPED, 3, 1, "Stopped - objective value %g"}, {CLP_SIMPLEX_ERROR, 4, 1, "Stopped due to errors - objective value %g"}, {CLP_SIMPLEX_INTERRUPT, 5, 1, "Stopped by event handler - objective value %g"}, {CLP_SIMPLEX_STATUS, 6, 1, "%d Obj %g%? Primal inf %g (%d)%? Dual inf %g (%d)%? w.o. free dual inf (%d)"}, {CLP_DUAL_BOUNDS, 25, 3, "Looking optimal checking bounds with %g"}, {CLP_SIMPLEX_ACCURACY, 60, 3, "Primal error %g, dual error %g"}, {CLP_SIMPLEX_BADFACTOR, 7, 2, "Singular factorization of basis - status %d"}, {CLP_SIMPLEX_BOUNDTIGHTEN, 8, 3, "Bounds were tightened %d times"}, {CLP_SIMPLEX_INFEASIBILITIES, 9, 1, "%d infeasibilities"}, {CLP_SIMPLEX_FLAG, 10, 3, "Flagging variable %c%d"}, {CLP_SIMPLEX_GIVINGUP, 11, 2, "Stopping as close enough"}, {CLP_DUAL_CHECKB, 12, 2, "New dual bound of %g"}, {CLP_DUAL_ORIGINAL, 13, 3, "Going back to original objective"}, {CLP_SIMPLEX_PERTURB, 14, 1, "Perturbing problem by %g %% of %g - largest nonzero change %g (%% %g) - largest zero change %g"}, {CLP_PRIMAL_ORIGINAL, 15, 2, "Going back to original tolerance"}, {CLP_PRIMAL_WEIGHT, 16, 2, "New infeasibility weight of %g"}, {CLP_PRIMAL_OPTIMAL, 17, 2, "Looking optimal with tolerance of %g"}, {CLP_SINGULARITIES, 18, 2, "%d total structurals rejected in initial factorization"}, {CLP_MODIFIEDBOUNDS, 19, 1, "%d variables/rows fixed as scaled bounds too close"}, {CLP_RIMSTATISTICS1, 20, 2, "Absolute values of scaled objective range from %g to %g"}, {CLP_RIMSTATISTICS2, 21, 2, "Absolute values of scaled bounds range from %g to %g, minimum gap %g"}, {CLP_RIMSTATISTICS3, 22, 2, "Absolute values of scaled rhs range from %g to %g, minimum gap %g"}, {CLP_POSSIBLELOOP, 23, 2, "Possible loop - %d matches (%x) after %d checks"}, {CLP_SMALLELEMENTS, 24, 1, "Matrix will be packed to eliminate %d small elements"}, {CLP_SIMPLEX_HOUSE1, 101, 32, "dirOut %d, dirIn %d, theta %g, out %g, dj %g, alpha %g"}, {CLP_SIMPLEX_HOUSE2, 102, 4, "%d %g In: %c%d Out: %c%d%? dj ratio %g distance %g%? dj %g distance %g"}, {CLP_SIMPLEX_NONLINEAR, 103, 4, "Primal nonlinear change %g (%d)"}, {CLP_SIMPLEX_FREEIN, 104, 32, "Free column in %d"}, {CLP_SIMPLEX_PIVOTROW, 105, 32, "Pivot row %d"}, {CLP_DUAL_CHECK, 106, 4, "Btran alpha %g, ftran alpha %g"}, {CLP_PRIMAL_DJ, 107, 4, "For %c%d btran dj %g, ftran dj %g"}, {CLP_PACKEDSCALE_INITIAL, 1001, 2, "Initial range of elements is %g to %g"}, {CLP_PACKEDSCALE_WHILE, 1002, 3, "Range of elements is %g to %g"}, {CLP_PACKEDSCALE_FINAL, 1003, 2, "Final range of elements is %g to %g"}, {CLP_PACKEDSCALE_FORGET, 1004, 2, "Not bothering to scale as good enough"}, {CLP_INITIALIZE_STEEP, 1005, 3, "Initializing steepest edge weights - old %g, new %g"}, {CLP_UNABLE_OPEN, 6001, 0, "Unable to open file %s for reading"}, {CLP_BAD_BOUNDS, 6002, 1, "%d bad bound pairs or bad objectives were found - first at %c%d"}, {CLP_BAD_MATRIX, 6003, 1, "Matrix has %d large values, first at column %d, row %d is %g"}, {CLP_LOOP, 6004, 1, "Can't get out of loop - stopping"}, {CLP_DUPLICATEELEMENTS, 26, 1, "Matrix will be packed to eliminate %d duplicate elements"}, {CLP_IMPORT_RESULT, 27, 1, "Model was imported from %s in %g seconds"}, {CLP_IMPORT_ERRORS, 3001, 1, " There were %d errors when importing model from %s"}, {CLP_EMPTY_PROBLEM, 3002, 1, "Empty problem - %d rows, %d columns and %d elements"}, {CLP_CRASH, 28, 1, "Crash put %d variables in basis, %d dual infeasibilities"}, {CLP_END_VALUES_PASS, 29, 1, "End of values pass after %d iterations"}, {CLP_QUADRATIC_BOTH, 108, 32, "%s %d (%g) and %d (%g) both basic"}, {CLP_QUADRATIC_PRIMAL_DETAILS, 109, 32, "coeff %g, %g, %g - dj %g - deriv zero at %g, sj at %g"}, {CLP_IDIOT_ITERATION, 30, 1, "%d infeas %g, obj %g - mu %g, its %d, %d interior"}, {CLP_INFEASIBLE, 3003, 1, "Analysis indicates model infeasible or unbounded"}, {CLP_MATRIX_CHANGE, 31, 2, "Matrix can not be converted into %s"}, {CLP_TIMING, 32, 1, "%s objective %.10g - %d iterations time %.2f2%?, Presolve %.2f%?, Idiot %.2f%?"}, {CLP_INTERVAL_TIMING, 33, 2, "%s took %.2f seconds (total %.2f)"}, {CLP_SPRINT, 34, 1, "Pass %d took %d iterations, objective %g, dual infeasibilities %g( %d)"}, {CLP_BARRIER_ITERATION, 35, 1, "%d Primal %g Dual %g Complementarity %g - %d fixed, rank %d"}, {CLP_BARRIER_OBJECTIVE_GAP, 36, 3, "Feasible - objective gap %g"}, {CLP_BARRIER_GONE_INFEASIBLE, 37, 2, "Infeasible"}, {CLP_BARRIER_CLOSE_TO_OPTIMAL, 38, 2, "Close to optimal after %d iterations with complementarity %g"}, {CLP_BARRIER_COMPLEMENTARITY, 39, 2, "Complementarity %g - %s"}, {CLP_BARRIER_EXIT2, 40, 1, "Exiting - using solution from iteration %d"}, {CLP_BARRIER_STOPPING, 41, 1, "Exiting on iterations"}, {CLP_BARRIER_EXIT, 42, 1, "Optimal %s"}, {CLP_BARRIER_SCALING, 43, 3, "Scaling %s by %g"}, {CLP_BARRIER_MU, 44, 3, "Changing mu from %g to %g"}, {CLP_BARRIER_INFO, 45, 3, "Detail - %s"}, {CLP_BARRIER_END, 46, 1, "At end primal/dual infeasibilities %g/%g, complementarity gap %g, objective %g"}, {CLP_BARRIER_ACCURACY, 47, 2, "Relative error in phase %d, %d passes %g => %g"}, {CLP_BARRIER_SAFE, 48, 2, "Initial safe primal value %g, objective norm %g"}, {CLP_BARRIER_NEGATIVE_GAPS, 49, 3, "%d negative gaps summing to %g"}, {CLP_BARRIER_REDUCING, 50, 2, "Reducing %s step from %g to %g"}, {CLP_BARRIER_DIAGONAL, 51, 3, "Range of diagonal values is %g to %g"}, {CLP_BARRIER_SLACKS, 52, 3, "%d slacks increased, %d decreased this iteration"}, {CLP_BARRIER_DUALINF, 53, 3, "Maximum dual infeasibility on fixed is %g"}, {CLP_BARRIER_KILLED, 54, 3, "%d variables killed this iteration"}, {CLP_BARRIER_ABS_DROPPED, 55, 2, "Absolute error on dropped rows is %g"}, {CLP_BARRIER_ABS_ERROR, 56, 2, "Primal error is %g and dual error is %g"}, {CLP_BARRIER_FEASIBLE, 57, 2, "Infeasibilities - bound %g , primal %g ,dual %g"}, {CLP_BARRIER_STEP, 58, 2, "Steps - primal %g ,dual %g , mu %g"}, {CLP_BARRIER_KKT, 6005, 0, "Quadratic barrier needs a KKT factorization"}, {CLP_RIM_SCALE, 59, 1, "Automatic rim scaling gives objective scale of %g and rhs/bounds scale of %g"}, {CLP_SLP_ITER, 58, 1, "Pass %d objective %g - drop %g, largest delta %g"}, {CLP_COMPLICATED_MODEL, 3004, 1, "Can not use addRows or addColumns on CoinModel as mixed, %d rows, %d columns"}, {CLP_BAD_STRING_VALUES, 3005, 1, "%d string elements had no values associated with them"}, {CLP_CRUNCH_STATS, 61, 2, "Crunch %d (%d) rows, %d (%d) columns and %d (%d) elements"}, {CLP_PARAMETRICS_STATS, 62, 1, "Theta %g - objective %g"}, {CLP_PARAMETRICS_STATS2, 63, 2, "Theta %g - objective %g, %s in, %s out"}, #ifndef NO_FATHOM_PRINT {CLP_FATHOM_STATUS, 63, 2, "Fathoming node %d - %d nodes (%d iterations) - current depth %d"}, {CLP_FATHOM_SOLUTION, 64, 1, "Fathoming node %d - solution of %g after %d nodes at depth %d"}, {CLP_FATHOM_FINISH, 65, 1, "Fathoming node %d (depth %d) took %d nodes (%d iterations) - maximum depth %d"}, #endif {CLP_GENERAL, 1000, 1, "%s"}, {CLP_GENERAL2, 1001, 2, "%s"}, {CLP_DUMMY_END, 999999, 0, ""} }; static Clp_message uk_english[] = { { CLP_SIMPLEX_FINISHED, 0, 1, "Optimal - objective value %g,\ okay CLP can solve some LPs but you really need Xpress from Dash Associates :-)" }, {CLP_DUMMY_END, 999999, 0, ""} }; /* Constructor */ ClpMessage::ClpMessage(Language language) : CoinMessages(sizeof(clp_us_english) / sizeof(Clp_message)) { language_ = language; strcpy(source_, "Clp"); class_ = 1; //solver Clp_message * message = clp_us_english; while (message->internalNumber != CLP_DUMMY_END) { CoinOneMessage oneMessage(message->externalNumber, message->detail, message->message); addMessage(message->internalNumber, oneMessage); message ++; } // Put into compact form toCompact(); // now override any language ones switch (language) { case uk_en: message = uk_english; break; default: message = NULL; break; } // replace if any found if (message) { while (message->internalNumber != CLP_DUMMY_END) { replaceMessage(message->internalNumber, message->message); message ++; } } }
gpl-3.0
vanpouckesven/cosnics
src/Chamilo/Configuration/Plugin/phpfreechat/index.php
1021
<?php require_once "src/phpfreechat.class.php"; // adjust to your own path $params["serverid"] = md5(__FILE__); // used to identify the chat $params["isadmin"] = true; // set wether the person is admin or not $params["title"] = "Chamilo Chat"; // title of the chat $params["nick"] = ""; // ask for nick at the user $params["frozen_nick"] = true; // forbid the user to change his/her nickname later $params["channels"] = array("Chamilo"); $params["max_channels"] = 1; $params["theme"] = "blune"; $params["display_pfc_logo"] = false; $params["display_ping"] = false; $params["displaytabclosebutton"] = false; $params["btn_sh_whosonline"] = false; $params["btn_sh_smileys"] = false; $chat = new phpFreeChat($params); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>phpFreeChat demo</title> </head> <body> <?php $chat->printChat(); ?> </body> </html>
gpl-3.0
looseend/android
libraries/cyclestreets-core/src/main/java/net/cyclestreets/api/DistanceFormatter.java
1547
package net.cyclestreets.api; public abstract class DistanceFormatter { public abstract String distance(int metres); public abstract String total_distance(int metres); static public DistanceFormatter formatter(final String name) { if("miles".equals(name)) return milesFormatter; return kmFormatter; } // formatter static private DistanceFormatter kmFormatter = new KmFormatter(); static private DistanceFormatter milesFormatter = new MilesFormatter(); static private class KmFormatter extends DistanceFormatter { public String distance(int metres) { if(metres < 2000) return String.format("%dm", metres); return total_distance(metres); } // distance public String total_distance(int metres) { int km = metres / 1000; int frackm = (int)((metres % 1000) / 10.0); return String.format("%d.%02dkm", km, frackm); } // total_distance } // class KmFormatter static private class MilesFormatter extends DistanceFormatter { private int metresToYards(int metres) { return (int)(metres * 1.0936133); } public String distance(int metres) { int yards = metresToYards(metres); if(yards <= 750) return String.format("%dyds", yards); return total_distance(metres); } // distance public String total_distance(int metres) { int yards = metresToYards(metres); int miles = yards / 1760; int frackm = (int)((yards % 1760) / 17.6); return String.format("%d.%02d miles", miles, frackm); } // total_distance } // class MilesFormatter } // DistanceFormatter
gpl-3.0
chriskmanx/qmole
QMOLEDEV/llvm-3.1.src/utils/TableGen/TableGen.cpp
6829
//===- TableGen.cpp - Top-Level TableGen implementation for LLVM ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the main function for LLVM's TableGen. // //===----------------------------------------------------------------------===// #include "AsmMatcherEmitter.h" #include "AsmWriterEmitter.h" #include "CallingConvEmitter.h" #include "CodeEmitterGen.h" #include "DAGISelEmitter.h" #include "DFAPacketizerEmitter.h" #include "DisassemblerEmitter.h" #include "EDEmitter.h" #include "FastISelEmitter.h" #include "InstrInfoEmitter.h" #include "IntrinsicEmitter.h" #include "PseudoLoweringEmitter.h" #include "RegisterInfoEmitter.h" #include "SubtargetEmitter.h" #include "SetTheory.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenAction.h" using namespace llvm; enum ActionType { PrintRecords, GenEmitter, GenRegisterInfo, GenInstrInfo, GenAsmWriter, GenAsmMatcher, GenDisassembler, GenPseudoLowering, GenCallingConv, GenDAGISel, GenDFAPacketizer, GenFastISel, GenSubtarget, GenIntrinsic, GenTgtIntrinsic, GenEDInfo, PrintEnums, PrintSets }; namespace { cl::opt<ActionType> Action(cl::desc("Action to perform:"), cl::values(clEnumValN(PrintRecords, "print-records", "Print all records to stdout (default)"), clEnumValN(GenEmitter, "gen-emitter", "Generate machine code emitter"), clEnumValN(GenRegisterInfo, "gen-register-info", "Generate registers and register classes info"), clEnumValN(GenInstrInfo, "gen-instr-info", "Generate instruction descriptions"), clEnumValN(GenCallingConv, "gen-callingconv", "Generate calling convention descriptions"), clEnumValN(GenAsmWriter, "gen-asm-writer", "Generate assembly writer"), clEnumValN(GenDisassembler, "gen-disassembler", "Generate disassembler"), clEnumValN(GenPseudoLowering, "gen-pseudo-lowering", "Generate pseudo instruction lowering"), clEnumValN(GenAsmMatcher, "gen-asm-matcher", "Generate assembly instruction matcher"), clEnumValN(GenDAGISel, "gen-dag-isel", "Generate a DAG instruction selector"), clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer", "Generate DFA Packetizer for VLIW targets"), clEnumValN(GenFastISel, "gen-fast-isel", "Generate a \"fast\" instruction selector"), clEnumValN(GenSubtarget, "gen-subtarget", "Generate subtarget enumerations"), clEnumValN(GenIntrinsic, "gen-intrinsic", "Generate intrinsic information"), clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic", "Generate target intrinsic information"), clEnumValN(GenEDInfo, "gen-enhanced-disassembly-info", "Generate enhanced disassembly info"), clEnumValN(PrintEnums, "print-enums", "Print enum values for a class"), clEnumValN(PrintSets, "print-sets", "Print expanded sets for testing DAG exprs"), clEnumValEnd)); cl::opt<std::string> Class("class", cl::desc("Print Enum list for this class"), cl::value_desc("class name")); class LLVMTableGenAction : public TableGenAction { public: bool operator()(raw_ostream &OS, RecordKeeper &Records) { switch (Action) { case PrintRecords: OS << Records; // No argument, dump all contents break; case GenEmitter: CodeEmitterGen(Records).run(OS); break; case GenRegisterInfo: RegisterInfoEmitter(Records).run(OS); break; case GenInstrInfo: InstrInfoEmitter(Records).run(OS); break; case GenCallingConv: CallingConvEmitter(Records).run(OS); break; case GenAsmWriter: AsmWriterEmitter(Records).run(OS); break; case GenAsmMatcher: AsmMatcherEmitter(Records).run(OS); break; case GenDisassembler: DisassemblerEmitter(Records).run(OS); break; case GenPseudoLowering: PseudoLoweringEmitter(Records).run(OS); break; case GenDAGISel: DAGISelEmitter(Records).run(OS); break; case GenDFAPacketizer: DFAGen(Records).run(OS); break; case GenFastISel: FastISelEmitter(Records).run(OS); break; case GenSubtarget: SubtargetEmitter(Records).run(OS); break; case GenIntrinsic: IntrinsicEmitter(Records).run(OS); break; case GenTgtIntrinsic: IntrinsicEmitter(Records, true).run(OS); break; case GenEDInfo: EDEmitter(Records).run(OS); break; case PrintEnums: { std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class); for (unsigned i = 0, e = Recs.size(); i != e; ++i) OS << Recs[i]->getName() << ", "; OS << "\n"; break; } case PrintSets: { SetTheory Sets; Sets.addFieldExpander("Set", "Elements"); std::vector<Record*> Recs = Records.getAllDerivedDefinitions("Set"); for (unsigned i = 0, e = Recs.size(); i != e; ++i) { OS << Recs[i]->getName() << " = ["; const std::vector<Record*> *Elts = Sets.expand(Recs[i]); assert(Elts && "Couldn't expand Set instance"); for (unsigned ei = 0, ee = Elts->size(); ei != ee; ++ei) OS << ' ' << (*Elts)[ei]->getName(); OS << " ]\n"; } break; } } return false; } }; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); LLVMTableGenAction Action; return TableGenMain(argv[0], Action); }
gpl-3.0
tectronics/xerteonlinetoolkits
website_code/php/extend/get_module.php
2048
<?php require_once("../../../config.php"); require("../user_library.php"); if(is_user_admin()){ _load_language_file("/extend.inc"); $url = str_replace("github","codeload.github",$_POST['url']) . "/zip/master"; // set URL and other appropriate options $ch = curl_init(); $vers = curl_version(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'curl/' . $vers['version'] ); curl_setopt($ch, CURLOPT_URL, $url); // grab URL and pass it to the browser $data = curl_exec($ch); $file = $xerte_toolkits_site->import_path . time() . ".zip"; file_put_contents($file, $data); $zip = new ZipArchive(); $data = $zip->open($file); $extract_files = array(); $language_files = array(); for($i = 0; $i < $zip->numFiles; $i++) { if(strpos($zip->getNameIndex($i),"/languagesXOT/")){ $zip->renameIndex($i,str_replace($_POST['name'] . "-master/","",$zip->getNameIndex($i))); $name = explode("/", $zip->getNameIndex($i)); $zip->renameIndex($i,$name[2] . "/modules/" . $name[0] . "/" . $name[3]); array_push($language_files, $zip->getNameIndex($i)); }else{ $zip->renameIndex($i,str_replace($_POST['name'] . "-master/","",$zip->getNameIndex($i))); array_push($extract_files, $zip->getNameIndex($i)); } } array_shift($language_files); array_shift($extract_files); $zip->extractTo($xerte_toolkits_site->root_file_path . "modules/" , $extract_files); $zip->extractTo($xerte_toolkits_site->root_file_path . "languages/" , $language_files); echo "<p>" . $_POST['name'] . " " . EXTEND_INSTALLED . " : <a onclick='module_activate(\"" . str_replace("XOT-","",$_POST['name']) . "\")'>" . EXTEND_ACTIVATE . "</a></p>"; echo "<p><a onclick='list_modules(\"" . str_replace("XOT-","",$_POST['name']) . "\")'>" . EXTEND_LIST . "</a></p>"; } ?>
gpl-3.0
kenshay/ImageScripter
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/algorithms/bipartite/matrix.py
6742
# -*- coding: utf-8 -*- """ ==================== Biadjacency matrices ==================== """ # Copyright (C) 2013-2018 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. import itertools from networkx.convert_matrix import _generate_weighted_edges import networkx as nx __author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>', 'Aric Hagberg <aric.hagberg@gmail.com>']) __all__ = ['biadjacency_matrix', 'from_biadjacency_matrix'] def biadjacency_matrix(G, row_order, column_order=None, dtype=None, weight='weight', format='csr'): r"""Return the biadjacency matrix of the bipartite graph G. Let `G = (U, V, E)` be a bipartite graph with node sets `U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1` if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is not `None` and matches the name of an edge attribute, its value is used instead of 1. Parameters ---------- G : graph A NetworkX graph row_order : list of nodes The rows of the matrix are ordered according to the list of nodes. column_order : list, optional The columns of the matrix are ordered according to the list of nodes. If column_order is None, then the ordering of columns is arbitrary. dtype : NumPy data-type, optional A valid NumPy dtype used to initialize the array. If None, then the NumPy default is used. weight : string or None, optional (default='weight') The edge data key used to provide each value in the matrix. If None, then each edge has weight 1. format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'} The type of the matrix to be returned (default 'csr'). For some algorithms different implementations of sparse matrices can perform better. See [2]_ for details. Returns ------- M : SciPy sparse matrix Biadjacency matrix representation of the bipartite graph G. Notes ----- No attempt is made to check that the input graph is bipartite. For directed bipartite graphs only successors are considered as neighbors. To obtain an adjacency matrix with ones (or weight values) for both predecessors and successors you have to generate two biadjacency matrices where the rows of one of them are the columns of the other, and then add one to the transpose of the other. See Also -------- adjacency_matrix from_biadjacency_matrix References ---------- .. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph .. [2] Scipy Dev. References, "Sparse Matrices", https://docs.scipy.org/doc/scipy/reference/sparse.html """ from scipy import sparse nlen = len(row_order) if nlen == 0: raise nx.NetworkXError("row_order is empty list") if len(row_order) != len(set(row_order)): msg = "Ambiguous ordering: `row_order` contained duplicates." raise nx.NetworkXError(msg) if column_order is None: column_order = list(set(G) - set(row_order)) mlen = len(column_order) if len(column_order) != len(set(column_order)): msg = "Ambiguous ordering: `column_order` contained duplicates." raise nx.NetworkXError(msg) row_index = dict(zip(row_order, itertools.count())) col_index = dict(zip(column_order, itertools.count())) if G.number_of_edges() == 0: row, col, data = [], [], [] else: row, col, data = zip(*((row_index[u], col_index[v], d.get(weight, 1)) for u, v, d in G.edges(row_order, data=True) if u in row_index and v in col_index)) M = sparse.coo_matrix((data, (row, col)), shape=(nlen, mlen), dtype=dtype) try: return M.asformat(format) # From Scipy 1.1.0, asformat will throw a ValueError instead of an # AttributeError if the format if not recognized. except (AttributeError, ValueError): raise nx.NetworkXError("Unknown sparse matrix format: %s" % format) def from_biadjacency_matrix(A, create_using=None, edge_attribute='weight'): r"""Creates a new bipartite graph from a biadjacency matrix given as a SciPy sparse matrix. Parameters ---------- A: scipy sparse matrix A biadjacency matrix representation of a graph create_using: NetworkX graph Use specified graph for result. The default is Graph() edge_attribute: string Name of edge attribute to store matrix numeric value. The data will have the same type as the matrix entry (int, float, (real,imag)). Notes ----- The nodes are labeled with the attribute `bipartite` set to an integer 0 or 1 representing membership in part 0 or part 1 of the bipartite graph. If `create_using` is an instance of :class:`networkx.MultiGraph` or :class:`networkx.MultiDiGraph` and the entries of `A` are of type :class:`int`, then this function returns a multigraph (of the same type as `create_using`) with parallel edges. In this case, `edge_attribute` will be ignored. See Also -------- biadjacency_matrix from_numpy_matrix References ---------- [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph """ G = nx.empty_graph(0, create_using) n, m = A.shape # Make sure we get even the isolated nodes of the graph. G.add_nodes_from(range(n), bipartite=0) G.add_nodes_from(range(n, n + m), bipartite=1) # Create an iterable over (u, v, w) triples and for each triple, add an # edge from u to v with weight w. triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A)) # If the entries in the adjacency matrix are integers and the graph is a # multigraph, then create parallel edges, each with weight 1, for each # entry in the adjacency matrix. Otherwise, create one edge for each # positive entry in the adjacency matrix and set the weight of that edge to # be the entry in the matrix. if A.dtype.kind in ('i', 'u') and G.is_multigraph(): chain = itertools.chain.from_iterable triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples) G.add_weighted_edges_from(triples, weight=edge_attribute) return G # fixture for nose tests def setup_module(module): from nose import SkipTest try: import scipy except: raise SkipTest("SciPy not available")
gpl-3.0
Merlijnv/MFM
build/tmp/recompileMc/sources/net/minecraft/entity/ai/attributes/AbstractAttributeMap.java
3236
package net.minecraft.entity.ai.attributes; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import net.minecraft.util.LowerStringMap; public abstract class AbstractAttributeMap { protected final Map<IAttribute, IAttributeInstance> attributes = Maps.<IAttribute, IAttributeInstance>newHashMap(); protected final Map<String, IAttributeInstance> attributesByName = new LowerStringMap(); protected final Multimap<IAttribute, IAttribute> field_180377_c = HashMultimap.<IAttribute, IAttribute>create(); public IAttributeInstance getAttributeInstance(IAttribute attribute) { return (IAttributeInstance)this.attributes.get(attribute); } public IAttributeInstance getAttributeInstanceByName(String attributeName) { return (IAttributeInstance)this.attributesByName.get(attributeName); } /** * Registers an attribute with this AttributeMap, returns a modifiable AttributeInstance associated with this map */ public IAttributeInstance registerAttribute(IAttribute attribute) { if (this.attributesByName.containsKey(attribute.getAttributeUnlocalizedName())) { throw new IllegalArgumentException("Attribute is already registered!"); } else { IAttributeInstance iattributeinstance = this.func_180376_c(attribute); this.attributesByName.put(attribute.getAttributeUnlocalizedName(), iattributeinstance); this.attributes.put(attribute, iattributeinstance); for (IAttribute iattribute = attribute.func_180372_d(); iattribute != null; iattribute = iattribute.func_180372_d()) { this.field_180377_c.put(iattribute, attribute); } return iattributeinstance; } } protected abstract IAttributeInstance func_180376_c(IAttribute attribute); public Collection<IAttributeInstance> getAllAttributes() { return this.attributesByName.values(); } public void func_180794_a(IAttributeInstance instance) { } public void removeAttributeModifiers(Multimap<String, AttributeModifier> modifiers) { for (Entry<String, AttributeModifier> entry : modifiers.entries()) { IAttributeInstance iattributeinstance = this.getAttributeInstanceByName((String)entry.getKey()); if (iattributeinstance != null) { iattributeinstance.removeModifier((AttributeModifier)entry.getValue()); } } } public void applyAttributeModifiers(Multimap<String, AttributeModifier> modifiers) { for (Entry<String, AttributeModifier> entry : modifiers.entries()) { IAttributeInstance iattributeinstance = this.getAttributeInstanceByName((String)entry.getKey()); if (iattributeinstance != null) { iattributeinstance.removeModifier((AttributeModifier)entry.getValue()); iattributeinstance.applyModifier((AttributeModifier)entry.getValue()); } } } }
gpl-3.0
MaxGfeller/BigTree-CMS
core/admin/modules/developer/security/default.php
3141
<? $security_policy = $cms->getSetting("bigtree-internal-security-policy"); BigTree::globalizeArray($security_policy,"htmlspecialchars"); ?> <div class="container" id="security_settings"> <form method="post" action="<?=DEVELOPER_ROOT?>security/update/"> <section> <div class="contain"> <div class="left"> <h3>Failed Logins</h3> <p>Rules to prevent brute forcing of passwords.</p> <fieldset class="rule"> <input type="text" name="user_fails[count]" value="<?=$user_fails["count"]?>" /> failed logins for a given <strong>user</strong> over <br /> <input type="text" name="user_fails[time]" value="<?=$user_fails["time"]?>" /> minutes leads to a ban of the <strong>user</strong> for <br /> <input type="text" name="user_fails[ban]" value="<?=$user_fails["ban"]?>" /> <strong>minutes</strong> or until a password reset </fieldset> <fieldset class="rule"> <input type="text" name="ip_fails[count]" value="<?=$ip_fails["count"]?>" /> failed logins for a given <strong>IP address</strong> over <br /> <input type="text" name="ip_fails[time]" value="<?=$ip_fails["time"]?>" /> minutes leads to a ban of the <strong>IP address</strong> for <br /> <input type="text" name="ip_fails[ban]" value="<?=$ip_fails["ban"]?>" /> <strong>hours</strong> </fieldset> <br /> <h3>Password Strength</h3> <fieldset> <label>Minimum Password Length <small>(leave blank or 0 to have no restriction)</small></label> <input type="text" name="password[length]" value="<?=$password["length"]?>" /> </fieldset> <fieldset> <input type="checkbox" name="password[mixedcase]"<? if ($password["mixedcase"]) { ?> checked="checked"<? } ?> /> <label class="for_checkbox">Require Mixed-Case <small>(both lowercase and uppercase characters)</small></label> </fieldset> <fieldset> <input type="checkbox" name="password[numbers]"<? if ($password["numbers"]) { ?> checked="checked"<? } ?> /> <label class="for_checkbox">Require Numbers</label> </fieldset> <fieldset> <input type="checkbox" name="password[nonalphanumeric]"<? if ($password["nonalphanumeric"]) { ?> checked="checked"<? } ?> /> <label class="for_checkbox">Require Non-Alphanumeric Characters <small>(i.e. $ # ^ *)</small></label> </fieldset> </div> <div class="right"> <fieldset> <h3>Allowed IP Ranges</h3> <p>Enter IP address ranges below to restrict login access.<br />Each line should contain two IP addresses separated by a comma that delineate the beginning and end of the IP ranges.</p> <textarea name="allowed_ips" placeholder="i.e. 192.168.1.1, 192.168.1.128"><?=$allowed_ips?></textarea> </fieldset> <fieldset> <h3>Permanent Ban List</h3> <p>Include a list of IP addresses you wish to permanently ban from logging into the admin area (one per line).</p> <textarea name="banned_ips"><?=$banned_ips?></textarea> </fieldset> </div> </div> </section> <footer> <input type="submit" class="button blue" value="Update Security Settings" /> </footer> </form> </div>
gpl-3.0
OpenAgInitiative/openag-brain
src/openag_brain/settings.py
364
import os import rospy # Turn on logic tracing by creating a '~/TRACE' file. # Output is written to the node's log file. e.g: # tail -f ~/.ros/log/latest/environments-environment_1-recipe_handler_1-6.log TRACE = os.path.isfile(os.path.expanduser('~/TRACE')) def trace(msg, *args): if TRACE: msg = '\nTRACE> ' + msg rospy.logdebug(msg, *args)
gpl-3.0
substratum/substratum
app/src/main/java/projekt/substratum/adapters/fragments/themes/ThemeItem.java
1515
/* * Copyright (c) 2016-2019 Projekt Substratum * This file is part of Substratum. * * SPDX-License-Identifier: GPL-3.0-Or-Later */ package projekt.substratum.adapters.fragments.themes; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.VectorDrawable; import static projekt.substratum.common.References.dynamicallyResize; public class ThemeItem { private String themeName; private String themeAuthor; private String themePackage; private Drawable themeDrawable; private Context themeContext; public String getThemeName() { return this.themeName; } public void setThemeName(String themeName) { this.themeName = themeName; } public String getThemeAuthor() { return this.themeAuthor; } public void setThemeAuthor(String themeAuthor) { this.themeAuthor = themeAuthor; } String getThemePackage() { return this.themePackage; } public void setThemePackage(String themePackage) { this.themePackage = themePackage; } public Drawable getThemeDrawable() { return this.themeDrawable; } public void setThemeDrawable(Drawable drawable) { this.themeDrawable = drawable instanceof VectorDrawable ? drawable : dynamicallyResize(drawable); } public Context getContext() { return this.themeContext; } public void setContext(Context context) { this.themeContext = context; } }
gpl-3.0
pruthvi1991/OpenFOAM-2.3.x
src/OpenFOAM/meshes/primitiveMesh/primitiveMeshFindCell.C
3762
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "primitiveMesh.H" #include "cell.H" #include "boundBox.H" // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // bool Foam::primitiveMesh::pointInCellBB ( const point& p, label celli, scalar tol ) const { boundBox bb ( cells()[celli].points ( faces(), points() ), false ); if (tol > SMALL) { bb = boundBox ( bb.min() - tol*bb.span(), bb.max() + tol*bb.span() ); } return bb.contains(p); } bool Foam::primitiveMesh::pointInCell(const point& p, label celli) const { const labelList& f = cells()[celli]; const labelList& owner = this->faceOwner(); const vectorField& cf = faceCentres(); const vectorField& Sf = faceAreas(); forAll(f, facei) { label nFace = f[facei]; vector proj = p - cf[nFace]; vector normal = Sf[nFace]; if (owner[nFace] != celli) { normal = -normal; } if ((normal & proj) > 0) { return false; } } return true; } Foam::label Foam::primitiveMesh::findNearestCell(const point& location) const { const vectorField& centres = cellCentres(); label nearestCelli = 0; scalar minProximity = magSqr(centres[0] - location); for (label celli = 1; celli < centres.size(); celli++) { scalar proximity = magSqr(centres[celli] - location); if (proximity < minProximity) { nearestCelli = celli; minProximity = proximity; } } return nearestCelli; } Foam::label Foam::primitiveMesh::findCell(const point& location) const { if (nCells() == 0) { return -1; } // Find the nearest cell centre to this location label celli = findNearestCell(location); // If point is in the nearest cell return if (pointInCell(location, celli)) { return celli; } else // point is not in the nearest cell so search all cells { bool cellFound = false; label n = 0; while ((!cellFound) && (n < nCells())) { if (pointInCell(location, n)) { cellFound = true; celli = n; } else { n++; } } if (cellFound) { return celli; } else { return -1; } } } // ************************************************************************* //
gpl-3.0
fxcebx/sumatrapdf
tools/buildgo/main.go
18951
package main import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" "sync" "time" ) /* To run: * install Go - download and run latest installer http://golang.org/doc/install - restart so that PATH changes take place - set GOPATH env variable (e.g. to %USERPROFILE%\src\go) * go run .\tools\buildgo\main.go Some notes on the insanity that is setting up command-line build for both 32 and 64 bit executables. Useful references: https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx https://msdn.microsoft.com/en-us/library/x4d2c09s.aspx http://www.sqlite.org/src/artifact/60dbf6021d3de0a9 -sqlite's win build script %VS140COMNTOOLS%\vsvars32.bat is how set basic env for 32bit builds for VS 2015 (it's VS120COMNTOOLS for VS 2013). That sets VSINSTALLDIR env variable which we can use to setup both 32bit and 64bit builds: %VCINSTALLDIR%\vcvarsall.bat x86_amd64 : 64bit %VCINSTALLDIR%\vcvarsall.bat x86 : 32bit If the OS is 64bit, there are also 64bit compilers that can be selected with: amd64 (for 64bit builds) and amd64_x86 (for 32bit builds). They generate the exact same code but can compiler bigger programs (can use more memory). I'm guessing %VS140COMNTOOLS%\vsvars32.bat is the same as %VSINSTALLDIR%\vcvarsall.bat x86. */ // Platform represents a 32bit vs 64bit platform type Platform int // Config is release, debug etc. type Config int const ( // Platform32Bit describes 32bit build Platform32Bit Platform = 1 // Platform64Bit describes 64bit build Platform64Bit Platform = 2 // ConfigDebug describes debug build ConfigDebug Config = 1 // ConfigRelease describes release build ConfigRelease Config = 2 // ConfigAnalyze describes relase build with /analyze option ConfigAnalyze Config = 3 ) // EnvVar describes an environment variable type EnvVar struct { Name string Val string } // Args represent arguments to a command to run type Args struct { args []string } var ( cachedVcInstallDir string cachedExePaths map[string]string createdDirs map[string]bool fileInfoCache map[string]os.FileInfo alwaysRebuild bool wg sync.WaitGroup sem chan bool mupdfDir string extDir string zlibDir string freetypeDir string jpegTurboDir string openJpegDir string jbig2Dir string mupdfGenDir string nasmPath string cflagsB *Args cflagsOpt *Args cflags *Args zlibCflags *Args // TODO: should be cflagsZlib freetypeCflags *Args jpegTurboCflags *Args jbig2Cflags *Args openJpegCflags *Args jpegTurboNasmFlags *Args mupdfNasmFlags *Args mpudfCflags *Args ldFlags *Args libs *Args ftSrc []string zlibSrc []string jpegTurboSrc []string jpegTurboAsmSrc []string jbig2Src []string openJpegSrc []string mupdfDrawSrc []string mupdfFitzSrc []string mupdfSrc []string muxpsSrc []string mupdfAllSrc []string mudocSrc []string mutoolsSrc []string mutoolAllSrc []string mudrawSrc []string ) func (p Platform) is64() bool { return p == Platform64Bit } func (p Platform) is32() bool { return p == Platform32Bit } func (a *Args) append(toAppend ...string) *Args { return &Args{ args: strConcat(a.args, toAppend), } } func NewArgs(args ...string) *Args { return &Args{ args: args, } } func semEnter() { sem <- true } func semLeave() { <-sem } func fatalf(format string, args ...interface{}) { fmt.Printf(format, args...) os.Exit(1) } func pj(elem ...string) string { return filepath.Join(elem...) } func strConcat(arr1, arr2 []string) []string { var res []string for _, s := range arr1 { res = append(res, s) } for _, s := range arr2 { res = append(res, s) } return res } func replaceExt(path string, newExt string) string { ext := filepath.Ext(path) return path[0:len(path)-len(ext)] + newExt } func fileExists(path string) bool { if _, ok := fileInfoCache[path]; !ok { fi, err := os.Stat(path) if err != nil { return false } fileInfoCache[path] = fi } fi := fileInfoCache[path] return fi.Mode().IsRegular() } func createDirCached(dir string) { if _, ok := createdDirs[dir]; ok { return } if err := os.MkdirAll(dir, 0644); err != nil { fatalf("os.MkdirAll(%s) failed wiht %s\n", dir, err) } } func getModTime(path string, def time.Time) time.Time { if _, ok := fileInfoCache[path]; !ok { fi, err := os.Stat(path) if err != nil { return def } fileInfoCache[path] = fi } fi := fileInfoCache[path] return fi.ModTime() } // maps upper-cased name of env variable to Name/Val func envToMap(env []string) map[string]*EnvVar { res := make(map[string]*EnvVar) for _, v := range env { if len(v) == 0 { continue } parts := strings.SplitN(v, "=", 2) if len(parts) != 2 { } nameUpper := strings.ToUpper(parts[0]) res[nameUpper] = &EnvVar{ Name: parts[0], Val: parts[1], } } return res } func getEnvAfterScript(dir, script string) map[string]*EnvVar { // TODO: maybe use COMSPEC env variable instead of "cmd.exe" (more robust) cmd := exec.Command("cmd.exe", "/c", script+" & set") cmd.Dir = dir fmt.Printf("Executing: %s in %s\n", cmd.Args, cmd.Dir) resBytes, err := cmd.Output() if err != nil { fmt.Printf("failed with %s\n", err) os.Exit(1) } res := string(resBytes) //fmt.Printf("res:\n%s\n", res) parts := strings.Split(res, "\n") if len(parts) == 1 { fmt.Printf("split failed\n") fmt.Printf("res:\n%s\n", res) os.Exit(1) } for idx, env := range parts { env = strings.TrimSpace(env) parts[idx] = env } return envToMap(parts) } func calcEnvAdded(before, after map[string]*EnvVar) map[string]*EnvVar { res := make(map[string]*EnvVar) for k, afterVal := range after { beforeVal := before[k] if beforeVal == nil || beforeVal.Val != afterVal.Val { res[k] = afterVal } } return res } // return value of VCINSTALLDIR env variable after running vsvars32.bat func getVcInstallDir(toolsDir string) string { if cachedVcInstallDir == "" { env := getEnvAfterScript(toolsDir, "vsvars32.bat") val := env["VCINSTALLDIR"] if val == nil { fmt.Printf("no 'VCINSTALLDIR' variable in %s\n", env) os.Exit(1) } cachedVcInstallDir = val.Val } return cachedVcInstallDir } func getEnvForVcTools(vcInstallDir, platform string) []string { //initialEnv := envToMap(os.Environ()) afterEnv := getEnvAfterScript(vcInstallDir, "vcvarsall.bat "+platform) //return calcEnvAdded(initialEnv, afterEnv) var envArr []string for _, envVar := range afterEnv { v := fmt.Sprintf("%s=%s", envVar.Name, envVar.Val) envArr = append(envArr, v) } return envArr } func getEnv32(vcInstallDir string) []string { return getEnvForVcTools(vcInstallDir, "x86") } func getEnv64(vcInstallDir string) []string { return getEnvForVcTools(vcInstallDir, "x86_amd64") } func dumpEnv(env map[string]*EnvVar) { var keys []string for k := range env { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { v := env[k] fmt.Printf("%s: %s\n", v.Name, v.Val) } } func getEnv(platform Platform) []string { initialEnv := envToMap(os.Environ()) vs2013 := initialEnv["VS120COMNTOOLS"] vs2015 := initialEnv["VS140COMNTOOLS"] vsVar := vs2015 if vsVar == nil { vsVar = vs2013 } if vsVar == nil { fmt.Printf("VS120COMNTOOLS or VS140COMNTOOLS not set; VS 2013 or 2015 not installed\n") os.Exit(1) } vcInstallDir := getVcInstallDir(vsVar.Val) switch platform { case Platform32Bit: return getEnv32(vcInstallDir) case Platform64Bit: return getEnv64(vcInstallDir) default: panic("unknown platform") } } func getOutDir(platform Platform, config Config) string { dir := "" switch config { case ConfigRelease: dir = "rel" case ConfigDebug: dir = "dbg" } if platform == Platform64Bit { dir += "64" } return dir } // returns true if dst doesn't exist or is older than src or any of the deps func isOutdated(src, dst string, deps []string) bool { if alwaysRebuild { return true } if !fileExists(dst) { return true } dstTime := getModTime(dst, time.Now()) srcTime := getModTime(src, time.Now()) if srcTime.Sub(dstTime) > 0 { return true } for _, path := range deps { pathTime := getModTime(path, time.Now()) if srcTime.Sub(pathTime) > 0 { return true } } if true { fmt.Printf("%s is up to date\n", dst) } return false } func createDirForFileCached(path string) { createDirCached(filepath.Dir(path)) } func lookupInEnvPathUncached(exeName string, env []string) string { for _, envVar := range env { parts := strings.SplitN(envVar, "=", 2) name := strings.ToLower(parts[0]) if name != "path" { continue } parts = strings.Split(parts[1], ";") for _, dir := range parts { path := filepath.Join(dir, exeName) if fileExists(path) { return path } } fatalf("didn't find %s in '%s'\n", exeName, parts[1]) } return "" } func lookupInEnvPath(exeName string, env []string) string { if _, ok := cachedExePaths[exeName]; !ok { cachedExePaths[exeName] = lookupInEnvPathUncached(exeName, env) fmt.Printf("found %s as %s\n", exeName, cachedExePaths[exeName]) } return cachedExePaths[exeName] } func runExeHelper(exeName string, env []string, args *Args) { exePath := lookupInEnvPath(exeName, env) cmd := exec.Command(exePath, args.args...) cmd.Env = env if true { args := cmd.Args args[0] = exeName fmt.Printf("Running %s\n", args) args[0] = exePath } out, err := cmd.CombinedOutput() if err != nil { fatalf("%s failed with %s, out:\n%s\n", cmd.Args, err, string(out)) } } func runExe(exeName string, env []string, args *Args) { semEnter() wg.Add(1) go func() { runExeHelper(exeName, env, args) semLeave() wg.Done() }() } func rc(src, dst string, env []string, args *Args) { createDirForFileCached(dst) extraArgs := []string{ "/Fo" + dst, src, } args = args.append(extraArgs...) runExe("rc.exe", env, args) } func cl(src, dst string, env []string, args *Args) { if !isOutdated(src, dst, nil) { return } createDirForFileCached(dst) extraArgs := []string{ "/Fo" + dst, src, } args = args.append(extraArgs...) runExe("cl.exe", env, args) } // given ${dir}/foo.rc, returns ${outDir}/${dir}/foo.rc func rcOut(src, outDir string) string { verifyIsRcFile(src) s := filepath.Join(outDir, src) return replaceExt(s, ".res") } func verifyIsRcFile(path string) { s := strings.ToLower(path) if strings.HasSuffix(s, ".rc") { return } fatalf("%s should end in '.rc'\n", path) } func verifyIsCFile(path string) { s := strings.ToLower(path) if strings.HasSuffix(s, ".cpp") { return } if strings.HasSuffix(s, ".c") { return } fatalf("%s should end in '.c' or '.cpp'\n", path) } func clOut(src, outDir string) string { verifyIsCFile(src) s := filepath.Join(outDir, src) return replaceExt(s, ".obj") } func clDir(srcDir string, files []string, outDir string, env []string, args *Args) { for _, f := range files { src := filepath.Join(srcDir, f) dst := clOut(src, outDir) cl(src, dst, env, args) } } func build(platform Platform, config Config) { env := getEnv(platform) //dumpEnv(env) outDir := getOutDir(platform, config) createDirCached(outDir) rcArgs := []string{ "/r", "/D", "DEBUG", "/D", "_DEBUG", } rcSrc := filepath.Join("src", "SumatraPDF.rc") rcDst := rcOut(rcSrc, outDir) rc(rcSrc, rcDst, env, &Args{args: rcArgs}) startArgs := []string{ "/nologo", "/c", "/D", "WIN32", "/D", "_WIN32", "/D", "WINVER=0x0501", "/D", "_WIN32_WINNT=0x0501", "/D", "DEBUG", "/D", "_DEBUG", "/D", "_USING_V110_SDK71_", "/GR-", "/Zi", "/GS", "/Gy", "/GF", "/arch:IA32", "/EHs-c-", "/MTd", "/Od", "/RTCs", "/RTCu", "/WX", "/W4", "/FS", "/wd4100", "/wd4127", "/wd4189", "/wd4428", "/wd4324", "/wd4458", "/wd4838", "/wd4800", "/Imupdf/include", "/Iext/zlib", "/Iext/lzma/C", "/Iext/libwebp", "/Iext/unarr", "/Iext/synctex", "/Iext/libdjvu", "/Iext/CHMLib/src", "/Isrc", "/Isrc/utils", "/Isrc/wingui", "/Isrc/mui", //fmt.Sprintf("/Fo%s\\sumatrapdf", outDir), fmt.Sprintf("/Fd%s\\vc80.pdb", outDir), } initialClArgs := &Args{ args: startArgs, } srcFiles := []string{ "AppPrefs.cpp", "DisplayModel.cpp", "CrashHandler.cpp", "Favorites.cpp", "TextSearch.cpp", "SumatraAbout.cpp", "SumatraAbout2.cpp", "SumatraDialogs.cpp", "SumatraProperties.cpp", "GlobalPrefs.cpp", "PdfSync.cpp", "RenderCache.cpp", "TextSelection.cpp", "WindowInfo.cpp", "ParseCOmmandLine.cpp", "StressTesting.cpp", "AppTools.cpp", "AppUtil.cpp", "TableOfContents.cpp", "Toolbar.cpp", "Print.cpp", "Notifications.cpp", "Selection.cpp", "Search.cpp", "ExternalViewers.cpp", "EbookControls.cpp", "EbookController.cpp", "Doc.cpp", "MuiEbookPageDef.cpp", "PagesLayoutDef.cpp", "Tester.cpp", "Translations.cpp", "Trans_sumatra_txt.cpp", "Tabs.cpp", "FileThumbnails.cpp", "FileHistory.cpp", "ChmModel.cpp", "Caption.cpp", "Canvas.cpp", "TabInfo.cpp", } clDir("src", srcFiles, outDir, env, initialClArgs) if false { regressFiles := []string{ "Regress.cpp", } clDir(pj("src", "regress"), regressFiles, outDir, env, initialClArgs) } srcUtilsFiles := []string{ "FileUtil.cpp", "HttpUtil.cpp", "StrUtil.cpp", "WinUtil.cpp", "GdiPlusUtil.cpp", "FileTransactions.cpp", "Touch.cpp", "TrivialHtmlParser.cpp", "HtmlWindow.cpp", "DirIter.cpp", "BitReader.cpp", "HtmlPullParser.cpp", "HtmlPrettyPrint.cpp", "ThreadUtil.cpp", "DebugLog.cpp", "DbgHelpDyn.cpp", "JsonParser.cpp", "TgaReader.cpp", "HtmlParserLookup.cpp", "ByteOrderDecoder.cpp", "CmdLineParser.cpp", "UITask.cpp", "StrFormat.cpp", "Dict.cpp", "BaseUtil.cpp", "CssParser.cpp", "FileWatcher.cpp", "CryptoUtil.cpp", "StrSlice.cpp", "TxtParser.cpp", "SerializeTxt.cpp", "SquareTreeParser.cpp", "SettingsUtil.cpp", "WebpReader.cpp", "FzImgReader.cpp", "ArchUtil.cpp", "ZipUtil.cpp", "LzmaSimpleArchive.cpp", "Dpi.cpp", } clDir(pj("src", "utils"), srcUtilsFiles, outDir, env, initialClArgs) } func initDirs() { mupdfDir = "mupdf" // we invoke make from inside mupdfDir, so this must be relative to that // TODO: fix that extDir = pj("..", "ext") zlibDir = pj(extDir, "zlib") freetypeDir = pj(extDir, "freetype2") jpegTurboDir = pj(extDir, "libjpeg-turbo") openJpegDir = pj(extDir, "openjpeg") jbig2Dir = pj(extDir, "jbig2dec") // TODO: this is a build artifact so should go under outDir mupdfGenDir = pj(mupdfDir, "generated") } func initFlags(platform Platform, config Config) { cflagsB = NewArgs("/nologo", "/c") if platform.is64() { cflagsB.append("/D", "WIN64", "/D", "_WIN64") } else { cflagsB.append("/D", "WIN32", "/D", "_WIN32") } if config != ConfigAnalyze { // TODO: probably different for vs 2015 cflagsB = cflagsB.append("/D", "_USING_V110_SDK71_") } /* # /WX : treat warnings as errors # /GR- : disable RTTI # /Zi : enable debug information # /GS : enable security checks # /Gy : separate functions for linker # /GF : enable read-only string pooling # /MP : use muliple processors to speed up compilation # Note: /MP not used as it might be causing extreme flakiness on EC2 buildbot */ // for 64bit don't treat warnings as errors // TODO: add an over-ride as STRICT_X64 in makefile if !platform.is32() { cflagsB = cflagsB.append("/WX") } cflagsB = cflagsB.append("/GR-", "/Zi", "/GS", "/Gy", "/GF") // disable the default /arch:SSE2 for 32-bit builds if platform.is32() { cflagsB = cflagsB.append("/arch:IA32") } // /EHs-c- : disable C++ exceptions (generates smaller binaries) cflagsB = cflagsB.append("/EHs-c-") /* # /W4 : bump warnings level from 1 to 4 # warnings unlikely to be turned off due to false positives from using CrashIf() # and various logging functions: # 4100 : unreferenced param # 4127 : conditional expression is constant # 4189 : variable initialized but not referenced # warnings that might not make sense to fix: # 4428 : universal-character-name encountered in source (prevents using "\u202A" etc.) # 4324 : structure was padded due to __declspec(align()) */ cflagsB = cflagsB.append("/W4", "/wd4100", "/wd4127", "/wd4189", "/wd4428", "/wd4324") /* # Those only need to be disabled in VS 2015 # 4458 : declaration of '*' hides class member, a new warning in VS 2015 # unfortunately it's triggered by SDK 10 Gdiplus headers # 4838 : 'conversion from '*' to '*' requires a narrowing conversion # because QITABENT in SDK 10 triggers this TODO: only for VS 2015 */ cflagsB = cflagsB.append("/wd4458", "/wd4838") /* # /Ox : maximum optimizations # /O2 : maximize speed # docs say /Ox better, my tests say /O2 better */ cflagsOpt = cflagsB.append("/O2", "/D", "NDEBUG") ldFlags = NewArgs("/nologo", "/DEBUG", "/RELEASE", "/opt:ref", "/opt:icf") if platform.is32() { ldFlags = ldFlags.append("/MACHINE:X86") } else { ldFlags = ldFlags.append("/MACHINE:X64") } if config != ConfigDebug { // /GL : enable link-time code generation cflags = cflagsOpt.append("/GL") ldFlags = ldFlags.append("/LTCG") // /DYNAMICBASE and /NXCOMPAT for better protection against stack overflows // http://blogs.msdn.com/vcblog/archive/2009/05/21/dynamicbase-and-nxcompat.aspx // We don't use /NXCOMPAT because we need to turn it on/off at runtime ldFlags = ldFlags.append("/DYNAMICBASE", "/FIXED:NO") } else { // /MTd : statically link debug crt (libcmtd.lib) cflagsB = cflagsB.append("/MTd") // /RTCs : stack frame runtime checking // /RTCu : ununitialized local usage checks // /Od : disable optimizations cflags = cflagsB.append("/Od", "/RTCs", "/RTCu") } if platform.is64() { ldFlags = ldFlags.append("/SUBSYSTEM:WINDOWS,5.2") } else { ldFlags = ldFlags.append("/SUBSYSTEM:WINDOWS,5.1") } zlibCflags = cflagsOpt.append("/TC", "/wd4131", "/wd4244", "/wd4996", "/I"+zlibDir) // TODO: } func initSrc() { ftSrc = []string{ "ftbase.c", "ftbbox.c", "ftbitmap.c", "ftgasp.c", "ftglyph.c", "ftinit.c", "ftstroke.c", "ftsynth.c", "ftsystem.c", "fttype1.c", "ftxf86.c", "cff.c", "type1cid.c", "psaux.c", "psnames.c", "smooth.c", "sfnt.c", "truetype.c", "type1.c", "raster.c", "otvalid.c", "ftotval.c", "pshinter.c", "ftgzip.c", } } func main() { cachedExePaths = make(map[string]string) createdDirs = make(map[string]bool) fileInfoCache = make(map[string]os.FileInfo) initDirs() initFlags(Platform64Bit, ConfigRelease) initSrc() n := runtime.NumCPU() fmt.Printf("Using %d goroutines\n", n) sem = make(chan bool, n) timeStart := time.Now() build(Platform32Bit, ConfigRelease) wg.Wait() fmt.Printf("total time: %s\n", time.Since(timeStart)) }
gpl-3.0
GirlsCodePy/girlscode-coursebuilder
modules/core_ui/_static/lightbox/lightbox.js
1549
window.gcb = window.gcb || {}; /** * A class to put up a modal lightbox. Use setContent to set the DOM element * displayed in the lightbox. * * @class */ window.gcb.Lightbox = function() { this._window = $(window); this._container = $('<div class="lightbox"/>'); this._background = $('<div class="background"/>'); this._content = $('<div class="content"/>'); this._container.append(this._background); this._container.append(this._content); this._background.click(this.close.bind(this)); this._container.hide(); } window.gcb.Lightbox.prototype = { /** * Set a DOM element to root the lightbox in. Typically will be document.body. * * @param rootEl {Node} */ bindTo: function(rootEl) { $(rootEl).append(this._container); return this; }, /** * Show the lightbox to the user. */ show: function() { this._container.show(); var top = this._window.scrollTop() + Math.max(8, (this._window.height() - this._content.height()) / 2); var left = this._window.scrollLeft() + Math.max(8, (this._window.width() - this._content.width()) / 2); this._content.css('top', top).css('left', left); return this; }, /** * Close the lightbox and remove it from the DOM. */ close: function() { this._container.remove(); cbHideMsg(); return this; }, /** * Set the content shown in the lightbox. * * @param contentEl {Node or jQuery} */ setContent: function(contentEl) { this._content.empty().append(contentEl); return this; } };
gpl-3.0
grilo/ansible-1
lib/ansible/modules/cloud/ovirt/ovirt_hosts.py
17241
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_hosts short_description: Module to manage hosts in oVirt/RHV version_added: "2.3" author: "Ondra Machacek (@machacekondra)" description: - "Module to manage hosts in oVirt/RHV" options: name: description: - "Name of the host to manage." required: true state: description: - "State which should a host to be in after successful completion." choices: [ 'present', 'absent', 'maintenance', 'upgraded', 'started', 'restarted', 'stopped', 'reinstalled' ] default: present comment: description: - "Description of the host." cluster: description: - "Name of the cluster, where host should be created." address: description: - "Host address. It can be either FQDN (preferred) or IP address." password: description: - "Password of the root. It's required in case C(public_key) is set to I(False)." public_key: description: - "I(True) if the public key should be used to authenticate to host." - "It's required in case C(password) is not set." default: False aliases: ['ssh_public_key'] kdump_integration: description: - "Specify if host will have enabled Kdump integration." choices: ['enabled', 'disabled'] default: enabled spm_priority: description: - "SPM priority of the host. Integer value from 1 to 10, where higher number means higher priority." override_iptables: description: - "If True host iptables will be overridden by host deploy script." - "Note that C(override_iptables) is I(false) by default in oVirt/RHV." force: description: - "If True host will be forcibly moved to desired state." default: False override_display: description: - "Override the display address of all VMs on this host with specified address." kernel_params: description: - "List of kernel boot parameters." - "Following are most common kernel parameters used for host:" - "Hostdev Passthrough & SR-IOV: intel_iommu=on" - "Nested Virtualization: kvm-intel.nested=1" - "Unsafe Interrupts: vfio_iommu_type1.allow_unsafe_interrupts=1" - "PCI Reallocation: pci=realloc" - "C(Note:)" - "Modifying kernel boot parameters settings can lead to a host boot failure. Please consult the product documentation before doing any changes." - "Kernel boot parameters changes require host deploy and restart. The host needs to be I(reinstalled) suceesfully and then to be I(rebooted) for kernel boot parameters to be applied." hosted_engine: description: - "If I(deploy) it means this host should deploy also hosted engine components." - "If I(undeploy) it means this host should un-deploy hosted engine components and this host will not function as part of the High Availability cluster." power_management_enabled: description: - "Enable or disable power management of the host." - "For more comprehensive setup of PM use C(ovirt_host_pm) module." version_added: 2.4 extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Add host with username/password supporting SR-IOV. # Note that override_iptables is false by default in oVirt/RHV: - ovirt_hosts: cluster: Default name: myhost address: 10.34.61.145 password: secret override_iptables: true kernel_params: - intel_iommu=on # Add host using public key - ovirt_hosts: public_key: true cluster: Default name: myhost2 address: 10.34.61.145 override_iptables: true # Deploy hosted engine host - ovirt_hosts: cluster: Default name: myhost2 password: secret address: 10.34.61.145 override_iptables: true hosted_engine: deploy # Maintenance - ovirt_hosts: state: maintenance name: myhost # Restart host using power management: - ovirt_hosts: state: restarted name: myhost # Upgrade host - ovirt_hosts: state: upgraded name: myhost # Reinstall host using public key - ovirt_hosts: state: reinstalled name: myhost public_key: true # Remove host - ovirt_hosts: state: absent name: myhost force: True ''' RETURN = ''' id: description: ID of the host which is managed returned: On success if host is found. type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c host: description: "Dictionary of all the host attributes. Host attributes can be found on your oVirt/RHV instance at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/host." returned: On success if host is found. type: dict ''' import time import traceback try: import ovirtsdk4.types as otypes from ovirtsdk4.types import HostStatus as hoststate except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( BaseModule, check_sdk, create_connection, equal, ovirt_full_argument_spec, wait, ) class HostsModule(BaseModule): def build_entity(self): return otypes.Host( name=self.param('name'), cluster=otypes.Cluster( name=self.param('cluster') ) if self.param('cluster') else None, comment=self.param('comment'), address=self.param('address'), root_password=self.param('password'), ssh=otypes.Ssh( authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY, ) if self.param('public_key') else None, kdump_status=otypes.KdumpStatus( self.param('kdump_integration') ) if self.param('kdump_integration') else None, spm=otypes.Spm( priority=self.param('spm_priority'), ) if self.param('spm_priority') else None, override_iptables=self.param('override_iptables'), display=otypes.Display( address=self.param('override_display'), ) if self.param('override_display') else None, os=otypes.OperatingSystem( custom_kernel_cmdline=' '.join(self.param('kernel_params')), ) if self.param('kernel_params') else None, power_management=otypes.PowerManagement( enabled=self.param('power_management_enabled'), ) if self.param('power_management_enabled') is not None else None, ) def update_check(self, entity): kernel_params = self.param('kernel_params') return ( equal(self.param('comment'), entity.comment) and equal(self.param('kdump_integration'), entity.kdump_status) and equal(self.param('spm_priority'), entity.spm.priority) and equal(self.param('power_management_enabled'), entity.power_management.enabled) and equal(self.param('override_display'), getattr(entity.display, 'address', None)) and equal( sorted(kernel_params) if kernel_params else None, sorted(entity.os.custom_kernel_cmdline.split(' ')) ) ) def pre_remove(self, entity): self.action( entity=entity, action='deactivate', action_condition=lambda h: h.status != hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.MAINTENANCE, ) def post_update(self, entity): if entity.status != hoststate.UP and self.param('state') == 'present': if not self._module.check_mode: self._service.host_service(entity.id).activate() self.changed = True def post_reinstall(self, host): wait( service=self._service.service(host.id), condition=lambda h: h.status != hoststate.MAINTENANCE, fail_condition=failed_state, wait=self.param('wait'), timeout=self.param('timeout'), ) def failed_state(host): return host.status in [ hoststate.ERROR, hoststate.INSTALL_FAILED, hoststate.NON_RESPONSIVE, hoststate.NON_OPERATIONAL, ] def control_state(host_module): host = host_module.search_entity() if host is None: return state = host_module._module.params['state'] host_service = host_module._service.service(host.id) if failed_state(host): # In case host is in INSTALL_FAILED status, we can reinstall it: if hoststate.INSTALL_FAILED == host.status and state != 'reinstalled': raise Exception( "Not possible to manage host '%s' in state '%s'." % ( host.name, host.status ) ) elif host.status in [ hoststate.REBOOT, hoststate.CONNECTING, hoststate.INITIALIZING, hoststate.INSTALLING, hoststate.INSTALLING_OS, ]: wait( service=host_service, condition=lambda host: host.status == hoststate.UP, fail_condition=failed_state, ) elif host.status == hoststate.PREPARING_FOR_MAINTENANCE: wait( service=host_service, condition=lambda host: host.status == hoststate.MAINTENANCE, fail_condition=failed_state, ) return host def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=[ 'present', 'absent', 'maintenance', 'upgraded', 'started', 'restarted', 'stopped', 'reinstalled', ], default='present', ), name=dict(required=True), comment=dict(default=None), cluster=dict(default=None), address=dict(default=None), password=dict(default=None, no_log=True), public_key=dict(default=False, type='bool', aliases=['ssh_public_key']), kdump_integration=dict(default=None, choices=['enabled', 'disabled']), spm_priority=dict(default=None, type='int'), override_iptables=dict(default=None, type='bool'), force=dict(default=False, type='bool'), timeout=dict(default=600, type='int'), override_display=dict(default=None), kernel_params=dict(default=None, type='list'), hosted_engine=dict(default=None, choices=['deploy', 'undeploy']), power_management_enabled=dict(default=None, type='bool'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() hosts_module = HostsModule( connection=connection, module=module, service=hosts_service, ) state = module.params['state'] host = control_state(hosts_module) if state == 'present': hosts_module.create( deploy_hosted_engine=( module.params.get('hosted_engine') == 'deploy' ) if module.params.get('hosted_engine') is not None else None, ) ret = hosts_module.action( action='activate', action_condition=lambda h: h.status == hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.UP, fail_condition=failed_state, ) elif state == 'absent': ret = hosts_module.remove() elif state == 'maintenance': hosts_module.action( action='deactivate', action_condition=lambda h: h.status != hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.MAINTENANCE, fail_condition=failed_state, ) ret = hosts_module.create() elif state == 'upgraded': result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP ret = hosts_module.action( action='upgrade', action_condition=lambda h: h.update_available, wait_condition=lambda h: h.status == result_state, post_action=lambda h: time.sleep(module.params['poll_interval']), fail_condition=failed_state, ) elif state == 'started': ret = hosts_module.action( action='fence', action_condition=lambda h: h.status == hoststate.DOWN, wait_condition=lambda h: h.status in [hoststate.UP, hoststate.MAINTENANCE], fail_condition=failed_state, fence_type='start', ) elif state == 'stopped': hosts_module.action( action='deactivate', action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN], wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN], fail_condition=failed_state, ) ret = hosts_module.action( action='fence', action_condition=lambda h: h.status != hoststate.DOWN, wait_condition=lambda h: h.status == hoststate.DOWN if module.params['wait'] else True, fail_condition=failed_state, fence_type='stop', ) elif state == 'restarted': ret = hosts_module.action( action='fence', wait_condition=lambda h: h.status == hoststate.UP, fail_condition=failed_state, fence_type='restart', ) elif state == 'reinstalled': # Deactivate host if not in maintanence: hosts_module.action( action='deactivate', action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN], wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN], fail_condition=failed_state, ) # Reinstall host: hosts_module.action( action='install', action_condition=lambda h: h.status == hoststate.MAINTENANCE, post_action=hosts_module.post_reinstall, wait_condition=lambda h: h.status == hoststate.MAINTENANCE, fail_condition=failed_state, host=otypes.Host( override_iptables=module.params['override_iptables'], ) if module.params['override_iptables'] else None, root_password=module.params['password'], ssh=otypes.Ssh( authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY, ) if module.params['public_key'] else None, deploy_hosted_engine=( module.params.get('hosted_engine') == 'deploy' ) if module.params.get('hosted_engine') is not None else None, undeploy_hosted_engine=( module.params.get('hosted_engine') == 'undeploy' ) if module.params.get('hosted_engine') is not None else None, ) # Activate host after reinstall: ret = hosts_module.action( action='activate', action_condition=lambda h: h.status == hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.UP, fail_condition=failed_state, ) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == "__main__": main()
gpl-3.0
sbouchex/domoticz
dzVents/runtime/integration-tests/scriptSelectorSwitch.lua
1116
return { on = { devices = { 'vdSelectorSwitch', 'vdScriptStart', 'vdScriptEnd', }, }, data = { switchStates = {initial = ''}, }, logging = { level = domoticz.LOG_DEBUG, marker = 'Selector test', }, execute = function(dz, item) local switch = dz.devices('vdSelectorSwitch') dz.log(item.name .. ' ==>> Selector state: ' .. item.state .. ' ==>> level: ' .. item.level .. ' ==>> date: ' .. dz.data.switchStates, dz.LOG_DEBUG ) if item.name == 'vdScriptStart' then switch.switchSelector(10) switch.switchSelector(30).afterSec(1).forSec(1) dz.devices('vdScriptEnd').switchOn().afterSec(3) elseif item.name == 'vdScriptEnd' then if dz.data.switchStates ~= '103010' then dz.log('Error: ' .. dz.data.switchStates .. ' should be 103010', dz.LOG_DEBUG) else dz.devices('vdScriptOK').switchOn() end elseif item == switch then dz.data.switchStates = dz.data.switchStates .. item.level dz.log(item.name .. ' ==>> Selector state: ' .. item.state .. ' ==>> level: ' .. item.level .. ' ==>> date: ' .. dz.data.switchStates , dz.LOG_DEBUG ) end end }
gpl-3.0
wilmacx/f_mdl32
mod/assign/db/upgrade.php
9708
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Upgrade code for install * * @package mod_assign * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * upgrade this assignment instance - this function could be skipped but it will be needed later * @param int $oldversion The old version of the assign module * @return bool */ function xmldb_assign_upgrade($oldversion) { global $CFG, $DB; $dbman = $DB->get_manager(); if ($oldversion < 2014051201) { // Cleanup bad database records where assignid is missing. $DB->delete_records('assign_user_mapping', array('assignment'=>0)); // Assign savepoint reached. upgrade_mod_savepoint(true, 2014051201, 'assign'); } if ($oldversion < 2014072400) { // Add "latest" column to submissions table to mark the latest attempt. $table = new xmldb_table('assign_submission'); $field = new xmldb_field('latest', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'attemptnumber'); // Conditionally launch add field latest. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Assign savepoint reached. upgrade_mod_savepoint(true, 2014072400, 'assign'); } if ($oldversion < 2014072401) { // Define index latestattempt (not unique) to be added to assign_submission. $table = new xmldb_table('assign_submission'); $index = new xmldb_index('latestattempt', XMLDB_INDEX_NOTUNIQUE, array('assignment', 'userid', 'groupid', 'latest')); // Conditionally launch add index latestattempt. if (!$dbman->index_exists($table, $index)) { $dbman->add_index($table, $index); } // Assign savepoint reached. upgrade_mod_savepoint(true, 2014072401, 'assign'); } if ($oldversion < 2014072405) { // Prevent running this multiple times. $countsql = 'SELECT COUNT(id) FROM {assign_submission} WHERE latest = ?'; $count = $DB->count_records_sql($countsql, array(1)); if ($count == 0) { // Mark the latest attempt for every submission in mod_assign. $maxattemptsql = 'SELECT assignment, userid, groupid, max(attemptnumber) AS maxattempt FROM {assign_submission} GROUP BY assignment, groupid, userid'; $maxattemptidssql = 'SELECT souter.id FROM {assign_submission} souter JOIN (' . $maxattemptsql . ') sinner ON souter.assignment = sinner.assignment AND souter.userid = sinner.userid AND souter.groupid = sinner.groupid AND souter.attemptnumber = sinner.maxattempt'; // We need to avoid using "WHERE ... IN(SELECT ...)" clause with MySQL for performance reason. // TODO MDL-29589 Remove this dbfamily exception when implemented. if ($DB->get_dbfamily() === 'mysql') { $params = array('latest' => 1); $sql = 'UPDATE {assign_submission} INNER JOIN (' . $maxattemptidssql . ') souterouter ON souterouter.id = {assign_submission}.id SET latest = :latest'; $DB->execute($sql, $params); } else { $select = 'id IN(' . $maxattemptidssql . ')'; $DB->set_field_select('assign_submission', 'latest', 1, $select); } // Look for grade records with no submission record. // This is when a teacher has marked a student before they submitted anything. $records = $DB->get_records_sql('SELECT g.id, g.assignment, g.userid FROM {assign_grades} g LEFT JOIN {assign_submission} s ON s.assignment = g.assignment AND s.userid = g.userid WHERE s.id IS NULL'); $submissions = array(); foreach ($records as $record) { $submission = new stdClass(); $submission->assignment = $record->assignment; $submission->userid = $record->userid; $submission->status = 'new'; $submission->groupid = 0; $submission->latest = 1; $submission->timecreated = time(); $submission->timemodified = time(); array_push($submissions, $submission); } $DB->insert_records('assign_submission', $submissions); } // Assign savepoint reached. upgrade_mod_savepoint(true, 2014072405, 'assign'); } // Moodle v2.8.0 release upgrade line. // Put any upgrade step following this. if ($oldversion < 2014122600) { // Delete any entries from the assign_user_flags and assign_user_mapping that are no longer required. if ($DB->get_dbfamily() === 'mysql') { $sql1 = "DELETE {assign_user_flags} FROM {assign_user_flags} LEFT JOIN {assign} ON {assign_user_flags}.assignment = {assign}.id WHERE {assign}.id IS NULL"; $sql2 = "DELETE {assign_user_mapping} FROM {assign_user_mapping} LEFT JOIN {assign} ON {assign_user_mapping}.assignment = {assign}.id WHERE {assign}.id IS NULL"; } else { $sql1 = "DELETE FROM {assign_user_flags} WHERE NOT EXISTS ( SELECT 'x' FROM {assign} WHERE {assign_user_flags}.assignment = {assign}.id)"; $sql2 = "DELETE FROM {assign_user_mapping} WHERE NOT EXISTS ( SELECT 'x' FROM {assign} WHERE {assign_user_mapping}.assignment = {assign}.id)"; } $DB->execute($sql1); $DB->execute($sql2); upgrade_mod_savepoint(true, 2014122600, 'assign'); } if ($oldversion < 2015022300) { // Define field preventsubmissionnotingroup to be added to assign. $table = new xmldb_table('assign'); $field = new xmldb_field('preventsubmissionnotingroup', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'sendstudentnotifications'); // Conditionally launch add field preventsubmissionnotingroup. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Assign savepoint reached. upgrade_mod_savepoint(true, 2015022300, 'assign'); } // Moodle v2.9.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.0.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.1.0 release upgrade line. // Put any upgrade step following this. if ($oldversion < 2016100301) { // Define table assign_overrides to be created. $table = new xmldb_table('assign_overrides'); // Adding fields to table assign_overrides. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('assignid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('sortorder', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('allowsubmissionsfromdate', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('duedate', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('cutoffdate', XMLDB_TYPE_INTEGER, '10', null, null, null, null); // Adding keys to table assign_overrides. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('assignid', XMLDB_KEY_FOREIGN, array('assignid'), 'assign', array('id')); $table->add_key('groupid', XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id')); $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); // Conditionally launch create table for assign_overrides. if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Assign savepoint reached. upgrade_mod_savepoint(true, 2016100301, 'assign'); } return true; }
gpl-3.0
jgjimenez/nethserver-lang
locale/en/server-manager/NethServer_Module_FQDN.php
568
<?php $L['FQDN_Description'] = 'Configure server host and domain name'; $L['FQDN_Tags'] = 'hostname host name domainname domain fqdn'; $L['FQDN_Title'] = 'Server name'; $L['FQDN_header'] = 'Host and domain name'; $L['FQDN_warning_certs_selfsigned'] = "Any change to these fields recreates the SSL certificates and reconfigures all installed packages.\nIt will be asked to reload this page."; $L['FQDN_warning_certs_custom'] = "Any change to these fields reconfigures all installed packages."; $L['SystemName_label'] = 'Hostname'; $L['DomainName_label'] = 'Domain';
gpl-3.0
iamthemuffinman/go-coreutils
sha224sum/sha224sum.go
4040
/* go sha224sum Copyright (c) 2014-2015 Dingjun Fang 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/>. */ /* Sha224sum util implement by go. Usage: sha224sum [OPTION]... [FILE]... Print or check SHA224 (224-bit) checksums. With no FILE, or when FILE is -, read standard input. -b, --binary read in binary mode(default) -c, --check read SHA224 sums from the FILEs and check them -t, --text read in text mode Note: there is no difference between text and binary mode option. The following three options are useful only when verifying checksums: --quiet don't print OK for each successfully verified file --status don't output anything, status code shows success -w, --warn warn about improperly formated checksum lines --help show help and exit --version show version and exit The sums are computed as described in RFC 3874. When checking, the input should be a former output of this program. The default mode is to print a line with checksum, a character indicating type ('*' for binary, ' ' for text), and name for each FILE. */ package main import ( "fmt" cc "github.com/fangdingjun/go-coreutils/md5sum/checksum_common" flag "github.com/ogier/pflag" "os" ) const ( Help = `Usage: sha224sum [OPTION]... [FILE]... Print or check SHA224 (224-bit) checksums. With no FILE, or when FILE is -, read standard input. -b, --binary read in binary mode(default) -c, --check read SHA224 sums from the FILEs and check them -t, --text read in text mode Note: there is no difference between text and binary mode option. The following three options are useful only when verifying checksums: --quiet don't print OK for each successfully verified file --status don't output anything, status code shows success -w, --warn warn about improperly formated checksum lines --help show help and exit --version show version and exit The sums are computed as described in RFC 3874. When checking, the input should be a former output of this program. The default mode is to print a line with checksum, a character indicating type ('*' for binary, ' ' for text), and name for each FILE. ` Version = `sha224sum (Go coreutils) 0.1 Copyright (C) 2015 Dingjun Fang License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. ` ) var ( check_sum = flag.BoolP("check", "c", false, "") no_output = flag.BoolP("quiet", "q", false, "") no_output_s = flag.BoolP("status", "", false, "") show_warn = flag.BoolP("warn", "w", true, "") show_version = flag.BoolP("version", "v", false, "") text_mode = flag.BoolP("text", "t", false, "") binary_mode = flag.BoolP("binary", "b", false, "") ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() /* trust --status and --quiet as the same */ if *no_output_s == true { *no_output = true } has_error := false file_lists := flag.Args() if len(file_lists) == 0 { file_lists = append(file_lists, "-") } switch { case *show_version: fmt.Fprintf(os.Stdout, "%s", Version) os.Exit(0) case *check_sum: if r := cc.CompareChecksum(file_lists, "sha224", !(*no_output), *show_warn); !r { has_error = true } default: if r := cc.GenerateChecksum(file_lists, "sha224"); !r { has_error = true } } if has_error { os.Exit(1) } os.Exit(0) }
gpl-3.0
NikNitro/Python-iBeacon-Scan
sympy/integrals/tests/test_meijerint.py
28412
from sympy import (meijerg, I, S, integrate, Integral, oo, gamma, cosh, sinc, hyperexpand, exp, simplify, sqrt, pi, erf, erfc, sin, cos, exp_polar, polygamma, hyper, log, expand_func) from sympy.integrals.meijerint import (_rewrite_single, _rewrite1, meijerint_indefinite, _inflate_g, _create_lookup_table, meijerint_definite, meijerint_inversion) from sympy.utilities import default_sort_key from sympy.utilities.pytest import slow from sympy.utilities.randtest import (verify_numerically, random_complex_number as randcplx) from sympy.core.compatibility import range from sympy.abc import x, y, a, b, c, d, s, t, z def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) assert e is not None assert isinstance(e[0][0][2], meijerg) assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,)) def tn(expr): assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None t(x, 1, x) t(x**2, 1, x**2) t(x**2 + y*x**2, y + 1, x**2) tn(x**2 + x) tn(x**y) def u(expr, x): from sympy import Add, exp, exp_polar r = _rewrite_single(expr, x) e = Add(*[res[0]*res[2] for res in r[0]]).replace( exp_polar, exp) # XXX Hack? assert verify_numerically(e, expr, x) u(exp(-x)*sin(x), x) # The following has stopped working because hyperexpand changed slightly. # It is probably not worth fixing #u(exp(-x)*sin(x)*cos(x), x) # This one cannot be done numerically, since it comes out as a g-function # of argument 4*pi # NOTE This also tests a bug in inverse mellin transform (which used to # turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of # exp_polar). #u(exp(x)*sin(x), x) assert _rewrite_single(exp(x)*sin(x), x) == \ ([(-sqrt(2)/(2*sqrt(pi)), 0, meijerg(((-S(1)/2, 0, S(1)/4, S(1)/2, S(3)/4), (1,)), ((), (-S(1)/2, 0)), 64*exp_polar(-4*I*pi)/x**4))], True) def test_rewrite1(): assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \ (5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True) def test_meijerint_indefinite_numerically(): def t(fac, arg): g = meijerg([a], [b], [c], [d], arg)*fac subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx()} integral = meijerint_indefinite(g, x) assert integral is not None assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x) t(1, x) t(2, x) t(1, 2*x) t(1, x**2) t(5, x**S('3/2')) t(x**3, x) t(3*x**S('3/2'), 4*x**S('7/3')) def test_meijerint_definite(): v, b = meijerint_definite(x, x, 0, 0) assert v.is_zero and b is True v, b = meijerint_definite(x, x, oo, oo) assert v.is_zero and b is True def test_inflate(): subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx(), y: randcplx()/10} def t(a, b, arg, n): from sympy import Mul m1 = meijerg(a, b, arg) m2 = Mul(*_inflate_g(m1, n)) # NOTE: (the random number)**9 must still be on the principal sheet. # Thus make b&d small to create random numbers of small imaginary part. return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1) assert t([[a], [b]], [[c], [d]], x, 3) assert t([[a, y], [b]], [[c], [d]], x, 3) assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3) def test_recursive(): from sympy import symbols a, b, c = symbols('a b c', positive=True) r = exp(-(x - a)**2)*exp(-(x - b)**2) e = integrate(r, (x, 0, oo), meijerg=True) assert simplify(e.expand()) == ( sqrt(2)*sqrt(pi)*( (erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True) assert simplify(e) == ( sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2 + (2*a + 2*b + c)**2/8)/4) assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 + erf(a + b + c)) assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 - erf(a + b + c)) @slow def test_meijerint(): from sympy import symbols, expand, arg s, t, mu = symbols('s t mu', real=True) assert integrate(meijerg([], [], [0], [], s*t) *meijerg([], [], [mu/2], [-mu/2], t**2/4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma))) assert c == True i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1/(mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) # Note: causes a NaN in _check_antecedents assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2), x, -oo, oo) == (1, True) assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S(1)/2, True) # Test a bug def res(n): return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True) ) == sqrt(2)*sin(a + pi/4)/2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy import And, re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \ (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1)) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S(1)/2)/4).expand() # Test hyperexpand bug. from sympy import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S(1)/2, alpha/2 + 1)), ((0, 0, S(1)/2), (-S(1)/2,)), alpha**S(2)/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S(1)/2)*((-1)**s + 1)*gamma(s/2 + S(1)/2)/2 def test_bessel(): from sympy import besselj, besseli assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo), meijerg=True, conds='none')) == \ 2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b)) assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo), meijerg=True, conds='none')) == 1/(2*a) # TODO more orthogonality integrals assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S(1)/2)), (x, 1, oo), meijerg=True, conds='none') *2/((z/2)**y*sqrt(pi)*gamma(S(1)/2 - y))) == \ besselj(y, z) # Werner Rosenheinrich # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x) assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x) # TODO can do higher powers, but come out as high order ... should they be # reduced to order 0, 1? assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x) assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \ -(besselj(0, x)**2 + besselj(1, x)**2)/2 # TODO more besseli when tables are extended or recursive mellin works assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \ -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \ + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \ -besselj(0, x)**2/2 assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \ x**2*besselj(1, x)**2/2 assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \ (x*besselj(0, x)**2 + x*besselj(1, x)**2 - besselj(0, x)*besselj(1, x)) # TODO how does besselj(0, a*x)*besselj(0, b*x) work? # TODO how does besselj(0, x)**2*besselj(1, x)**2 work? # TODO sin(x)*besselj(0, x) etc come out a mess # TODO can x*log(x)*besselj(0, x) be done? # TODO how does besselj(1, x)*besselj(0, x+a) work? # TODO more indefinite integrals when struve functions etc are implemented # test a substitution assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \ -besselj(0, x**2)/2 def test_inversion(): from sympy import piecewise_fold, besselj, sqrt, sin, cos, Heaviside def inv(f): return piecewise_fold(meijerint_inversion(f, s, t)) assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t) assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t) assert inv(exp(-s)/s) == Heaviside(t - 1) assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t) # Test some antcedents checking. assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None assert inv(exp(s**2)) is None assert meijerint_inversion(exp(-s**2), s, t) is None @slow def test_lookup_table(): from random import uniform, randrange from sympy import Add from sympy.integrals.meijerint import z as z_dummy table = {} _create_lookup_table(table) for _, l in sorted(table.items()): for formula, terms, cond, hint in sorted(l, key=default_sort_key): subs = {} for a in list(formula.free_symbols) + [z_dummy]: if hasattr(a, 'properties') and a.properties: # these Wilds match positive integers subs[a] = randrange(1, 10) else: subs[a] = uniform(1.5, 2.0) if not isinstance(terms, list): terms = terms(subs) # First test that hyperexpand can do this. expanded = [hyperexpand(g) for (_, g) in terms] assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded) # Now test that the meijer g-function is indeed as advertised. expanded = Add(*[f*x for (f, x) in terms]) a, b = formula.n(subs=subs), expanded.n(subs=subs) r = min(abs(a), abs(b)) if r < 1: assert abs(a - b).n() <= 1e-10 else: assert (abs(a - b)/r).n() <= 1e-10 def test_branch_bug(): from sympy import powdenest, lowergamma # TODO combsimp cannot prove that the factor is unity assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x), polar=True) == 2*erf(x**3)*gamma(S(2)/3)/3/gamma(S(5)/3) assert integrate(erf(x**3), x, meijerg=True) == \ 2*x*erf(x**3)*gamma(S(2)/3)/(3*gamma(S(5)/3)) \ - 2*gamma(S(2)/3)*lowergamma(S(2)/3, x**6)/(3*sqrt(pi)*gamma(S(5)/3)) def test_linear_subs(): from sympy import besselj assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x) assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x) @slow def test_probability(): # various integrals from probability theory from sympy.abc import x, y from sympy import symbols, Symbol, Abs, expand_mul, combsimp, powsimp, sin mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, finite=True, positive=True) rate = Symbol('lambda', real=True, positive=True, finite=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \ mu1 assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**2 + sigma1**2 assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**3 + 3*mu1*sigma1**2 assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1 assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2 assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2 assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2 assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ -1 + mu1 + mu2 i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) assert not i.has(Abs) assert simplify(i) == mu1**2 + sigma1**2 assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ sigma2**2 + mu2**2 assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1 assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 1/rate assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 2/rate**2 def E(expr): res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) assert expand_mul(res1) == expand_mul(res2) return res1 assert E(1) == 1 assert E(x*y) == mu1/rate assert E(x*y**2) == mu1**2/rate + sigma1**2/rate ans = sigma1**2 + 1/rate**2 assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans assert simplify(E((x + y)**2) - E(x + y)**2) == ans # Beta' distribution alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) assert integrate(betadist, (x, 0, oo), meijerg=True) == 1 i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate') assert (combsimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta) j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate') assert j[1] == (1 < beta - 1) assert combsimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \ /(beta - 2)/(beta - 1)**2 # Beta distribution # NOTE: this is evaluated using antiderivatives. It also tests that # meijerint_indefinite returns the simplest possible answer. a, b = symbols('a b', positive=True) betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b)) assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1 assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \ a/(a + b) assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \ a*(a + 1)/(a + b)/(a + b + 1) assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \ gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y) # Chi distribution k = Symbol('k', integer=True, positive=True) chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \ sqrt(2)*gamma((k + 1)/2)/gamma(k/2) assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k # Chi^2 distribution chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \ k*(k + 2) assert combsimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)) == 2*sqrt(2)/sqrt(k) # Dagum distribution a, b, p = symbols('a b p', positive=True) # XXX (x/b)**a does not work dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1) assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1 # XXX conditions are a mess arg = x*dagum assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/( (a*p + 1)*gamma(p)) assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/( (a*p + 2)*gamma(p)) # F-distribution d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1 # TODO conditions are a mess assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none') ) == d2/(d2 - 2) assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none') ) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2) # TODO gamma, rayleigh # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(-S(3)/2)*exp(-lamda*(x - mu)**2/x/2/mu**2) mysimp = lambda expr: simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2 # Levi c = Symbol('c', positive=True) assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'), (x, mu, oo)) == 1 # higher moments oo # log-logistic distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \ (1 + x**beta/alpha**beta)**2 assert simplify(integrate(distn, (x, 0, oo))) == 1 # NOTE the conditions are a mess, but correctly state beta > 1 assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \ pi*alpha/beta/sin(pi/beta) # (similar comment for conditions applies) assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \ pi*alpha**y*y/beta/sin(pi*y/beta) # weibull k = Symbol('k', positive=True) n = Symbol('n', positive=True) distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k) assert simplify(integrate(distn, (x, 0, oo))) == 1 assert simplify(integrate(x**n*distn, (x, 0, oo))) == \ lamda**n*gamma(1 + n/k) # rice distribution from sympy import besseli nu, sigma = symbols('nu sigma', positive=True) rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2) assert integrate(rice, (x, 0, oo), meijerg=True) == 1 # can someone verify higher moments? # Laplace distribution mu = Symbol('mu', real=True) b = Symbol('b', positive=True) laplace = exp(-abs(x - mu)/b)/2/b assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1 assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \ 2*b**2 + mu**2 # TODO are there other distributions supported on (-oo, oo) that we can do? # misc tests k = Symbol('k', positive=True) assert combsimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k), (x, 0, oo)))) == polygamma(0, k) def test_expint(): """ Test various exponential integrals. """ from sympy import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi, sin, cos, sinh, cosh, Ei) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewrite(expint).expand(func=True))) == expint(y, z) assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(1, z) assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(2, z).rewrite(Ei).rewrite(expint) assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(3, z).rewrite(Ei).rewrite(expint).expand() t = Symbol('t', positive=True) assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t) assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \ Si(t) - pi/2 assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z) assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z) assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \ I*pi - expint(1, x) assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \ == expint(1, x) - exp(-x)/x - I*pi u = Symbol('u', polar=True) assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Ci(u) assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Chi(u) assert integrate(expint(1, x), x, meijerg=True ).rewrite(expint).expand() == x*expint(1, x) - exp(-x) assert integrate(expint(2, x), x, meijerg=True ).rewrite(expint).expand() == \ -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2 assert simplify(unpolarify(integrate(expint(y, x), x, meijerg=True).rewrite(expint).expand(func=True))) == \ -expint(y + 1, x) assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x) assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u) assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x) assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u) assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4 assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2 def test_messy(): from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise, acoth, E1, besselj, acosh, asin, And, re, fourier_transform, sqrt) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 4*abs(pi**2*s**2) > 1), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True)) def test_issue_6122(): assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \ -I*sqrt(pi)*exp(I*pi/4) def test_issue_6252(): expr = 1/x/(a + b*x)**(S(1)/3) anti = integrate(expr, x, meijerg=True) assert not expr.has(hyper) # XXX the expression is a mess, but actually upon differentiation and # putting in numerical values seems to work... def test_issue_6348(): assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \ == pi*exp(-1) def test_fresnel(): from sympy import fresnels, fresnelc assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x) assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x) def test_issue_6860(): assert meijerint_indefinite(x**x**x, x) is None def test_issue_7337(): f = meijerint_indefinite(x*sqrt(2*x + 3), x).together() assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5 assert f._eval_interval(x, S(-1), S(1)) == S(2)/5 def test_issue_8368(): assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == ( (-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1) def test_issue_10211(): from sympy.abc import h, w assert integrate((1/sqrt(((y-x)**2 + h**2))**3), (x,0,w), (y,0,w)) == \ 2*sqrt(1 + w**2/h**2)/h - 2/h def test_issue_11806(): from sympy import symbols y, L = symbols('y L', positive=True) assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \ 2*L/(y**2*sqrt(L**2 + y**2)) def test_issue_10681(): from sympy import RR from sympy.abc import R, r f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True) g = (1.0/3)*R**1.0*r**3*hyper((-0.5, S(3)/2), (S(5)/2,), r**2*exp_polar(2*I*pi)/R**2) assert RR.almosteq((f/g).n(), 1.0, 1e-12)
gpl-3.0
fgimenez/snappy
interfaces/builtin/dcdbas_control_test.go
2838
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package builtin_test import ( . "gopkg.in/check.v1" "github.com/snapcore/snapd/interfaces" "github.com/snapcore/snapd/interfaces/apparmor" "github.com/snapcore/snapd/interfaces/builtin" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/snap/snaptest" "github.com/snapcore/snapd/testutil" ) type DcdbasControlInterfaceSuite struct { iface interfaces.Interface slot *interfaces.Slot plug *interfaces.Plug } var _ = Suite(&DcdbasControlInterfaceSuite{ iface: builtin.MustInterface("dcdbas-control"), }) func (s *DcdbasControlInterfaceSuite) SetUpTest(c *C) { consumingSnapInfo := snaptest.MockInfo(c, ` name: other apps: app: command: foo plugs: [dcdbas-control] `, nil) s.slot = &interfaces.Slot{ SlotInfo: &snap.SlotInfo{ Snap: &snap.Info{SuggestedName: "core", Type: snap.TypeOS}, Name: "dcdbas-control", Interface: "dcdbas-control", }, } s.plug = &interfaces.Plug{PlugInfo: consumingSnapInfo.Plugs["dcdbas-control"]} } func (s *DcdbasControlInterfaceSuite) TestName(c *C) { c.Assert(s.iface.Name(), Equals, "dcdbas-control") } func (s *DcdbasControlInterfaceSuite) TestSanitizeSlot(c *C) { c.Assert(s.slot.Sanitize(s.iface), IsNil) slot := &interfaces.Slot{SlotInfo: &snap.SlotInfo{ Snap: &snap.Info{SuggestedName: "some-snap"}, Name: "dcdbas-control", Interface: "dcdbas-control", }} c.Assert(slot.Sanitize(s.iface), ErrorMatches, "dcdbas-control slots are reserved for the core snap") } func (s *DcdbasControlInterfaceSuite) TestSanitizePlug(c *C) { c.Assert(s.plug.Sanitize(s.iface), IsNil) } func (s *DcdbasControlInterfaceSuite) TestUsedSecuritySystems(c *C) { // connected plugs have a non-nil security snippet for apparmor apparmorSpec := &apparmor.Specification{} err := apparmorSpec.AddConnectedPlug(s.iface, s.plug, nil, s.slot, nil) c.Assert(err, IsNil) c.Assert(apparmorSpec.SecurityTags(), DeepEquals, []string{"snap.other.app"}) c.Assert(apparmorSpec.SnippetForTag("snap.other.app"), testutil.Contains, `/dcdbas/smi_data`) } func (s *DcdbasControlInterfaceSuite) TestInterfaces(c *C) { c.Check(builtin.Interfaces(), testutil.DeepContains, s.iface) }
gpl-3.0
kira8565/graylog2-server
graylog2-server/src/test/java/org/graylog2/plugin/configuration/ConfigurationRequestTest.java
2716
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.plugin.configuration; import com.google.common.collect.ImmutableMap; import org.graylog2.plugin.configuration.fields.ConfigurationField; import org.graylog2.plugin.configuration.fields.TextField; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ConfigurationRequestTest { private ConfigurationRequest configurationRequest; @Before public void setUp() throws Exception { configurationRequest = new ConfigurationRequest(); } @Test public void putAllRetainsOrder() throws Exception { final ImmutableMap<String, ConfigurationField> fields = ImmutableMap.<String, ConfigurationField>of( "field1", new TextField("field1", "humanName", "defaultValue", "description"), "field2", new TextField("field2", "humanName", "defaultValue", "description"), "field3", new TextField("field3", "humanName", "defaultValue", "description") ); configurationRequest.putAll(fields); assertThat(configurationRequest.getFields().keySet()).containsSequence("field1", "field2", "field3"); } @Test public void addFieldAppendsFieldAtTheEnd() throws Exception { int numberOfFields = 5; for (int i = 0; i < numberOfFields; i++) { configurationRequest.addField(new TextField("field" + i, "humanName", "defaultValue", "description")); } assertThat(configurationRequest.getFields().keySet()) .containsSequence("field0", "field1", "field2", "field3", "field4"); } @Test public void asListRetainsOrder() throws Exception { int numberOfFields = 5; for (int i = 0; i < numberOfFields; i++) { configurationRequest.addField(new TextField("field" + i, "humanName", "defaultValue", "description")); } assertThat(configurationRequest.asList().keySet()) .containsSequence("field0", "field1", "field2", "field3", "field4"); } }
gpl-3.0
MaxOnTheHill/mautic-max
app/bundles/PageBundle/Helper/BuilderTokenHelper.php
2857
<?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\PageBundle\Helper; use Mautic\CoreBundle\Factory\MauticFactory; /** * Class BuilderTokenHelper */ class BuilderTokenHelper { /** * @var MauticFactory */ private $factory; /** * @param MauticFactory $factory */ public function __construct(MauticFactory $factory) { $this->factory = $factory; } /** * @param int $page * * @return string */ public function getTokenContent($page = 1) { //set some permissions $permissions = $this->factory->getSecurity()->isGranted(array( 'page:pages:viewown', 'page:pages:viewother' ), "RETURN_ARRAY"); if (!$permissions['page:pages:viewown'] && !$permissions['page:pages:viewother']) { return; } $session = $this->factory->getSession(); //set limits $limit = 5; $start = ($page === 1) ? 0 : (($page-1) * $limit); if ($start < 0) { $start = 0; } $request = $this->factory->getRequest(); $search = $request->get('search', $session->get('mautic.page.buildertoken.filter', '')); $session->set('mautic.page.buildertoken.filter', $search); $filter = array('string' => $search, 'force' => array( array('column' => 'p.variantParent', 'expr' => 'isNull') )); if (!$permissions['page:pages:viewother']) { $filter['force'][] = array('column' => 'p.createdBy', 'expr' => 'eq', 'value' => $this->factory->getUser()); } $pages = $this->factory->getModel('page')->getEntities( array( 'start' => $start, 'limit' => $limit, 'filter' => $filter, 'orderByDir' => "DESC" )); $count = count($pages); if ($count && $count < ($start + 1)) { //the number of entities are now less then the current page so redirect to the last page if ($count === 1) { $page = 1; } else { $page = (floor($limit / $count)) ? : 1; } $session->set('mautic.page.buildertoken.page', $page); } return $this->factory->getTemplating()->render('MauticPageBundle:SubscribedEvents\BuilderToken:list.html.php', array( 'items' => $pages, 'page' => $page, 'limit' => $limit, 'totalCount' => $count, 'tmpl' => $request->get('tmpl', 'index'), 'searchValue' => $search )); } }
gpl-3.0
dslab-epfl/accessibility-checker
mod/quiz/mod_form.php
28414
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines the quiz module ettings form. * * @package mod * @subpackage quiz * @copyright 2006 Jamie Pratt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->dirroot . '/course/moodleform_mod.php'); require_once($CFG->dirroot . '/mod/quiz/locallib.php'); /** * Settings form for the quiz module. * * @copyright 2006 Jamie Pratt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class mod_quiz_mod_form extends moodleform_mod { /** @var array options to be used with date_time_selector fields in the quiz. */ public static $datefieldoptions = array('optional' => true, 'step' => 1); protected $_feedbacks; protected static $reviewfields = array(); // Initialised in the constructor. public function __construct($current, $section, $cm, $course) { self::$reviewfields = array( 'attempt' => array('theattempt', 'quiz'), 'correctness' => array('whethercorrect', 'question'), 'marks' => array('marks', 'quiz'), 'specificfeedback' => array('specificfeedback', 'question'), 'generalfeedback' => array('generalfeedback', 'question'), 'rightanswer' => array('rightanswer', 'question'), 'overallfeedback' => array('reviewoverallfeedback', 'quiz'), ); parent::__construct($current, $section, $cm, $course); } protected function definition() { global $COURSE, $CFG, $DB, $PAGE; $quizconfig = get_config('quiz'); $mform = $this->_form; // ------------------------------------------------------------------------------- $mform->addElement('header', 'general', get_string('general', 'form')); // Name. $mform->addElement('text', 'name', get_string('name'), array('size'=>'64')); if (!empty($CFG->formatstringstriptags)) { $mform->setType('name', PARAM_TEXT); } else { $mform->setType('name', PARAM_CLEANHTML); } $mform->addRule('name', null, 'required', null, 'client'); $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); // Introduction. $this->add_intro_editor(false, get_string('introduction', 'quiz')); // ------------------------------------------------------------------------------- $mform->addElement('header', 'timing', get_string('timing', 'quiz')); // Open and close dates. $mform->addElement('date_time_selector', 'timeopen', get_string('quizopen', 'quiz'), self::$datefieldoptions); $mform->addHelpButton('timeopen', 'quizopenclose', 'quiz'); $mform->addElement('date_time_selector', 'timeclose', get_string('quizclose', 'quiz'), self::$datefieldoptions); // Time limit. $mform->addElement('duration', 'timelimit', get_string('timelimit', 'quiz'), array('optional' => true)); $mform->addHelpButton('timelimit', 'timelimit', 'quiz'); $mform->setAdvanced('timelimit', $quizconfig->timelimit_adv); $mform->setDefault('timelimit', $quizconfig->timelimit); // What to do with overdue attempts. $mform->addElement('select', 'overduehandling', get_string('overduehandling', 'quiz'), quiz_get_overdue_handling_options()); $mform->addHelpButton('overduehandling', 'overduehandling', 'quiz'); $mform->setAdvanced('overduehandling', $quizconfig->overduehandling_adv); $mform->setDefault('overduehandling', $quizconfig->overduehandling); // TODO Formslib does OR logic on disableif, and we need AND logic here. // $mform->disabledIf('overduehandling', 'timelimit', 'eq', 0); // $mform->disabledIf('overduehandling', 'timeclose', 'eq', 0); // Grace period time. $mform->addElement('duration', 'graceperiod', get_string('graceperiod', 'quiz'), array('optional' => true)); $mform->addHelpButton('graceperiod', 'graceperiod', 'quiz'); $mform->setAdvanced('graceperiod', $quizconfig->graceperiod_adv); $mform->setDefault('graceperiod', $quizconfig->graceperiod); $mform->disabledIf('graceperiod', 'overduehandling', 'neq', 'graceperiod'); // ------------------------------------------------------------------------------- // Grade settings. $this->standard_grading_coursemodule_elements(); $mform->removeElement('grade'); $mform->addElement('hidden', 'grade', $quizconfig->maximumgrade); $mform->setType('grade', PARAM_FLOAT); // Number of attempts. $attemptoptions = array('0' => get_string('unlimited')); for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) { $attemptoptions[$i] = $i; } $mform->addElement('select', 'attempts', get_string('attemptsallowed', 'quiz'), $attemptoptions); $mform->setAdvanced('attempts', $quizconfig->attempts_adv); $mform->setDefault('attempts', $quizconfig->attempts); // Grading method. $mform->addElement('select', 'grademethod', get_string('grademethod', 'quiz'), quiz_get_grading_options()); $mform->addHelpButton('grademethod', 'grademethod', 'quiz'); $mform->setAdvanced('grademethod', $quizconfig->grademethod_adv); $mform->setDefault('grademethod', $quizconfig->grademethod); $mform->disabledIf('grademethod', 'attempts', 'eq', 1); // ------------------------------------------------------------------------------- $mform->addElement('header', 'layouthdr', get_string('layout', 'quiz')); // Shuffle questions. $shuffleoptions = array( 0 => get_string('asshownoneditscreen', 'quiz'), 1 => get_string('shuffledrandomly', 'quiz') ); $mform->addElement('select', 'shufflequestions', get_string('questionorder', 'quiz'), $shuffleoptions, array('id' => 'id_shufflequestions')); $mform->setAdvanced('shufflequestions', $quizconfig->shufflequestions_adv); $mform->setDefault('shufflequestions', $quizconfig->shufflequestions); // Questions per page. $pageoptions = array(); $pageoptions[0] = get_string('neverallononepage', 'quiz'); $pageoptions[1] = get_string('everyquestion', 'quiz'); for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) { $pageoptions[$i] = get_string('everynquestions', 'quiz', $i); } $pagegroup = array(); $pagegroup[] = $mform->createElement('select', 'questionsperpage', get_string('newpage', 'quiz'), $pageoptions, array('id' => 'id_questionsperpage')); $mform->setDefault('questionsperpage', $quizconfig->questionsperpage); if (!empty($this->_cm)) { $pagegroup[] = $mform->createElement('checkbox', 'repaginatenow', '', get_string('repaginatenow', 'quiz'), array('id' => 'id_repaginatenow')); $mform->disabledIf('repaginatenow', 'shufflequestions', 'eq', 1); $PAGE->requires->js('/question/qengine.js'); $module = array( 'name' => 'mod_quiz_edit', 'fullpath' => '/mod/quiz/edit.js', 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'), 'strings' => array(), 'async' => false, ); $PAGE->requires->js_init_call('quiz_settings_init', null, false, $module); } $mform->addGroup($pagegroup, 'questionsperpagegrp', get_string('newpage', 'quiz'), null, false); $mform->addHelpButton('questionsperpagegrp', 'newpage', 'quiz'); $mform->setAdvanced('questionsperpagegrp', $quizconfig->questionsperpage_adv); // Navigation method. $mform->addElement('select', 'navmethod', get_string('navmethod', 'quiz'), quiz_get_navigation_options()); $mform->addHelpButton('navmethod', 'navmethod', 'quiz'); $mform->setAdvanced('navmethod', $quizconfig->navmethod_adv); $mform->setDefault('navmethod', $quizconfig->navmethod); // ------------------------------------------------------------------------------- $mform->addElement('header', 'interactionhdr', get_string('questionbehaviour', 'quiz')); // Shuffle within questions. $mform->addElement('selectyesno', 'shuffleanswers', get_string('shufflewithin', 'quiz')); $mform->addHelpButton('shuffleanswers', 'shufflewithin', 'quiz'); $mform->setAdvanced('shuffleanswers', $quizconfig->shuffleanswers_adv); $mform->setDefault('shuffleanswers', $quizconfig->shuffleanswers); // How questions behave (question behaviour). if (!empty($this->current->preferredbehaviour)) { $currentbehaviour = $this->current->preferredbehaviour; } else { $currentbehaviour = ''; } $behaviours = question_engine::get_behaviour_options($currentbehaviour); $mform->addElement('select', 'preferredbehaviour', get_string('howquestionsbehave', 'question'), $behaviours); $mform->addHelpButton('preferredbehaviour', 'howquestionsbehave', 'question'); $mform->setDefault('preferredbehaviour', $quizconfig->preferredbehaviour); // Each attempt builds on last. $mform->addElement('selectyesno', 'attemptonlast', get_string('eachattemptbuildsonthelast', 'quiz')); $mform->addHelpButton('attemptonlast', 'eachattemptbuildsonthelast', 'quiz'); $mform->setAdvanced('attemptonlast', $quizconfig->attemptonlast_adv); $mform->setDefault('attemptonlast', $quizconfig->attemptonlast); $mform->disabledIf('attemptonlast', 'attempts', 'eq', 1); // ------------------------------------------------------------------------------- $mform->addElement('header', 'reviewoptionshdr', get_string('reviewoptionsheading', 'quiz')); $mform->addHelpButton('reviewoptionshdr', 'reviewoptionsheading', 'quiz'); // Review options. $this->add_review_options_group($mform, $quizconfig, 'during', mod_quiz_display_options::DURING, true); $this->add_review_options_group($mform, $quizconfig, 'immediately', mod_quiz_display_options::IMMEDIATELY_AFTER); $this->add_review_options_group($mform, $quizconfig, 'open', mod_quiz_display_options::LATER_WHILE_OPEN); $this->add_review_options_group($mform, $quizconfig, 'closed', mod_quiz_display_options::AFTER_CLOSE); foreach ($behaviours as $behaviour => $notused) { $unusedoptions = question_engine::get_behaviour_unused_display_options($behaviour); foreach ($unusedoptions as $unusedoption) { $mform->disabledIf($unusedoption . 'during', 'preferredbehaviour', 'eq', $behaviour); } } $mform->disabledIf('attemptduring', 'preferredbehaviour', 'neq', 'wontmatch'); $mform->disabledIf('overallfeedbackduring', 'preferredbehaviour', 'neq', 'wontmatch'); // ------------------------------------------------------------------------------- $mform->addElement('header', 'display', get_string('display', 'form')); // Show user picture. $mform->addElement('select', 'showuserpicture', get_string('showuserpicture', 'quiz'), array( QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'), QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'), QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'))); $mform->addHelpButton('showuserpicture', 'showuserpicture', 'quiz'); $mform->setAdvanced('showuserpicture', $quizconfig->showuserpicture_adv); $mform->setDefault('showuserpicture', $quizconfig->showuserpicture); // Overall decimal points. $options = array(); for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) { $options[$i] = $i; } $mform->addElement('select', 'decimalpoints', get_string('decimalplaces', 'quiz'), $options); $mform->addHelpButton('decimalpoints', 'decimalplaces', 'quiz'); $mform->setAdvanced('decimalpoints', $quizconfig->decimalpoints_adv); $mform->setDefault('decimalpoints', $quizconfig->decimalpoints); // Question decimal points. $options = array(-1 => get_string('sameasoverall', 'quiz')); for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) { $options[$i] = $i; } $mform->addElement('select', 'questiondecimalpoints', get_string('decimalplacesquestion', 'quiz'), $options); $mform->addHelpButton('questiondecimalpoints', 'decimalplacesquestion', 'quiz'); $mform->setAdvanced('questiondecimalpoints', $quizconfig->questiondecimalpoints_adv); $mform->setDefault('questiondecimalpoints', $quizconfig->questiondecimalpoints); // Show blocks during quiz attempt. $mform->addElement('selectyesno', 'showblocks', get_string('showblocks', 'quiz')); $mform->addHelpButton('showblocks', 'showblocks', 'quiz'); $mform->setAdvanced('showblocks', $quizconfig->showblocks_adv); $mform->setDefault('showblocks', $quizconfig->showblocks); // ------------------------------------------------------------------------------- $mform->addElement('header', 'security', get_string('extraattemptrestrictions', 'quiz')); // Require password to begin quiz attempt. $mform->addElement('passwordunmask', 'quizpassword', get_string('requirepassword', 'quiz')); $mform->setType('quizpassword', PARAM_TEXT); $mform->addHelpButton('quizpassword', 'requirepassword', 'quiz'); $mform->setAdvanced('quizpassword', $quizconfig->password_adv); $mform->setDefault('quizpassword', $quizconfig->password); // IP address. $mform->addElement('text', 'subnet', get_string('requiresubnet', 'quiz')); $mform->setType('subnet', PARAM_TEXT); $mform->addHelpButton('subnet', 'requiresubnet', 'quiz'); $mform->setAdvanced('subnet', $quizconfig->subnet_adv); $mform->setDefault('subnet', $quizconfig->subnet); // Enforced time delay between quiz attempts. $mform->addElement('duration', 'delay1', get_string('delay1st2nd', 'quiz'), array('optional' => true)); $mform->addHelpButton('delay1', 'delay1st2nd', 'quiz'); $mform->setAdvanced('delay1', $quizconfig->delay1_adv); $mform->setDefault('delay1', $quizconfig->delay1); $mform->disabledIf('delay1', 'attempts', 'eq', 1); $mform->addElement('duration', 'delay2', get_string('delaylater', 'quiz'), array('optional' => true)); $mform->addHelpButton('delay2', 'delaylater', 'quiz'); $mform->setAdvanced('delay2', $quizconfig->delay2_adv); $mform->setDefault('delay2', $quizconfig->delay2); $mform->disabledIf('delay2', 'attempts', 'eq', 1); $mform->disabledIf('delay2', 'attempts', 'eq', 2); // Browser security choices. $mform->addElement('select', 'browsersecurity', get_string('browsersecurity', 'quiz'), quiz_access_manager::get_browser_security_choices()); $mform->addHelpButton('browsersecurity', 'browsersecurity', 'quiz'); $mform->setAdvanced('browsersecurity', $quizconfig->browsersecurity_adv); $mform->setDefault('browsersecurity', $quizconfig->browsersecurity); // Any other rule plugins. quiz_access_manager::add_settings_form_fields($this, $mform); // ------------------------------------------------------------------------------- $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'quiz')); $mform->addHelpButton('overallfeedbackhdr', 'overallfeedback', 'quiz'); if (isset($this->current->grade)) { $needwarning = $this->current->grade === 0; } else { $needwarning = $quizconfig->maximumgrade == 0; } if ($needwarning) { $mform->addElement('static', 'nogradewarning', '', get_string('nogradewarning', 'quiz')); } $mform->addElement('static', 'gradeboundarystatic1', get_string('gradeboundary', 'quiz'), '100%'); $repeatarray = array(); $repeatedoptions = array(); $repeatarray[] = $mform->createElement('editor', 'feedbacktext', get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true, 'context' => $this->context)); $repeatarray[] = $mform->createElement('text', 'feedbackboundaries', get_string('gradeboundary', 'quiz'), array('size' => 10)); $repeatedoptions['feedbacktext']['type'] = PARAM_RAW; $repeatedoptions['feedbackboundaries']['type'] = PARAM_RAW; if (!empty($this->_instance)) { $this->_feedbacks = $DB->get_records('quiz_feedback', array('quizid' => $this->_instance), 'mingrade DESC'); } else { $this->_feedbacks = array(); } $numfeedbacks = max(count($this->_feedbacks) * 1.5, 5); $nextel = $this->repeat_elements($repeatarray, $numfeedbacks - 1, $repeatedoptions, 'boundary_repeats', 'boundary_add_fields', 3, get_string('addmoreoverallfeedbacks', 'quiz'), true); // Put some extra elements in before the button. $mform->insertElementBefore($mform->createElement('editor', "feedbacktext[$nextel]", get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true, 'context' => $this->context)), 'boundary_add_fields'); $mform->insertElementBefore($mform->createElement('static', 'gradeboundarystatic2', get_string('gradeboundary', 'quiz'), '0%'), 'boundary_add_fields'); // Add the disabledif rules. We cannot do this using the $repeatoptions parameter to // repeat_elements because we don't want to dissable the first feedbacktext. for ($i = 0; $i < $nextel; $i++) { $mform->disabledIf('feedbackboundaries[' . $i . ']', 'grade', 'eq', 0); $mform->disabledIf('feedbacktext[' . ($i + 1) . ']', 'grade', 'eq', 0); } // ------------------------------------------------------------------------------- $this->standard_coursemodule_elements(); // Check and act on whether setting outcomes is considered an advanced setting. $mform->setAdvanced('modoutcomes', !empty($quizconfig->outcomes_adv)); // The standard_coursemodule_elements method sets this to 100, but the // quiz has its own setting, so use that. $mform->setDefault('grade', $quizconfig->maximumgrade); // ------------------------------------------------------------------------------- $this->add_action_buttons(); } protected function add_review_options_group($mform, $quizconfig, $whenname, $when, $withhelp = false) { global $OUTPUT; $group = array(); foreach (self::$reviewfields as $field => $string) { list($identifier, $component) = $string; $label = get_string($identifier, $component); if ($withhelp) { $label .= ' ' . $OUTPUT->help_icon($identifier, $component); } $group[] = $mform->createElement('checkbox', $field . $whenname, '', $label); } $mform->addGroup($group, $whenname . 'optionsgrp', get_string('review' . $whenname, 'quiz'), null, false); foreach (self::$reviewfields as $field => $notused) { $cfgfield = 'review' . $field; if ($quizconfig->$cfgfield & $when) { $mform->setDefault($field . $whenname, 1); } else { $mform->setDefault($field . $whenname, 0); } } if ($whenname != 'during') { $mform->disabledIf('correctness' . $whenname, 'attempt' . $whenname); $mform->disabledIf('specificfeedback' . $whenname, 'attempt' . $whenname); $mform->disabledIf('generalfeedback' . $whenname, 'attempt' . $whenname); $mform->disabledIf('rightanswer' . $whenname, 'attempt' . $whenname); } } protected function preprocessing_review_settings(&$toform, $whenname, $when) { foreach (self::$reviewfields as $field => $notused) { $fieldname = 'review' . $field; if (array_key_exists($fieldname, $toform)) { $toform[$field . $whenname] = $toform[$fieldname] & $when; } } } public function data_preprocessing(&$toform) { if (isset($toform['grade'])) { // Convert to a real number, so we don't get 0.0000. $toform['grade'] = $toform['grade'] + 0; } if (count($this->_feedbacks)) { $key = 0; foreach ($this->_feedbacks as $feedback) { $draftid = file_get_submitted_draft_itemid('feedbacktext['.$key.']'); $toform['feedbacktext['.$key.']']['text'] = file_prepare_draft_area( $draftid, // Draftid. $this->context->id, // Context. 'mod_quiz', // Component. 'feedback', // Filarea. !empty($feedback->id) ? (int) $feedback->id : null, // Itemid. null, $feedback->feedbacktext // Text. ); $toform['feedbacktext['.$key.']']['format'] = $feedback->feedbacktextformat; $toform['feedbacktext['.$key.']']['itemid'] = $draftid; if ($toform['grade'] == 0) { // When a quiz is un-graded, there can only be one lot of // feedback. If the quiz previously had a maximum grade and // several lots of feedback, we must now avoid putting text // into input boxes that are disabled, but which the // validation will insist are blank. break; } if ($feedback->mingrade > 0) { $toform['feedbackboundaries['.$key.']'] = (100.0 * $feedback->mingrade / $toform['grade']) . '%'; } $key++; } } if (isset($toform['timelimit'])) { $toform['timelimitenable'] = $toform['timelimit'] > 0; } $this->preprocessing_review_settings($toform, 'during', mod_quiz_display_options::DURING); $this->preprocessing_review_settings($toform, 'immediately', mod_quiz_display_options::IMMEDIATELY_AFTER); $this->preprocessing_review_settings($toform, 'open', mod_quiz_display_options::LATER_WHILE_OPEN); $this->preprocessing_review_settings($toform, 'closed', mod_quiz_display_options::AFTER_CLOSE); $toform['attemptduring'] = true; $toform['overallfeedbackduring'] = false; // Password field - different in form to stop browsers that remember // passwords from getting confused. if (isset($toform['password'])) { $toform['quizpassword'] = $toform['password']; unset($toform['password']); } // Load any settings belonging to the access rules. if (!empty($toform['instance'])) { $accesssettings = quiz_access_manager::load_settings($toform['instance']); foreach ($accesssettings as $name => $value) { $toform[$name] = $value; } } } public function validation($data, $files) { $errors = parent::validation($data, $files); // Check open and close times are consistent. if ($data['timeopen'] != 0 && $data['timeclose'] != 0 && $data['timeclose'] < $data['timeopen']) { $errors['timeclose'] = get_string('closebeforeopen', 'quiz'); } // Check that the grace period is not too short. if ($data['overduehandling'] == 'graceperiod') { $graceperiodmin = get_config('quiz', 'graceperiodmin'); if ($data['graceperiod'] <= $graceperiodmin) { $errors['graceperiod'] = get_string('graceperiodtoosmall', 'quiz', format_time($graceperiodmin)); } } // Check the boundary value is a number or a percentage, and in range. $i = 0; while (!empty($data['feedbackboundaries'][$i] )) { $boundary = trim($data['feedbackboundaries'][$i]); if (strlen($boundary) > 0) { if ($boundary[strlen($boundary) - 1] == '%') { $boundary = trim(substr($boundary, 0, -1)); if (is_numeric($boundary)) { $boundary = $boundary * $data['grade'] / 100.0; } else { $errors["feedbackboundaries[$i]"] = get_string('feedbackerrorboundaryformat', 'quiz', $i + 1); } } else if (!is_numeric($boundary)) { $errors["feedbackboundaries[$i]"] = get_string('feedbackerrorboundaryformat', 'quiz', $i + 1); } } if (is_numeric($boundary) && $boundary <= 0 || $boundary >= $data['grade'] ) { $errors["feedbackboundaries[$i]"] = get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1); } if (is_numeric($boundary) && $i > 0 && $boundary >= $data['feedbackboundaries'][$i - 1]) { $errors["feedbackboundaries[$i]"] = get_string('feedbackerrororder', 'quiz', $i + 1); } $data['feedbackboundaries'][$i] = $boundary; $i += 1; } $numboundaries = $i; // Check there is nothing in the remaining unused fields. if (!empty($data['feedbackboundaries'])) { for ($i = $numboundaries; $i < count($data['feedbackboundaries']); $i += 1) { if (!empty($data['feedbackboundaries'][$i] ) && trim($data['feedbackboundaries'][$i] ) != '') { $errors["feedbackboundaries[$i]"] = get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1); } } } for ($i = $numboundaries + 1; $i < count($data['feedbacktext']); $i += 1) { if (!empty($data['feedbacktext'][$i]['text']) && trim($data['feedbacktext'][$i]['text'] ) != '') { $errors["feedbacktext[$i]"] = get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1); } } // Any other rule plugins. $errors = quiz_access_manager::validate_settings_form_fields($errors, $data, $files, $this); return $errors; } }
gpl-3.0
fenway-libraries-online/coral-resources
ajax_htmldata/getGeneralSubjectDisplay.php
1353
<?php $className = $_GET['className']; $instanceArray = array(); $obj = new $className(); $instanceArray = $obj->allAsArray(); echo "<div class='adminRightHeader'>" . preg_replace("/[A-Z]/", " \\0" , $className) . "</div>"; if (count($instanceArray) > 0){ ?> <table class='linedDataTable'> <tr> <th style='width:100%;'>Value</th> <th>&nbsp;</th> <th>&nbsp;</th> </tr> <?php foreach($instanceArray as $instance) { echo "<tr>"; echo "<td>" . $instance['shortName'] . "</td>"; echo "<td><a href='ajax_forms.php?action=getGeneralSubjectUpdateForm&className=" . $className . "&updateID=" . $instance[lcfirst($className) . 'ID'] . "&height=128&width=260&modal=true' class='thickbox'><img src='images/edit.gif' alt='edit' title='edit'></a></td>"; echo "<td><a href='javascript:void(0);' class='removeData' cn='" . $className . "' id='" . $instance[lcfirst($className) . 'ID'] . "'><img src='images/cross.gif' alt='remove' title='remove'></a></td>"; echo "</tr>"; } ?> </table> <?php }else{ echo "(none found)<br />"; } echo "<a href='ajax_forms.php?action=getAdminUpdateForm&className=" . $className . "&updateID=&height=128&width=260&modal=true' class='thickbox'>add new " . strtolower(preg_replace("/[A-Z]/", " \\0" , lcfirst($className))) . "</a>"; ?>
gpl-3.0
rmackay9/rmackay9-ardupilot
libraries/AP_Scripting/examples/plane-wind-fs.lua
15565
-- Adds a smart failsafe that accounts for how far the plane is from home -- the average battery consumption, and the wind to decide when to failsafe -- -- CAUTION: This script only works for Plane -- store the batt info as { instance, filtered, capacity, margin_mah } -- instance: the battery monitor instance (zero indexed) -- filtered: internal variable for current draw -- capacity: internal variable populated from battery monitor capacity param -- margin_mah: the mah to be remaining when you reach home and use the time margin, note that this is on top of CRT_MAH local batt_info = { {0, 0, 0, 0}, -- main battery -- add more batteries to monitor here } local margin = 30 -- margin in seconds of flight time that should remain once we have reached local time_SF = 1 -- the return time safety factor, 1.1 gives 10% extra time for return flight local filter = 0.9 -- filter gain local min_flying_time = 30 -- seconds, must have been flying in a none Qmode above the min alt for this long before script will start sampling current local print_time = 15 -- seconds between update prints (set to zero to disable) local alt_min = 0 -- the minimum altitude above home the script will start working at, zero disables -- if true current draw is normalized with dynamic pressure -- this gives better prediction of current draws at other airspeeds -- airspeed sensor recommended local airspeed_normalize = false -- hard code wind to match SITL -- should get exact return time estimates < +- 5 seconds local SITL_wind = false -- Read in required params local value = param:get('TRIM_ARSPD_CM') if value then air_speed = value / 100 else error('LUA: get TRIM_ARSPD_CM failed') end local value = param:get('ARSPD_FBW_MIN') if value then min_air_speed = value else error('LUA: get ARSPD_FBW_MIN failed') end local value = param:get('MIN_GNDSPD_CM') if value then min_ground_speed = value / 100 else error('LUA: get MIN_GNDSPD_CM failed') end local value = param:get('LIM_ROLL_CD') if value then max_bank_angle = value / 100 else error('LUA: get LIM_ROLL_CD failed') end -- https://en.wikipedia.org/wiki/Standard_rate_turn#Radius_of_turn_formula -- the radius is equal to the circumference per 1 radian local turn_rad = (air_speed^2) / (9.81 * math.tan(math.rad(max_bank_angle))) -- Read the radius we expect to circle at when we get home local home_reached_rad local value = param:get('RTL_RADIUS') if value then value = math.abs(value) if value > 0 then home_reached_rad = math.abs(value) * 2 else value = param:get('WP_LOITER_RAD') if value then home_reached_rad = math.abs(value) * 2 else error('LUA: get WP_LOITER_RAD failed') end end else error('LUA: get RTL_RADIUS failed') end -- internal global variables local return_start local return_distance local return_amps local trigger_instance = batt_info[1][1] local last_print = 0 local timer_start_time = 0 local timer_active = true -- calculates the amount of time it will take for the vehicle to return home -- returns 0 if there is no position, wind or home available -- returns a negative number if it will take excessively long time, or is impossible -- otherwise returns the time in seconds to get back local function time_to_home() local home = ahrs:get_home() local position = ahrs:get_location() local wind = ahrs:wind_estimate() if home and position and wind then local bearing = position:get_bearing(home) -- wind is in NED, convert for readability local wind_north = wind:x() local wind_east = wind:y() -- hard code wind for testing if SITL_wind then -- only safe to read from params at a high rate because we are in SITL -- don't do this on a real vehicle wind_speed = param:get('SIM_WIND_SPD') wind_dir = param:get('SIM_WIND_DIR') if wind_speed and wind_dir then wind_dir = math.rad(wind_dir) wind_north = -math.cos(wind_dir) * wind_speed wind_east = -math.sin(wind_dir) * wind_speed else error('Could not read SITL wind') end end --gcs:send_text(0, string.format("Wind: north %0.2f, east %0.2f",wind_north,wind_east)) -- rotate the wind vector inline with the home bearing local tail_wind = math.sin(bearing) * wind_east + math.cos(bearing) * wind_north local cross_wind = math.cos(bearing) * wind_east + math.sin(bearing) * wind_north -- left to right -- we can't get home if math.abs(cross_wind) > air_speed then return -1, air_speed -- FIXME: this should really be infinity end -- calculate the crab angle required to cancel out the cross wind local crab_angle = math.asin(-cross_wind / air_speed) -- the resulting speed in the desired direction local home_airspeed = air_speed * math.cos(crab_angle) local effective_speed = home_airspeed + tail_wind -- Estimate the extra distance required to turn local yaw = ahrs:get_yaw() -- this is the estimated angle we have to turn to be at the home bearing and crab angle local turn_angle_rad = bearing - crab_angle - yaw -- wrap to +- PI if turn_angle_rad < math.rad(-180) then turn_angle_rad = turn_angle_rad + math.rad(360) elseif turn_angle_rad > math.rad(180) then turn_angle_rad = turn_angle_rad - math.rad(360) end --gcs:send_text(0, "turn " .. tostring(math.deg(turn_angle_rad)) .. " deg") -- Take into account min ground speed and resulting increased RTL airspeed local return_air_speed = air_speed if min_ground_speed > 0 and effective_speed < min_ground_speed then -- we travel home at the min ground speed effective_speed = min_ground_speed -- work out the resulting airspeed return_air_speed = math.sqrt((effective_speed-tail_wind)^2 + cross_wind^2) end -- distance to travel over ground speed + turn circumference over airspeed return (position:get_distance(home) / effective_speed) + (math.abs(turn_angle_rad*turn_rad) / air_speed), return_air_speed end return 0, air_speed -- nothing useful available end -- idle function function idle() -- if disarmed and not flying reset for a potential second trigger if not arming:is_armed() and not vehicle:get_likely_flying() then return update, 100 end return idle, 1000 end -- time margin update function function margin_update() if not vehicle:get_likely_flying() then -- no longer flying, idle function return idle, 10000 end -- display the remaining battery capacity on the triggered monitor local capacity = battery:pack_capacity_mah(trigger_instance) local consumed = battery:consumed_mah(trigger_instance) if capacity and consumed then gcs:send_text(0, string.format("Failsafe: %is margin elapsed %.2fmAh remain",margin, capacity - consumed)) end -- idle function return idle, 10000 end -- this is an alternate update function that is simply used to track how long it will take to get home -- it's really only used for debugging how the prediction rules are working function track_return_time() if not vehicle:get_likely_flying() then -- no longer flying, idle function return idle, 10000 end local home = ahrs:get_home() local position = ahrs:get_location() if home and position then local now = millis() local home_dist = position:get_distance(home) if home_dist < home_reached_rad then -- calculate the extra time to fly the reached rad distance local time_home = time_to_home() local total_time = time_home + ((now-return_start)/1000) -- display the remaining battery capacity on the triggered monitor local capacity = battery:pack_capacity_mah(trigger_instance) local consumed = battery:consumed_mah(trigger_instance) if capacity and consumed then -- estimate the extra capacity used for the reached rad distance return_capacity = return_amps * time_home * (1000 / 60^2) -- convert from amp second's to mAh gcs:send_text(0, "Failsafe: RTL took " .. tostring(total_time) .. string.format("s, %.2fmAh remain", capacity - consumed - return_capacity) ) if margin > 0 then return margin_update, margin*1000 end else gcs:send_text(0, "Failsafe: RTL took " .. tostring(total_time) .. " s") end -- idle function return idle, 10000 end -- print updates tracking progress local return_time = time_to_home() local total_time = return_time + ((now-return_start)/1000) if last_print + (print_time * 1000) < now and print_time > 0 then last_print = now if (return_time < 0) then gcs:send_text(6, "Failsafe: ground speed low can not get home") elseif (return_time > 0) then -- cannot get string.format() to work with total time, wrong variable type? ie not %f or %i? gcs:send_text(0, "Failsafe: Estimated " .. tostring(total_time) .. string.format("s, %.0fs remain", return_time) ) end end logger.write('SFSC','total_return_time,remaining_return_time','If','ss','--',total_time,return_time) end return track_return_time, 100 end -- the main update function that is used to decide when we should do a failsafe function update() local now = millis(); -- check armed if not arming:is_armed() then --gcs:send_text(0, "Failsafe: disabled: not armed") timer_start_time = now timer_active = true return update, 100 end -- check flying if not vehicle:get_likely_flying() then --gcs:send_text(0, "Failsafe: disabled: not flying") timer_start_time = now timer_active = true return update, 100 end -- check mode local current_mode = vehicle:get_mode() if current_mode >= 17 then --gcs:send_text(0, "Failsafe: disabled: Q mode") timer_start_time = now timer_active = true return update, 100 end -- check altitude if alt_min ~= 0 then local dist = ahrs:get_relative_position_NED_home() if not dist or -1*dist:z() < alt_min then --gcs:send_text(0, "Failsafe: disabled: low alt") timer_start_time = now timer_active = true return update, 100 end end -- check timer if now - timer_start_time < (min_flying_time * 1000) then --gcs:send_text(0, "Failsafe: disabled: timer") return update, 100 end -- notify that we have started if timer_active then gcs:send_text(0, "Smart Battery RTL started monitoring") timer_active = false end -- check airspeed local air_speed_in = ahrs:airspeed_estimate() if not air_speed_in then error("Could not read airspeed") end if air_speed_in < min_air_speed * 0.75 then -- we are not flying fast enough, skip but don't reset the timer return update, 100 end local min_remaining_time = 86400 -- 24 hours -- find the return time and airspeed local return_time, return_airspeed = time_to_home() -- default to no normalization local q = 1 local return_q = 1 -- normalize current with dynamic pressure if airspeed_normalize then -- we could probably just use air speed^2 local press = baro:get_pressure() local temp = baro:get_external_temperature() + 273.2 -- convert deg centigrade to kelvin local density = press / (temp * 287.058) -- calculate the air density, ideal gas law, constant is (R) specific gas constant for air q = 0.5 * density * air_speed_in^2 return_q = 0.5 * density * return_airspeed^2 -- we could estimate the change in density also, but will be negligible end logger.write('SFSA','return_time,return_airspeed,Q,return_Q','ffff','snPP','----',return_time,return_airspeed,q,return_q) for i = 1, #batt_info do local instance, norm_filtered_amps, rated_capacity_mah = table.unpack(batt_info[i]) local amps = battery:current_amps(instance) local consumed_mah = battery:consumed_mah(instance) if amps and consumed_mah then local norm_amps = amps / q -- update all the current consumption rates norm_filtered_amps = (norm_filtered_amps * filter) + (norm_amps * (1.0 - filter)) batt_info[i][2] = norm_filtered_amps -- calculate the estimated return amps, estimate the return current if we were to fly at a different airspeed return_amps = norm_filtered_amps * return_q local remaining_capacity = (rated_capacity_mah - consumed_mah) * 3.6 -- amp seconds (60^2 / 1000) local remaining_time = remaining_capacity / return_amps local buffer_time = remaining_time - ((return_time * time_SF) + margin) logger.write('SFSB','Instance,current,rem_cap,rem_time,buffer','Bffff','#Aiss','--C--',i-1,return_amps,remaining_capacity,remaining_time,buffer_time) if (return_time < 0) or buffer_time < 0 then if return_time < 0 then gcs:send_text(0, "Failsafe: ground speed low can not get home") elseif #batt_info == 1 then gcs:send_text(0, string.format("Failsafe: Estimated %.0fs to home", return_time)) else trigger_instance = instance gcs:send_text(0, string.format("Failsafe: Estimated %.0fs to home, instance %i", return_time, instance)) end last_print = now -- FIXME: We need more insight into what the vehicles already doing. IE don't trigger RTL if we are already landing vehicle:set_mode(11) -- plane RTL FIXME: we need a set of enums defined for the vehicles -- swap to tracking the time rather then re trigger return_start = now -- Print the return distance --[[local home = ahrs:get_home() local position = ahrs:get_location() if home and position then return_distance = position:get_distance(home) end gcs:send_text(0, string.format("Failsafe: %.0f m to home", return_distance))]] -- print the current draw we estimate --gcs:send_text(0, string.format("Failsafe: %.2fa", return_amps)) return track_return_time, 100 end min_remaining_time = math.min(min_remaining_time, buffer_time) end end -- print updates tracking progress if last_print + (print_time * 1000) < now and print_time > 0 then last_print = now gcs:send_text(6, string.format("%.0f seconds of flight remaining before RTL", min_remaining_time)) end return update, 100 end -- validate that all the expected monitors have current monitoring capability, and fetch initial values for i = 1, #batt_info do -- check that the instance exists local instance = batt_info[i][1] if instance > battery:num_instances() then error("Battery " .. instance .. " does not exist") end -- check that we can actually read current from the instance if not battery:current_amps(instance) then error("Battery " .. instance .. " does not support current monitoring") end -- store the pack capacity for later use, it's assumed to never change mid flight -- subtract the capacity we want remaining when we get home local rated_cap = battery:pack_capacity_mah(instance) if rated_cap then -- read in the critical MAH local param_string = 'BATT' .. tostring(instance + 1) .. '_CRT_MAH' if instance == 0 then param_string = 'BATT_CRT_MAH' end local value = param:get(param_string) if not value then error('LUA: get '.. param_string .. ' failed') end batt_info[i][3] = rated_cap - (batt_info[i][4] + value) else error("Battery " .. instance .. " does not support current monitoring") end end return update, 100
gpl-3.0
vanpouckesven/cosnics
src/Chamilo/Core/Repository/Selector/TypeSelectorRenderer.php
2050
<?php namespace Chamilo\Core\Repository\Selector; use Chamilo\Libraries\Architecture\Application\Application; use Chamilo\Libraries\Utilities\StringUtilities; /** * Render content object type selection tabs based on their category * * @author Hans De Bisschop */ abstract class TypeSelectorRenderer { CONST TYPE_FULL = 'full'; CONST TYPE_FORM = 'form'; CONST TYPE_TABS = 'tabs'; /** * * @var \libraries\architecture\application\Application */ private $parent; /** * * @var \core\repository\TypeSelector */ private $type_selector; /** * * @param Application $parent * @param TypeSelector $type_selector */ public function __construct(Application $parent, TypeSelector $type_selector) { $this->parent = $parent; $this->type_selector = $type_selector; } /** * * @return \libraries\architecture\application\Application */ public function get_parent() { return $this->parent; } /** * * @return \Chamilo\Core\Repository\Selector\TypeSelector */ public function get_type_selector() { return $this->type_selector; } abstract function render(); public static function factory($type, Application $parent, TypeSelector $type_selector) { $class_name = __NAMESPACE__ . '\\' . StringUtilities::getInstance()->createString($type)->upperCamelize() . 'TypeSelectorRenderer'; $arguments = func_get_args(); switch ($type) { case self::TYPE_FORM : return new $class_name($parent, $type_selector, $arguments[3]); break; case self::TYPE_TABS : return new $class_name($parent, $type_selector, $arguments[3], $arguments[4]); break; case self::TYPE_FULL : return new $class_name($parent, $type_selector, $arguments[3], $arguments[4], $arguments[5]); break; } } }
gpl-3.0
AlanZatarain/video-tester
VideoTester/measures/vq.py
12101
# coding=UTF8 ## This file is part of VideoTester ## See http://video-tester.googlecode.com for more information ## Copyright 2011 Iñaki Úcar <i.ucar86@gmail.com> ## This program is published under a GPLv3 license from VideoTester.measures.core import Meter, Measure from VideoTester.measures.qos import QoSmeter from VideoTester.measures.bs import BSmeter from VideoTester.config import VTLOG import math import cv class VQmeter(Meter): """ Video quality meter. """ def __init__(self, selected, data): """ **On init:** Register selected video quality measures. :param selected: Selected video quality measures. :type selected: string or list :param tuple data: Collected QoS + bit-stream + video parameters. """ Meter.__init__(self) VTLOG.info("Starting VQmeter...") if 'psnr' in selected: self.measures.append(PSNR(data)) if 'ssim' in selected: self.measures.append(SSIM(data)) if 'g1070' in selected: self.measures.append(G1070(data)) if 'psnrtomos' in selected: self.measures.append(PSNRtoMOS(data)) if 'miv' in selected: self.measures.append(MIV(data)) class VQmeasure(Measure): """ Video quality measure type. """ def __init__(self, (conf, rawdata, codecdata, packetdata)): """ **On init:** Register QoS + bit-stream + video parameters. :param string conf: Video parameters: `codec`, `bitrate`, `framerate` and `size`. :param dictionary rawdata: Frame information from YUV videos (`original`, `received` and `coded`). :param dictionary codecdata: Frame information from compressed videos (`received` and `coded`). :param tuple packetdata: QoS parameters. """ Measure.__init__(self) #: Video parameters: `codec`, `bitrate`, `framerate` and `size`. self.conf = conf self.rawdata = rawdata #: Frame information from received YUV. self.yuv = rawdata['received'] #: Frame information from original YUV. self.yuvref = rawdata['original'] #: Frame information from compressed videos (`received` and `coded`). self.codecdata = codecdata #: QoS parameters. self.packetdata = packetdata def getQoSm(self, measures): """ Get QoS measures. :param measures: Selected QoS measures. :type measures: string or list :returns: Calculated QoS measures. :rtype: list """ VTLOG.info("----------getQoSm----------") measures = QoSmeter(measures, self.packetdata).run() VTLOG.info("---------------------------") return measures def getBSm(self, measures): """ Get bit-stream measures. :param measures: Selected bit-stream measures. :type measures: string or list :returns: Calculated bit-stream measures. :rtype: list """ VTLOG.info("----------getBSm-----------") measures = BSmeter(measures, self.codecdata).run() VTLOG.info("---------------------------") return measures class PSNR(VQmeasure): """ PSNR: Peak Signal to Noise Ratio (Y component). * Type: `plot`. * Units: `dB per frame`. """ def __init__(self, data, yuv=False, yuvref=False): VQmeasure.__init__(self, data) self.data['name'] = 'PSNR' self.data['type'] = 'plot' self.data['units'] = ('frame', 'dB') if yuv: self.yuv = self.rawdata['coded'] if yuvref: self.yuvref = self.rawdata['coded'] def calculate(self): L = 255 width = self.yuv.video['Y'][0].shape[0] height = self.yuv.video['Y'][0].shape[1] fin = min(self.yuv.frames, self.yuvref.frames) x = range(0, fin) y = [] for i in x: sum = (self.yuv.video['Y'][i].astype(int) - self.yuvref.video['Y'][i].astype(int))**2 mse = sum.sum() / width / height if mse != 0: y.append(20 * math.log(L / math.sqrt(mse), 10)) else: y.append(100) self.graph(x, y) return self.data class SSIM(VQmeasure): """ SSIM: Structural Similarity index (Y component). * Type: `plot`. * Units: `SSIM index per frame`. """ def __init__(self, data): VQmeasure.__init__(self, data) self.data['name'] = 'SSIM' self.data['type'] = 'plot' self.data['units'] = ('frame', 'SSIM index') def __array2cv(self, a): dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im def __SSIM(self, frame1, frame2): """ The equivalent of Zhou Wang's SSIM matlab code using OpenCV. from http://www.cns.nyu.edu/~zwang/files/research/ssim/index.html The measure is described in : "Image quality assessment: From error measurement to structural similarity" C++ code by Rabah Mehdi. http://mehdi.rabah.free.fr/SSIM C++ to Python translation and adaptation by Iñaki Úcar """ C1 = 6.5025 C2 = 58.5225 img1_temp = self.__array2cv(frame1) img2_temp = self.__array2cv(frame2) nChan = img1_temp.nChannels d = cv.IPL_DEPTH_32F size = img1_temp.width, img1_temp.height img1 = cv.CreateImage(size, d, nChan) img2 = cv.CreateImage(size, d, nChan) cv.Convert(img1_temp, img1) cv.Convert(img2_temp, img2) img1_sq = cv.CreateImage(size, d, nChan) img2_sq = cv.CreateImage(size, d, nChan) img1_img2 = cv.CreateImage(size, d, nChan) cv.Pow(img1, img1_sq, 2) cv.Pow(img2, img2_sq, 2) cv.Mul(img1, img2, img1_img2, 1) mu1 = cv.CreateImage(size, d, nChan) mu2 = cv.CreateImage(size, d, nChan) mu1_sq = cv.CreateImage(size, d, nChan) mu2_sq = cv.CreateImage(size, d, nChan) mu1_mu2 = cv.CreateImage(size, d, nChan) sigma1_sq = cv.CreateImage(size, d, nChan) sigma2_sq = cv.CreateImage(size, d, nChan) sigma12 = cv.CreateImage(size, d, nChan) temp1 = cv.CreateImage(size, d, nChan) temp2 = cv.CreateImage(size, d, nChan) temp3 = cv.CreateImage(size, d, nChan) ssim_map = cv.CreateImage(size, d, nChan) #/*************************** END INITS **********************************/ #// PRELIMINARY COMPUTING cv.Smooth(img1, mu1, cv.CV_GAUSSIAN, 11, 11, 1.5) cv.Smooth(img2, mu2, cv.CV_GAUSSIAN, 11, 11, 1.5) cv.Pow(mu1, mu1_sq, 2) cv.Pow(mu2, mu2_sq, 2) cv.Mul(mu1, mu2, mu1_mu2, 1) cv.Smooth(img1_sq, sigma1_sq, cv.CV_GAUSSIAN, 11, 11, 1.5) cv.AddWeighted(sigma1_sq, 1, mu1_sq, -1, 0, sigma1_sq) cv.Smooth(img2_sq, sigma2_sq, cv.CV_GAUSSIAN, 11, 11, 1.5) cv.AddWeighted(sigma2_sq, 1, mu2_sq, -1, 0, sigma2_sq) cv.Smooth(img1_img2, sigma12, cv.CV_GAUSSIAN, 11, 11, 1.5) cv.AddWeighted(sigma12, 1, mu1_mu2, -1, 0, sigma12) #////////////////////////////////////////////////////////////////////////// #// FORMULA #// (2*mu1_mu2 + C1) cv.Scale(mu1_mu2, temp1, 2) cv.AddS(temp1, C1, temp1) #// (2*sigma12 + C2) cv.Scale(sigma12, temp2, 2) cv.AddS(temp2, C2, temp2) #// ((2*mu1_mu2 + C1).*(2*sigma12 + C2)) cv.Mul(temp1, temp2, temp3, 1) #// (mu1_sq + mu2_sq + C1) cv.Add(mu1_sq, mu2_sq, temp1) cv.AddS(temp1, C1, temp1) #// (sigma1_sq + sigma2_sq + C2) cv.Add(sigma1_sq, sigma2_sq, temp2) cv.AddS(temp2, C2, temp2) #// ((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)) cv.Mul(temp1, temp2, temp1, 1) #// ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)) cv.Div(temp3, temp1, ssim_map, 1) index_scalar = cv.Avg(ssim_map) #// through observation, there is approximately #// 1% error max with the original matlab program return index_scalar[0] def calculate(self): fin = min(self.yuv.frames, self.yuvref.frames) x = range(0, fin) y = [] for i in x: y.append(self.__SSIM(self.yuv.video['Y'][i], self.yuvref.video['Y'][i])) self.graph(x, y) return self.data class G1070(VQmeasure): """ ITU-T G.1070 video quality estimation. * Type: `value`. * Units: `-`. """ def __init__(self, data): VQmeasure.__init__(self, data) self.data['name'] = 'G.1070' self.data['type'] = 'value' self.data['units'] = '' def calculate(self): v = [0, 1.431, 2.228e-2, 3.759, 184.1, 1.161, 1.446, 3.881e-4, 2.116, 467.4, 2.736, 15.28, 4.170] Dfrv = v[6] + v[7] * self.conf['bitrate'] Iofr = v[3] - v[3] / (1 + (self.conf['bitrate'] / v[4])**v[5]) Ofr = v[1] + v[2] * self.conf['bitrate'] Ic = Iofr * math.exp(-(math.log(self.conf['framerate']) - math.log(Ofr))**2 / (2 * Dfrv**2)) Dpplv = v[10] + v[11] * math.exp(-self.conf['framerate'] / v[8]) + v[12] * math.exp(-self.conf['bitrate'] / v[9]) self.data['value'] = 1 + Ic * math.exp(-self.getQoSm('plr')[0]['value'] * 100 / Dpplv) return self.data class PSNRtoMOS(VQmeasure): """ PSNR to MOS mapping used on `Evalvid <http://www.tkn.tu-berlin.de/research/evalvid/>`. * Type: `plot`. * Units: `MOS per frame`. """ def __init__(self, data, yuv=False, yuvref=False): VQmeasure.__init__(self, data) self.data['name'] = 'PSNRtoMOS' self.data['type'] = 'plot' self.data['units'] = ('frame', 'MOS') self.yuv = yuv self.yuvref = yuvref def calculate(self): x, y = PSNR((None, self.rawdata, None, None), yuv=self.yuv, yuvref=self.yuvref).calculate()['axes'] for i in range(0, len(y)): if y[i] < 20: y[i] = 1 elif 20 <= y[i] < 25: y[i] = 2 elif 25 <= y[i] < 31: y[i] = 3 elif 31 <= y[i] < 37: y[i] = 4 else: y[i] = 5 self.graph(x, y) return self.data class MIV(VQmeasure): """ MIV metric used on `Evalvid <http://www.tkn.tu-berlin.de/research/evalvid/>`. * Type: `plot`. * Units: `Distortion in Interval`. """ def __init__(self, data): VQmeasure.__init__(self, data) self.data['name'] = 'MIV' self.data['type'] = 'plot' self.interval = 25 self.data['units'] = ('frame', '% of frames with a MOS worse than the reference') def calculate(self): x, refmos = PSNRtoMOS((None, self.rawdata, None, None), yuv=True).calculate()['axes'] x, mos = PSNRtoMOS((None, self.rawdata, None, None)).calculate()['axes'] y = [0 for i in range(0, self.interval)] for l in range(0, min(len(refmos), len(mos)) - self.interval): i = 0 for j in range(l, l + self.interval): if mos[j] < refmos[j] and mos[j] < 4: i += 1 y.append(100 * float(i) / self.interval) x = [x for x in range(0, len(y))] self.graph(x, y) return self.data
gpl-3.0
IAMATinyCoder/SocialEDU
node_modules/gulp-sass/node_modules/node-sass/node_modules/sass-graph/node_modules/yargs/lib/validation.js
5274
// validation-type-stuff, missing params, // bad implications, custom checks. module.exports = function (yargs, usage) { var self = {} // validate appropriate # of non-option // arguments were provided, i.e., '_'. self.nonOptionCount = function (argv) { var demanded = yargs.getDemanded() if (demanded._ && argv._.length < demanded._.count) { if (demanded._.msg !== undefined) { usage.fail(demanded._.msg) } else { usage.fail('Not enough non-option arguments: got ' + argv._.length + ', need at least ' + demanded._.count ) } } } // make sure that any args that require an // value (--foo=bar), have a value. self.missingArgumentValue = function (argv) { var defaultValues = [true, false, ''] var options = yargs.getOptions() if (options.requiresArg.length > 0) { var missingRequiredArgs = [] options.requiresArg.forEach(function (key) { var value = argv[key] // if a value is explicitly requested, // flag argument as missing if it does not // look like foo=bar was entered. if (~defaultValues.indexOf(value) || (Array.isArray(value) && !value.length)) { missingRequiredArgs.push(key) } }) if (missingRequiredArgs.length === 1) { usage.fail('Missing argument value: ' + missingRequiredArgs[0]) } else if (missingRequiredArgs.length > 1) { var message = 'Missing argument values: ' + missingRequiredArgs.join(', ') usage.fail(message) } } } // make sure all the required arguments are present. self.requiredArguments = function (argv) { var demanded = yargs.getDemanded() var missing = null Object.keys(demanded).forEach(function (key) { if (!argv.hasOwnProperty(key)) { missing = missing || {} missing[key] = demanded[key] } }) if (missing) { var customMsgs = [] Object.keys(missing).forEach(function (key) { var msg = missing[key].msg if (msg && customMsgs.indexOf(msg) < 0) { customMsgs.push(msg) } }) var customMsg = customMsgs.length ? '\n' + customMsgs.join('\n') : '' usage.fail('Missing required arguments: ' + Object.keys(missing).join(', ') + customMsg) } } // check for unknown arguments (strict-mode). self.unknownArguments = function (argv, aliases) { var aliasLookup = {} var descriptions = usage.getDescriptions() var demanded = yargs.getDemanded() var unknown = [] Object.keys(aliases).forEach(function (key) { aliases[key].forEach(function (alias) { aliasLookup[alias] = key }) }) Object.keys(argv).forEach(function (key) { if (key !== '$0' && key !== '_' && !descriptions.hasOwnProperty(key) && !demanded.hasOwnProperty(key) && !aliasLookup.hasOwnProperty(key)) { unknown.push(key) } }) if (unknown.length === 1) { usage.fail('Unknown argument: ' + unknown[0]) } else if (unknown.length > 1) { usage.fail('Unknown arguments: ' + unknown.join(', ')) } } // custom checks, added using the `check` option on yargs. var checks = [] self.check = function (f) { checks.push(f) } self.customChecks = function (argv, aliases) { checks.forEach(function (f) { try { var result = f(argv, aliases) if (!result) { usage.fail('Argument check failed: ' + f.toString()) } else if (typeof result === 'string') { usage.fail(result) } } catch (err) { usage.fail(err.message ? err.message : err) } }) } // check implications, argument foo implies => argument bar. var implied = {} self.implies = function (key, value) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.implies(k, key[k]) }) } else { implied[key] = value } } self.getImplied = function () { return implied } self.implications = function (argv) { var implyFail = [] Object.keys(implied).forEach(function (key) { var num var origKey = key var value = implied[key] // convert string '1' to number 1 num = Number(key) key = isNaN(num) ? key : num if (typeof key === 'number') { // check length of argv._ key = argv._.length >= key } else if (key.match(/^--no-.+/)) { // check if key doesn't exist key = key.match(/^--no-(.+)/)[1] key = !argv[key] } else { // check if key exists key = argv[key] } num = Number(value) value = isNaN(num) ? value : num if (typeof value === 'number') { value = argv._.length >= value } else if (value.match(/^--no-.+/)) { value = value.match(/^--no-(.+)/)[1] value = !argv[value] } else { value = argv[value] } if (key && !value) { implyFail.push(origKey) } }) if (implyFail.length) { var msg = 'Implications failed:\n' implyFail.forEach(function (key) { msg += (' ' + key + ' -> ' + implied[key]) }) usage.fail(msg) } } return self }
gpl-3.0
stalker-people/r107
0.1.3/plugins/chatbox_menu/chatbox_sql.php
327
CREATE TABLE chatbox ( cb_id int(10) unsigned NOT NULL auto_increment, cb_nick varchar(30) NOT NULL default '', cb_message text NOT NULL, cb_datestamp int(10) unsigned NOT NULL default '0', cb_blocked tinyint(3) unsigned NOT NULL default '0', cb_ip varchar(15) NOT NULL default '', PRIMARY KEY (cb_id) ) ENGINE=MyISAM;
gpl-3.0
Acidburn0zzz/servo
tests/wpt/web-platform-tests/resources/chromium/nfc-mock.js
13557
'use strict'; // Converts between NDEFMessageInit https://w3c.github.io/web-nfc/#dom-ndefmessage // and mojom.NDEFMessage structure, so that watch function can be tested. function toMojoNDEFMessage(message) { let ndefMessage = new device.mojom.NDEFMessage(); ndefMessage.data = []; for (let record of message.records) { ndefMessage.data.push(toMojoNDEFRecord(record)); } return ndefMessage; } function toMojoNDEFRecord(record) { let nfcRecord = new device.mojom.NDEFRecord(); // Simply checks the existence of ':' to decide whether it's an external // type or a local type. As a mock, no need to really implement the validation // algorithms for them. if (record.recordType.startsWith(':')) { nfcRecord.category = device.mojom.NDEFRecordTypeCategory.kLocal; } else if (record.recordType.search(':') != -1) { nfcRecord.category = device.mojom.NDEFRecordTypeCategory.kExternal; } else { nfcRecord.category = device.mojom.NDEFRecordTypeCategory.kStandardized; } nfcRecord.recordType = record.recordType; nfcRecord.mediaType = record.mediaType; nfcRecord.id = record.id; if (record.recordType == 'text') { nfcRecord.encoding = record.encoding == null? 'utf-8': record.encoding; nfcRecord.lang = record.lang == null? 'en': record.lang; } nfcRecord.data = toByteArray(record.data); if (record.data != null && record.data.records !== undefined) { // |record.data| may be an NDEFMessageInit, i.e. the payload is a message. nfcRecord.payloadMessage = toMojoNDEFMessage(record.data); } return nfcRecord; } // Converts JS objects to byte array. function toByteArray(data) { if (data instanceof ArrayBuffer) return new Uint8Array(data); else if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); let byteArray = new Uint8Array(0); let tmpData = data; if (typeof tmpData === 'object' || typeof tmpData === 'number') tmpData = JSON.stringify(tmpData); if (typeof tmpData === 'string') byteArray = new TextEncoder('utf-8').encode(tmpData); return byteArray; } // Compares NDEFRecords that were provided / received by the mock service. // TODO: Use different getters to get received record data, // see spec changes at https://github.com/w3c/web-nfc/pull/243. function compareNDEFRecords(providedRecord, receivedRecord) { assert_equals(providedRecord.recordType, receivedRecord.recordType); if (providedRecord.id === undefined) { assert_equals(null, receivedRecord.id); } else { assert_equals(providedRecord.id, receivedRecord.id); } if (providedRecord.mediaType === undefined) { assert_equals(null, receivedRecord.mediaType); } else { assert_equals(providedRecord.mediaType, receivedRecord.mediaType); } assert_not_equals(providedRecord.recordType, 'empty'); if (providedRecord.recordType == 'text') { assert_equals( providedRecord.encoding == null? 'utf-8': providedRecord.encoding, receivedRecord.encoding); assert_equals(providedRecord.lang == null? 'en': providedRecord.lang, receivedRecord.lang); } else { assert_equals(null, receivedRecord.encoding); assert_equals(null, receivedRecord.lang); } assert_array_equals(toByteArray(providedRecord.data), new Uint8Array(receivedRecord.data)); } // Compares NDEFWriteOptions structures that were provided to API and // received by the mock mojo service. function assertNDEFWriteOptionsEqual(provided, received) { if (provided.ignoreRead !== undefined) assert_equals(provided.ignoreRead, !!received.ignoreRead); else assert_equals(!!received.ignore_read, true); } // Compares NDEFReaderOptions structures that were provided to API and // received by the mock mojo service. function assertNDEFReaderOptionsEqual(provided, received) { if (provided.url !== undefined) assert_equals(provided.url, received.url); else assert_equals(received.url, ''); if (provided.mediaType !== undefined) assert_equals(provided.mediaType, received.mediaType); else assert_equals(received.mediaType, ''); if (provided.recordType !== undefined) { assert_equals(provided.recordType, received.recordType); } } // Checks whether NDEFReaderOptions are matched with given message. function matchesWatchOptions(message, options) { // A message with no records is to notify that the tag is already formatted to // support NDEF but does not contain a message yet. We always dispatch it for // all options. if (message.records.length == 0) return true; for (let record of message.records) { if (options.id != null && options.id !== record.id) { continue; } if (options.recordType != null && options.recordType !== record.recordType) { continue; } if (options.mediaType != null && options.mediaType !== record.mediaType) { continue; } // Found one record matches, means the message matches. return true; } return false; } function createNDEFError(type) { return { error: type != null ? new device.mojom.NDEFError({errorType: type, errorMessage: ''}) : null }; } var WebNFCTest = (() => { class MockNFC { constructor() { this.bindingSet_ = new mojo.BindingSet(device.mojom.NFC); this.interceptor_ = new MojoInterfaceInterceptor(device.mojom.NFC.name); this.interceptor_.oninterfacerequest = e => { if (this.should_close_pipe_on_request_) e.handle.close(); else this.bindingSet_.addBinding(this, e.handle); } this.interceptor_.start(); this.hw_status_ = NFCHWStatus.ENABLED; this.pushed_message_ = null; this.pending_write_options_ = null; this.pending_promise_func_ = null; this.push_completed_ = true; this.client_ = null; this.watchers_ = []; this.reading_messages_ = []; this.operations_suspended_ = false; this.is_formatted_tag_ = false; this.data_transfer_failed_ = false; this.should_close_pipe_on_request_ = false; } // NFC delegate functions. async push(message, options) { let error = this.getHWError(); if (error) return error; // Cancels previous pending push operation. if (this.pending_promise_func_) { this.cancelPendingPushOperation(); } this.pushed_message_ = message; this.pending_write_options_ = options; return new Promise(resolve => { if (this.operations_suspended_ || !this.push_completed_) { // Leaves the push pending. this.pending_promise_func_ = resolve; } else if (this.is_formatted_tag_ && !options.overwrite) { // Resolves with NotAllowedError if there are NDEF records on the device // and overwrite is false. resolve(createNDEFError(device.mojom.NDEFErrorType.NOT_ALLOWED)); } else if (this.data_transfer_failed_) { // Resolves with NetworkError if data transfer fails. resolve(createNDEFError(device.mojom.NDEFErrorType.IO_ERROR)); } else { resolve(createNDEFError(null)); } }); } async cancelPush() { this.cancelPendingPushOperation(); return createNDEFError(null); } setClient(client) { this.client_ = client; } async watch(options, id) { assert_true(id > 0); let error = this.getHWError(); if (error) { return error; } this.watchers_.push({id: id, options: options}); // Ignores reading if NFC operation is suspended // or the NFC tag does not expose NDEF technology. if (!this.operations_suspended_) { // Triggers onWatch if the new watcher matches existing messages. for (let message of this.reading_messages_) { if (matchesWatchOptions(message, options)) { this.client_.onWatch( [id], fake_tag_serial_number, toMojoNDEFMessage(message)); } } } return createNDEFError(null); } async cancelWatch(id) { let index = this.watchers_.findIndex(value => value.id === id); if (index === -1) { return createNDEFError(device.mojom.NDEFErrorType.NOT_FOUND); } this.watchers_.splice(index, 1); return createNDEFError(null); } async cancelAllWatches() { if (this.watchers_.length === 0) { return createNDEFError(device.mojom.NDEFErrorType.NOT_FOUND); } this.watchers_.splice(0, this.watchers_.length); return createNDEFError(null); } getHWError() { if (this.hw_status_ === NFCHWStatus.DISABLED) return createNDEFError(device.mojom.NDEFErrorType.NOT_READABLE); if (this.hw_status_ === NFCHWStatus.NOT_SUPPORTED) return createNDEFError(device.mojom.NDEFErrorType.NOT_SUPPORTED); return null; } setHWStatus(status) { this.hw_status_ = status; } pushedMessage() { return this.pushed_message_; } writeOptions() { return this.pending_write_options_; } watchOptions() { assert_not_equals(this.watchers_.length, 0); return this.watchers_[this.watchers_.length - 1].options; } setPendingPushCompleted(result) { this.push_completed_ = result; } reset() { this.hw_status_ = NFCHWStatus.ENABLED; this.watchers_ = []; this.reading_messages_ = []; this.operations_suspended_ = false; this.cancelPendingPushOperation(); this.is_formatted_tag_ = false; this.data_transfer_failed_ = false; this.should_close_pipe_on_request_ = false; } cancelPendingPushOperation() { if (this.pending_promise_func_) { this.pending_promise_func_( createNDEFError(device.mojom.NDEFErrorType.OPERATION_CANCELLED)); this.pending_promise_func_ = null; } this.pushed_message_ = null; this.pending_write_options_ = null; this.push_completed_ = true; } // Sets message that is used to deliver NFC reading updates. setReadingMessage(message) { this.reading_messages_.push(message); // Ignores reading if NFC operation is suspended. if(this.operations_suspended_) return; // Ignores reading if NDEFWriteOptions.ignoreRead is true. if (this.pending_write_options_ && this.pending_write_options_.ignoreRead) return; // Triggers onWatch if the new message matches existing watchers. for (let watcher of this.watchers_) { if (matchesWatchOptions(message, watcher.options)) { this.client_.onWatch( [watcher.id], fake_tag_serial_number, toMojoNDEFMessage(message)); } } } // Suspends all pending NFC operations. Could be used when web page // visibility is lost. suspendNFCOperations() { this.operations_suspended_ = true; } // Resumes all suspended NFC operations. resumeNFCOperations() { this.operations_suspended_ = false; // Resumes pending NFC reading. for (let watcher of this.watchers_) { for (let message of this.reading_messages_) { if (matchesWatchOptions(message, watcher.options)) { this.client_.onWatch( [watcher.id], fake_tag_serial_number, toMojoNDEFMessage(message)); } } } // Resumes pending push operation. if (this.pending_promise_func_ && this.push_completed_) { this.pending_promise_func_(createNDEFError(null)); this.pending_promise_func_ = null; } } // Simulates the device coming in proximity does not expose NDEF technology. simulateNonNDEFTagDiscovered() { // Notify NotSupportedError to all active readers. if (this.watchers_.length != 0) { this.client_.onError(new device.mojom.NDEFError({ errorType: device.mojom.NDEFErrorType.NOT_SUPPORTED, errorMessage: '' })); } // Reject the pending push with NotSupportedError. if (this.pending_promise_func_) { this.pending_promise_func_( createNDEFError(device.mojom.NDEFErrorType.NOT_SUPPORTED)); this.pending_promise_func_ = null; } } setIsFormattedTag(isFormatted) { this.is_formatted_tag_ = isFormatted; } simulateDataTransferFails() { this.data_transfer_failed_ = true; } simulateClosedPipe() { this.should_close_pipe_on_request_ = true; } } let testInternal = { initialized: false, mockNFC: null } class NFCTestChromium { constructor() { Object.freeze(this); // Makes it immutable. } async initialize() { if (testInternal.initialized) throw new Error('Call reset() before initialize().'); // Grant nfc permissions for Chromium testdriver. await test_driver.set_permission({ name: 'nfc' }, 'granted', false); if (testInternal.mockNFC == null) { testInternal.mockNFC = new MockNFC(); } testInternal.initialized = true; } // Reuses the nfc mock but resets its state between test runs. async reset() { if (!testInternal.initialized) throw new Error('Call initialize() before reset().'); testInternal.mockNFC.reset(); testInternal.initialized = false; await new Promise(resolve => setTimeout(resolve, 0)); } getMockNFC() { return testInternal.mockNFC; } } return NFCTestChromium; })();
mpl-2.0
mgax/czl-scrape
munca/src/main/java/ro/code4/czl/scrape/client/ApiInvoker.java
1851
package ro.code4.czl.scrape.client;/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2016 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated and its * suppliers and are protected by all applicable intellectual property * laws, including trade secret and copyright laws. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/ /** * Basic API invoker contract. * * @author Ionut-Maxim Margelatu (ionut.margelatu@gmail.com) */ public interface ApiInvoker extends AutoCloseable { /** * Configures a request header that should be added to every request made via this API invoker. * * @param key request header name * @param value request header value */ void addDefaultHeader(String key, String value); /** * Executes a request. * * @param request the request to execute * @param <T> the type that the response should be deserialized into * @return a {@link Response} instance containing the response body deserialized into the desired type */ <T> Response<T> invokeAPI(Request<T> request); /** * Shuts down the connection manager used by this API invoker and releases allocated resources. This includes closing all connections, whether they * are currently used or not. */ void shutdown(); }
mpl-2.0
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/contribution/content/form/FormFatalException.java
2345
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.contribution.content.form; import org.silverpeas.core.exception.SilverpeasException; /** * Thrown when a fatal error occured in a form component. */ public class FormFatalException extends FormException { private static final long serialVersionUID = 1351471356522040519L; /** * Set the caller and the error message */ public FormFatalException(String caller, String message) { super(caller, SilverpeasException.ERROR, message); } /** * Set the caller, the error message and the nested exception. */ public FormFatalException(String caller, String message, Exception nestedException) { super(caller, SilverpeasException.ERROR, message, nestedException); } /** * Set the caller, infos and the error message */ public FormFatalException(String caller, String message, String infos) { super(caller, SilverpeasException.ERROR, message, infos); } /** * Set the caller, the error message, infos and the nested exception. */ public FormFatalException(String caller, String message, String infos, Exception nestedException) { super(caller, SilverpeasException.ERROR, message, infos, nestedException); } }
agpl-3.0
roskens/opennms-pre-github
opennms-webapp/src/main/java/org/opennms/web/rest/ValidatingMessageBodyReader.java
3480
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.rest; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlRootElement; import org.opennms.core.xml.JaxbUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; @Provider public class ValidatingMessageBodyReader<T> implements MessageBodyReader<T> { private static final Logger LOG = LoggerFactory.getLogger(ValidatingMessageBodyReader.class); @Context protected Providers providers; /** * @return true if the class is a JAXB-marshallable class that has * an {@link javax.xml.bind.annotation.XmlRootElement} annotation. */ @Override public boolean isReadable(final Class<?> clazz, final Type type, final Annotation[] annotations, final MediaType mediaType) { return (clazz.getAnnotation(XmlRootElement.class) != null); } @Override public T readFrom(final Class<T> clazz, final Type type, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> parameters, final InputStream stream) throws IOException, WebApplicationException { LOG.debug("readFrom: {}/{}/{}", clazz.getSimpleName(), type, mediaType); JAXBContext jaxbContext = null; final ContextResolver<JAXBContext> resolver = providers.getContextResolver(JAXBContext.class, mediaType); try { if (resolver != null) { jaxbContext = resolver.getContext(clazz); } if (jaxbContext == null) { jaxbContext = JAXBContext.newInstance(clazz); } return JaxbUtils.unmarshal(clazz, new InputSource(stream), jaxbContext); } catch (final JAXBException e) { LOG.warn("An error occurred while unmarshaling a {} object", clazz.getSimpleName(), e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } } }
agpl-3.0
smrealms/smrv2.0
engine/Default/logoff.php
136
<?php // Remove the lock if we're holding one (ie logged off from game screen) if($lock) { release_lock(); } SmrSession::destroy(); ?>
agpl-3.0
flyingSkull/dl-shopware
engine/Library/Zend/Feed/Rss.php
20141
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Rss.php 23772 2011-02-28 21:35:29Z ralph $ */ /** * @see Zend_Feed_Abstract */ require_once 'Zend/Feed/Abstract.php'; /** * @see Zend_Feed_Entry_Rss */ require_once 'Zend/Feed/Entry/Rss.php'; /** * RSS channel class * * The Zend_Feed_Rss class is a concrete subclass of * Zend_Feed_Abstract meant for representing RSS channels. It does not * add any methods to its parent, just provides a classname to check * against with the instanceof operator, and expects to be handling * RSS-formatted data instead of Atom. * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Rss extends Zend_Feed_Abstract { /** * The classname for individual channel elements. * * @var string */ protected $_entryClassName = 'Zend_Feed_Entry_Rss'; /** * The element name for individual channel elements (RSS <item>s). * * @var string */ protected $_entryElementName = 'item'; /** * The default namespace for RSS channels. * * @var string */ protected $_defaultNamespace = 'rss'; /** * Override Zend_Feed_Abstract to set up the $_element and $_entries aliases. * * @return void * @throws Zend_Feed_Exception */ public function __wakeup() { parent::__wakeup(); // Find the base channel element and create an alias to it. $rdfTags = $this->_element->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'RDF'); if ($rdfTags->length != 0) { $this->_element = $rdfTags->item(0); } else { $this->_element = $this->_element->getElementsByTagName('channel')->item(0); } if (!$this->_element) { /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('No root <channel> element found, cannot parse channel.'); } // Find the entries and save a pointer to them for speed and // simplicity. $this->_buildEntryCache(); } /** * Make accessing some individual elements of the channel easier. * * Special accessors 'item' and 'items' are provided so that if * you wish to iterate over an RSS channel's items, you can do so * using foreach ($channel->items as $item) or foreach * ($channel->item as $item). * * @param string $var The property to access. * @return mixed */ public function __get($var) { switch ($var) { case 'item': // fall through to the next case case 'items': return $this; default: return parent::__get($var); } } /** * Generate the header of the feed when working in write mode * * @param array $array the data to use * @return DOMElement root node */ protected function _mapFeedHeaders($array) { $channel = $this->_element->createElement('channel'); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($array->title)); $channel->appendChild($title); $link = $this->_element->createElement('link', $array->link); $channel->appendChild($link); $desc = isset($array->description) ? $array->description : ''; $description = $this->_element->createElement('description'); $description->appendChild($this->_element->createCDATASection($desc)); $channel->appendChild($description); $pubdate = isset($array->lastUpdate) ? $array->lastUpdate : time(); $pubdate = $this->_element->createElement('pubDate', date(DATE_RSS, $pubdate)); $channel->appendChild($pubdate); if (isset($array->published)) { $lastBuildDate = $this->_element->createElement('lastBuildDate', date(DATE_RSS, $array->published)); $channel->appendChild($lastBuildDate); } $editor = ''; if (!empty($array->email)) { $editor .= $array->email; } if (!empty($array->author)) { $editor .= ' (' . $array->author . ')'; } if (!empty($editor)) { $author = $this->_element->createElement('managingEditor', ltrim($editor)); $channel->appendChild($author); } if (isset($array->webmaster)) { $channel->appendChild($this->_element->createElement('webMaster', $array->webmaster)); } if (!empty($array->copyright)) { $copyright = $this->_element->createElement('copyright', $array->copyright); $channel->appendChild($copyright); } if (isset($array->category)) { $category = $this->_element->createElement('category', $array->category); $channel->appendChild($category); } if (!empty($array->image)) { $image = $this->_element->createElement('image'); $url = $this->_element->createElement('url', $array->image); $image->appendChild($url); $imagetitle = $this->_element->createElement('title'); $imagetitle->appendChild($this->_element->createCDATASection($array->title)); $image->appendChild($imagetitle); $imagelink = $this->_element->createElement('link', $array->link); $image->appendChild($imagelink); $channel->appendChild($image); } $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed'; $generator = $this->_element->createElement('generator', $generator); $channel->appendChild($generator); if (!empty($array->language)) { $language = $this->_element->createElement('language', $array->language); $channel->appendChild($language); } $doc = $this->_element->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss'); $channel->appendChild($doc); if (isset($array->cloud)) { $cloud = $this->_element->createElement('cloud'); $cloud->setAttribute('domain', $array->cloud['uri']->getHost()); $cloud->setAttribute('port', $array->cloud['uri']->getPort()); $cloud->setAttribute('path', $array->cloud['uri']->getPath()); $cloud->setAttribute('registerProcedure', $array->cloud['procedure']); $cloud->setAttribute('protocol', $array->cloud['protocol']); $channel->appendChild($cloud); } if (isset($array->ttl)) { $ttl = $this->_element->createElement('ttl', $array->ttl); $channel->appendChild($ttl); } if (isset($array->rating)) { $rating = $this->_element->createElement('rating', $array->rating); $channel->appendChild($rating); } if (isset($array->textInput)) { $textinput = $this->_element->createElement('textInput'); $textinput->appendChild($this->_element->createElement('title', $array->textInput['title'])); $textinput->appendChild($this->_element->createElement('description', $array->textInput['description'])); $textinput->appendChild($this->_element->createElement('name', $array->textInput['name'])); $textinput->appendChild($this->_element->createElement('link', $array->textInput['link'])); $channel->appendChild($textinput); } if (isset($array->skipHours)) { $skipHours = $this->_element->createElement('skipHours'); foreach ($array->skipHours as $hour) { $skipHours->appendChild($this->_element->createElement('hour', $hour)); } $channel->appendChild($skipHours); } if (isset($array->skipDays)) { $skipDays = $this->_element->createElement('skipDays'); foreach ($array->skipDays as $day) { $skipDays->appendChild($this->_element->createElement('day', $day)); } $channel->appendChild($skipDays); } if (isset($array->itunes)) { $this->_buildiTunes($channel, $array); } return $channel; } /** * Adds the iTunes extensions to a root node * * @param DOMElement $root * @param array $array * @return void */ private function _buildiTunes(DOMElement $root, $array) { /* author node */ $author = ''; if (isset($array->itunes->author)) { $author = $array->itunes->author; } elseif (isset($array->author)) { $author = $array->author; } if (!empty($author)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:author', $author); $root->appendChild($node); } /* owner node */ $author = ''; $email = ''; if (isset($array->itunes->owner)) { if (isset($array->itunes->owner['name'])) { $author = $array->itunes->owner['name']; } if (isset($array->itunes->owner['email'])) { $email = $array->itunes->owner['email']; } } if (empty($author) && isset($array->author)) { $author = $array->author; } if (empty($email) && isset($array->email)) { $email = $array->email; } if (!empty($author) || !empty($email)) { $owner = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:owner'); if (!empty($author)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:name', $author); $owner->appendChild($node); } if (!empty($email)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:email', $email); $owner->appendChild($node); } $root->appendChild($owner); } $image = ''; if (isset($array->itunes->image)) { $image = $array->itunes->image; } elseif (isset($array->image)) { $image = $array->image; } if (!empty($image)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:image'); $node->setAttribute('href', $image); $root->appendChild($node); } $subtitle = ''; if (isset($array->itunes->subtitle)) { $subtitle = $array->itunes->subtitle; } elseif (isset($array->description)) { $subtitle = $array->description; } if (!empty($subtitle)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:subtitle', $subtitle); $root->appendChild($node); } $summary = ''; if (isset($array->itunes->summary)) { $summary = $array->itunes->summary; } elseif (isset($array->description)) { $summary = $array->description; } if (!empty($summary)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:summary', $summary); $root->appendChild($node); } if (isset($array->itunes->block)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:block', $array->itunes->block); $root->appendChild($node); } if (isset($array->itunes->explicit)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:explicit', $array->itunes->explicit); $root->appendChild($node); } if (isset($array->itunes->keywords)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:keywords', $array->itunes->keywords); $root->appendChild($node); } if (isset($array->itunes->new_feed_url)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:new-feed-url', $array->itunes->new_feed_url); $root->appendChild($node); } if (isset($array->itunes->category)) { foreach ($array->itunes->category as $i => $category) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category'); $node->setAttribute('text', $category['main']); $root->appendChild($node); $add_end_category = false; if (!empty($category['sub'])) { $add_end_category = true; $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category'); $node->setAttribute('text', $category['sub']); $root->appendChild($node); } if ($i > 0 || $add_end_category) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category'); $root->appendChild($node); } } } } /** * Generate the entries of the feed when working in write mode * * The following nodes are constructed for each feed entry * <item> * <title>entry title</title> * <link>url to feed entry</link> * <guid>url to feed entry</guid> * <description>short text</description> * <content:encoded>long version, can contain html</content:encoded> * </item> * * @param DOMElement $root the root node to use * @param array $array the data to use * @return void */ protected function _mapFeedEntries(DOMElement $root, $array) { Zend_Feed::registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/'); foreach ($array as $dataentry) { $item = $this->_element->createElement('item'); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($dataentry->title)); $item->appendChild($title); if (isset($dataentry->author)) { $author = $this->_element->createElement('author', $dataentry->author); $item->appendChild($author); } $link = $this->_element->createElement('link', $dataentry->link); $item->appendChild($link); if (isset($dataentry->guid)) { $guid = $this->_element->createElement('guid', $dataentry->guid); if (!Zend_Uri::check($dataentry->guid)) { $guid->setAttribute('isPermaLink', 'false'); } $item->appendChild($guid); } $description = $this->_element->createElement('description'); $description->appendChild($this->_element->createCDATASection($dataentry->description)); $item->appendChild($description); if (isset($dataentry->content)) { $content = $this->_element->createElement('content:encoded'); $content->appendChild($this->_element->createCDATASection($dataentry->content)); $item->appendChild($content); } $pubdate = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time(); $pubdate = $this->_element->createElement('pubDate', date(DATE_RSS, $pubdate)); $item->appendChild($pubdate); if (isset($dataentry->category)) { foreach ($dataentry->category as $category) { $node = $this->_element->createElement('category', $category['term']); if (isset($category['scheme'])) { $node->setAttribute('domain', $category['scheme']); } $item->appendChild($node); } } if (isset($dataentry->source)) { $source = $this->_element->createElement('source', $dataentry->source['title']); $source->setAttribute('url', $dataentry->source['url']); $item->appendChild($source); } if (isset($dataentry->comments)) { $comments = $this->_element->createElement('comments', $dataentry->comments); $item->appendChild($comments); } if (isset($dataentry->commentRss)) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:commentRss', $dataentry->commentRss); $item->appendChild($comments); } if (isset($dataentry->enclosure)) { foreach ($dataentry->enclosure as $enclosure) { $node = $this->_element->createElement('enclosure'); $node->setAttribute('url', $enclosure['url']); if (isset($enclosure['type'])) { $node->setAttribute('type', $enclosure['type']); } if (isset($enclosure['length'])) { $node->setAttribute('length', $enclosure['length']); } $item->appendChild($node); } } $root->appendChild($item); } } /** * Override Zend_Feed_Element to include <rss> root node * * @return string */ public function saveXml() { // Return a complete document including XML prologue. $doc = new DOMDocument($this->_element->ownerDocument->version, $this->_element->ownerDocument->actualEncoding); $root = $doc->createElement('rss'); // Use rss version 2.0 $root->setAttribute('version', '2.0'); // Content namespace $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:content', 'http://purl.org/rss/1.0/modules/content/'); $root->appendChild($doc->importNode($this->_element, true)); // Append root node $doc->appendChild($root); // Format output $doc->formatOutput = true; return $doc->saveXML(); } /** * Send feed to a http client with the correct header * * @return void * @throws Zend_Feed_Exception if headers have already been sent */ public function send() { if (headers_sent()) { /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Cannot send RSS because headers have already been sent.'); } header('Content-Type: application/rss+xml; charset=' . $this->_element->ownerDocument->actualEncoding); echo $this->saveXml(); } }
agpl-3.0
codegram/decidim
decidim-sortitions/spec/helpers/decidim/sortitions/sortitions_helper_spec.rb
1813
# frozen_string_literal: true require "spec_helper" module Decidim module Sortitions describe SortitionsHelper do describe "proposal_path" do let(:proposal) { create(:proposal) } it "Returns a path for a proposal" do expect(helper.proposal_path(proposal)).not_to be_blank end end describe "sortition_category_label" do let(:sortition) { create(:sortition) } context "when uncategorized sortition" do it "returns from all categories" do expect(helper.sortition_category_label(sortition)).to eq("from all categories") end end context "when categorized sortition" do let(:category) { create(:category, participatory_space: sortition.component.participatory_space) } before do Decidim::Categorization.create!( decidim_category_id: category.id, categorizable: sortition ) sortition.reload end it "returns from the given category" do expect(helper.sortition_category_label(sortition)).to eq("from the #{category.name["en"]} category") end end end describe "sortition_proposal_candidate_ids" do let(:sortition) { create(:sortition) } let!(:label) { helper.sortition_proposal_candidate_ids(sortition) } it "Contains all candidate proposal ids" do sortition.candidate_proposals.each do |proposal_id| expect(label).to include proposal_id.to_s end end it "Selected proposal ids appear in bold" do sortition.selected_proposals.each do |proposal_id| expect(label).to include "<b>#{proposal_id}</b>" end end end end end end
agpl-3.0
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/contribution/attachment/model/HistorisedDocumentVersion.java
2492
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.contribution.attachment.model; import java.util.ArrayList; import java.util.Iterator; /** * This class permits to get an historised document behaviour not from the master version but * from a frozen version of the document. * The history is accorded to the specified version. * To obtain the master version, please use {@link #getVersionMaster()} method. * To check if the current instance is indexed on master version, * please use {@link #isVersionMaster()} method. * @author Yohann Chastagnier */ public class HistorisedDocumentVersion extends HistorisedDocument { private static final long serialVersionUID = -3077658530477641631L; /** * Default constructor. * @param version the simple document version from which the historised document is indexed. */ public HistorisedDocumentVersion(SimpleDocumentVersion version) { super(version); setVersionMaster(version.getVersionMaster()); setHistory(new ArrayList<SimpleDocumentVersion>(version.getVersionMaster().getHistory())); Iterator<SimpleDocumentVersion> historyIt = getHistory().iterator(); while (historyIt.hasNext()) { SimpleDocumentVersion currentVersion = historyIt.next(); if (currentVersion.getVersionIndex() >= getVersionIndex()) { historyIt.remove(); } else { break; } } } }
agpl-3.0
gcoop-libre/SuiteCRM
ModuleInstall/PackageManager/PackageManager.php
38124
<?php /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ define("CREDENTIAL_CATEGORY", "ml"); define("CREDENTIAL_USERNAME", "username"); define("CREDENTIAL_PASSWORD", "password"); require_once('include/nusoap/nusoap.php'); // TODO: is it needed? require_once('include/utils/zip_utils.php'); require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php'); require_once('ModuleInstall/ModuleInstaller.php'); require_once('include/entryPoint.php'); require_once('ModuleInstall/PackageManager/PackageManagerComm.php'); class PackageManager { public $soap_client; /** * Constructor: In this method we will initialize the nusoap client to point to the hearbeat server */ public function __construct() { $this->db = DBManagerFactory::getInstance(); $this->upload_dir = empty($GLOBALS['sugar_config']['upload_dir']) ? 'upload' : rtrim($GLOBALS['sugar_config']['upload_dir'], '/\\'); } /** * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead */ public function PackageManager() { $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code'; if (isset($GLOBALS['log'])) { $GLOBALS['log']->deprecated($deprecatedMessage); } else { trigger_error($deprecatedMessage, E_USER_DEPRECATED); } self::__construct(); } public function initializeComm() { } /** * Obtain a promotion from SugarDepot * @return string the string from the promotion */ public function getPromotion() { $name_value_list = PackageManagerComm::getPromotion(); if (!empty($name_value_list)) { $name_value_list = PackageManager::fromNameValueList($name_value_list); return $name_value_list['description']; } else { return ''; } } /** * Obtain a list of category/packages/releases for use within the module loader */ public function getModuleLoaderCategoryPackages($category_id = '') { $filter = array(); $filter = array('type' => "'module', 'theme', 'langpack'"); $filter = PackageManager::toNameValueList($filter); return PackageManager::getCategoryPackages($category_id, $filter); } /** * Obtain the list of category_packages from SugarDepot * @return category_packages */ public function getCategoryPackages($category_id = '', $filter = array()) { $results = PackageManagerComm::getCategoryPackages($category_id, $filter); PackageManagerComm::errorCheck(); $nodes = array(); $nodes[$category_id]['packages'] = array(); if (!empty($results['categories'])) { foreach ($results['categories'] as $category) { $mycat = PackageManager::fromNameValueList($category); $nodes[$mycat['id']] = array('id' => $mycat['id'], 'label' => $mycat['name'], 'description' => $mycat['description'], 'type' => 'cat', 'parent' => $mycat['parent_id']); $nodes[$mycat['id']]['packages'] = array(); } } if (!empty($results['packages'])) { $uh = new UpgradeHistory(); foreach ($results['packages'] as $package) { $mypack = PackageManager::fromNameValueList($package); $nodes[$mypack['category_id']]['packages'][$mypack['id']] = array('id' => $mypack['id'], 'label' => $mypack['name'], 'description' => $mypack['description'], 'category_id' => $mypack['category_id'], 'type' => 'package'); $releases = PackageManager::getReleases($category_id, $mypack['id'], $filter); $arr_releases = array(); $nodes[$mypack['category_id']]['packages'][$mypack['id']]['releases'] = array(); if (!empty($releases['packages'])) { foreach ($releases['packages'] as $release) { $myrelease = PackageManager::fromNameValueList($release); //check to see if we already this one installed $result = $uh->determineIfUpgrade($myrelease['id_name'], $myrelease['version']); $enable = false; if ($result == true || is_array($result)) { $enable = true; } $nodes[$mypack['category_id']]['packages'][$mypack['id']]['releases'][$myrelease['id']] = array('id' => $myrelease['id'], 'version' => $myrelease['version'], 'label' => $myrelease['description'], 'category_id' => $mypack['category_id'], 'package_id' => $mypack['id'], 'type' => 'release', 'enable' => $enable); } } //array_push($nodes[$mypack['category_id']]['packages'], $package_arr); } } $GLOBALS['log']->debug("NODES". var_export($nodes, true)); return $nodes; } /** * Get a list of categories from the SugarDepot * @param category_id the category id of parent to obtain * @param filter an array of filters to pass to limit the query * @return array an array of categories for display on the client */ public function getCategories($category_id, $filter = array()) { $nodes = array(); $results = PackageManagerComm::getCategories($category_id, $filter); PackageManagerComm::errorCheck(); if (!empty($results['categories'])) { foreach ($results['categories'] as $category) { $mycat = PackageManager::fromNameValueList($category); $nodes[] = array('id' => $mycat['id'], 'label' => $mycat['name'], 'description' => $mycat['description'], 'type' => 'cat', 'parent' => $mycat['parent_id']); } } return $nodes; } public function getPackages($category_id, $filter = array()) { $nodes = array(); $results = PackageManagerComm::getPackages($category_id, $filter); PackageManagerComm::errorCheck(); $packages = array(); //$xml = ''; //$xml .= '<packages>'; if (!empty($results['packages'])) { foreach ($results['packages'] as $package) { $mypack = PackageManager::fromNameValueList($package); $packages[$mypack['id']] = array('package_id' => $mypack['id'], 'name' => $mypack['name'], 'description' => $mypack['description'], 'category_id' => $mypack['category_id']); $releases = PackageManager::getReleases($category_id, $mypack['id']); $arr_releases = array(); foreach ($releases['packages'] as $release) { $myrelease = PackageManager::fromNameValueList($release); $arr_releases[$myrelease['id']] = array('release_id' => $myrelease['id'], 'version' => $myrelease['version'], 'description' => $myrelease['description'], 'category_id' => $mypack['category_id'], 'package_id' => $mypack['id']); } $packages[$mypack['id']]['releases'] = $arr_releases; } } return $packages; } public function getReleases($category_id, $package_id, $filter = array()) { $releases = PackageManagerComm::getReleases($category_id, $package_id, $filter); PackageManagerComm::errorCheck(); return $releases; } /** * Retrieve the package as specified by the $id from the heartbeat server * * @param category_id the category_id to which the release belongs * @param package_id the package_id to which the release belongs * @param release_id the release_id to download * @return filename - the path to which the zip file was saved */ public function download($category_id, $package_id, $release_id) { $GLOBALS['log']->debug('RELEASE _ID: '.$release_id); if (!empty($release_id)) { $filename = PackageManagerComm::addDownload($category_id, $package_id, $release_id); if ($filename) { $GLOBALS['log']->debug('RESULT: '.$filename); PackageManagerComm::errorCheck(); $filepath = PackageManagerComm::performDownload($filename); return $filepath; } } else { return null; } } /** * Given the Mambo username, password, and download key attempt to authenticate, if * successful then store these credentials * * @param username Mambo username * @param password Mambo password * @param systemname the user's download key * @return true if successful, false otherwise */ public function authenticate($username, $password, $systemname='', $terms_checked = true) { PackageManager::setCredentials($username, $password, $systemname); PackageManagerComm::clearSession(); $result = PackageManagerComm::login($terms_checked); if (is_array($result)) { return $result; } else { return true; } } public function setCredentials($username, $password, $systemname) { $admin = new Administration(); $admin->retrieveSettings(); $admin->saveSetting(CREDENTIAL_CATEGORY, CREDENTIAL_USERNAME, $username); $admin->saveSetting(CREDENTIAL_CATEGORY, CREDENTIAL_PASSWORD, $password); if (!empty($systemname)) { $admin->saveSetting('system', 'name', $systemname); } } public static function getCredentials() { $admin = new Administration(); $admin->retrieveSettings(CREDENTIAL_CATEGORY, true); $credentials = array(); $credentials['username'] = ''; $credentials['password'] = ''; $credentials['system_name'] = ''; if (!empty($admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME])) { $credentials['username'] = $admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME]; } if (!empty($admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME])) { $credentials['password'] = $admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_PASSWORD]; } if (!empty($admin->settings['system_name'])) { $credentials['system_name'] = $admin->settings['system_name']; } return $credentials; } public function getTermsAndConditions() { return PackageManagerComm::getTermsAndConditions(); } /** * Retrieve documentation for the given release or package * * @param package_id the specified package to retrieve documentation * @param release_id the specified release to retrieve documentation * * @return documents */ public function getDocumentation($package_id, $release_id) { if (!empty($release_id) || !empty($package_id)) { $documents = PackageManagerComm::getDocumentation($package_id, $release_id); return $documents; } else { return null; } } /** * Grab the list of installed modules and send that list to the depot. * The depot will then send back a list of modules that need to be updated */ public function checkForUpdates() { $lists = $this->buildInstalledReleases(array('module'), true); $updates = array(); if (!empty($lists)) { $updates = PackageManagerComm::checkForUpdates($lists); }//fi return $updates; } //////////////////////////////////////////////////////// /////////// HELPER FUNCTIONS public function toNameValueList($array) { $list = array(); foreach ($array as $name=>$value) { $list[] = array('name'=>$name, 'value'=>$value); } return $list; } public function toNameValueLists($arrays) { $lists = array(); foreach ($arrays as $array) { $lists[] = PackageManager::toNameValueList($array); } return $lists; } public function fromNameValueList($nvl) { $array = array(); foreach ($nvl as $list) { $array[$list['name']] = $list['value']; } return $array; } public function buildInstalledReleases($types = array('module')) { //1) get list of installed modules $installeds = $this->getInstalled($types); $releases = array(); foreach ($installeds as $installed) { $releases[] = array('name' => $installed->name, 'id_name' => $installed->id_name, 'version' => $installed->version, 'filename' => $installed->filename, 'type' => $installed->type); } $lists = array(); $name_value_list = array(); if (!empty($releases)) { $lists = $this->toNameValueLists($releases); }//fi return $lists; } public function buildPackageXML($package, $releases = array()) { $xml = '<package>'; $xml .= '<package_id>'.$package['id'].'</package_id>'; $xml .= '<name>'.$package['name'].'</name>'; $xml .= '<description>'.$package['description'].'</description>'; if (!empty($releases)) { $xml .= '<releases>'; foreach ($releases['packages'] as $release) { $myrelease = PackageManager::fromNameValueList($release); $xml .= '<release>'; $xml .= '<release_id>'.$myrelease['id'].'</release_id>'; $xml .= '<version>'.$myrelease['version'].'</version>'; $xml .= '<description>'.$myrelease['description'].'</description>'; $xml .= '<package_id>'.$package['id'].'</package_id>'; $xml .= '<category_id>'.$package['category_id'].'</category_id>'; $xml .= '</release>'; } $xml .= '</releases>'; } $xml .= '</package>'; return $xml; } private $cleanUpDirs = array(); private function addToCleanup($dir) { if (empty($this->cleanUpDirs)) { register_shutdown_function(array($this, "cleanUpTempDir")); } $this->cleanUpDirs[] = $dir; } public function cleanUpTempDir() { foreach ($this->cleanUpDirs as $dir) { rmdir_recursive($dir); } } ////////////////////////////////////////////////////////////////////// /////////// INSTALL SECTION public function extractFile($zip_file, $file_in_zip, $base_tmp_upgrade_dir) { $my_zip_dir = mk_temp_dir($base_tmp_upgrade_dir); $this->addToCleanup($my_zip_dir); unzip_file($zip_file, $file_in_zip, $my_zip_dir); return("$my_zip_dir/$file_in_zip"); } public function extractManifest($zip_file, $base_tmp_upgrade_dir) { global $sugar_config; $base_upgrade_dir = $this->upload_dir."/upgrades"; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; return $this->extractFile($zip_file, "manifest.php", $base_tmp_upgrade_dir); } public function validate_manifest($manifest) { // takes a manifest.php manifest array and validates contents global $subdirs; global $sugar_version; global $sugar_flavor; global $mod_strings; if (!isset($manifest['type'])) { die($mod_strings['ERROR_MANIFEST_TYPE']); } $type = $manifest['type']; $GLOBALS['log']->debug("Getting InstallType"); if ($this->getInstallType("/$type/") == "") { $GLOBALS['log']->debug("Error with InstallType".$type); die($mod_strings['ERROR_PACKAGE_TYPE']. ": '" . $type . "'."); } $GLOBALS['log']->debug("Passed with InstallType"); if (isset($manifest['acceptable_sugar_versions'])) { $version_ok = false; $matches_empty = true; if (isset($manifest['acceptable_sugar_versions']['exact_matches'])) { $matches_empty = false; foreach ($manifest['acceptable_sugar_versions']['exact_matches'] as $match) { if ($match == $sugar_version) { $version_ok = true; } } } if (!$version_ok && isset($manifest['acceptable_sugar_versions']['regex_matches'])) { $matches_empty = false; foreach ($manifest['acceptable_sugar_versions']['regex_matches'] as $match) { if (preg_match("/$match/", $sugar_version)) { $version_ok = true; } } } if (!$matches_empty && !$version_ok) { die($mod_strings['ERROR_VERSION_INCOMPATIBLE'] . $sugar_version); } } } public function getInstallType($type_string) { // detect file type global $subdirs; $subdirs = array('full', 'langpack', 'module', 'patch', 'theme', 'temp'); foreach ($subdirs as $subdir) { if (preg_match("#/$subdir/#", $type_string)) { return($subdir); } } // return empty if no match return(""); } public function performSetup($tempFile, $view = 'module', $display_messages = true) { global $sugar_config,$mod_strings; $base_filename = urldecode($tempFile); $GLOBALS['log']->debug("BaseFileName: ".$base_filename); $base_upgrade_dir = $this->upload_dir.'/upgrades'; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; $manifest_file = $this->extractManifest($base_filename, $base_tmp_upgrade_dir); $GLOBALS['log']->debug("Manifest: ".$manifest_file); if ($view == 'module') { $license_file = $this->extractFile($base_filename, 'LICENSE.txt', $base_tmp_upgrade_dir); } if (is_file($manifest_file)) { $GLOBALS['log']->debug("VALIDATING MANIFEST". $manifest_file); require_once($manifest_file); $this->validate_manifest($manifest); $upgrade_zip_type = $manifest['type']; $GLOBALS['log']->debug("VALIDATED MANIFEST"); // exclude the bad permutations if ($view == "module") { if ($upgrade_zip_type != "module" && $upgrade_zip_type != "theme" && $upgrade_zip_type != "langpack") { $this->unlinkTempFiles(); if ($display_messages) { die($mod_strings['ERR_UW_NOT_ACCEPTIBLE_TYPE']); } } } elseif ($view == "default") { if ($upgrade_zip_type != "patch") { $this->unlinkTempFiles(); if ($display_messages) { die($mod_strings['ERR_UW_ONLY_PATCHES']); } } } $base_filename = preg_replace("#\\\\#", "/", $base_filename); $base_filename = basename($base_filename); mkdir_recursive("$base_upgrade_dir/$upgrade_zip_type"); $target_path = "$base_upgrade_dir/$upgrade_zip_type/$base_filename"; $target_manifest = remove_file_extension($target_path) . "-manifest.php"; if (isset($manifest['icon']) && $manifest['icon'] != "") { $icon_location = $this->extractFile($tempFile, $manifest['icon'], $base_tmp_upgrade_dir); $path_parts = pathinfo($icon_location); copy($icon_location, remove_file_extension($target_path) . "-icon." . $path_parts['extension']); } if (copy($tempFile, $target_path)) { copy($manifest_file, $target_manifest); if ($display_messages) { $messages = '<script>ajaxStatus.flashStatus("' .$base_filename.$mod_strings['LBL_UW_UPLOAD_SUCCESS'] . ', 5000");</script>'; } } else { if ($display_messages) { $messages = '<script>ajaxStatus.flashStatus("' .$mod_strings['ERR_UW_UPLOAD_ERROR'] . ', 5000");</script>'; } } }//fi else { $this->unlinkTempFiles(); if ($display_messages) { die($mod_strings['ERR_UW_NO_MANIFEST']); } } if (isset($messages)) { return $messages; } } public function unlinkTempFiles() { global $sugar_config; @unlink($_FILES['upgrade_zip']['tmp_name']); @unlink("upload://".$_FILES['upgrade_zip']['name']); } public function performInstall($file, $silent=true) { global $sugar_config; global $mod_strings; global $current_language; $base_upgrade_dir = $this->upload_dir.'/upgrades'; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; if (!file_exists($base_tmp_upgrade_dir)) { mkdir_recursive($base_tmp_upgrade_dir, true); } $GLOBALS['log']->debug("INSTALLING: ".$file); $mi = new ModuleInstaller(); $mi->silent = $silent; $mod_strings = return_module_language($current_language, "Administration"); $GLOBALS['log']->debug("ABOUT TO INSTALL: ".$file); if (preg_match("#.*\.zip\$#", $file)) { $GLOBALS['log']->debug("1: ".$file); // handle manifest.php $target_manifest = remove_file_extension($file) . '-manifest.php'; include($target_manifest); $GLOBALS['log']->debug("2: ".$file); $unzip_dir = mk_temp_dir($base_tmp_upgrade_dir); $this->addToCleanup($unzip_dir); unzip($file, $unzip_dir); $GLOBALS['log']->debug("3: ".$unzip_dir); $id_name = $installdefs['id']; $version = $manifest['version']; $uh = new UpgradeHistory(); $previous_install = array(); if (!empty($id_name) & !empty($version)) { $previous_install = $uh->determineIfUpgrade($id_name, $version); } $previous_version = (empty($previous_install['version'])) ? '' : $previous_install['version']; $previous_id = (empty($previous_install['id'])) ? '' : $previous_install['id']; if (!empty($previous_version)) { $mi->install($unzip_dir, true, $previous_version); } else { $mi->install($unzip_dir); } $GLOBALS['log']->debug("INSTALLED: ".$file); $new_upgrade = new UpgradeHistory(); $new_upgrade->filename = $file; $new_upgrade->md5sum = md5_file($file); $new_upgrade->type = $manifest['type']; $new_upgrade->version = $manifest['version']; $new_upgrade->status = "installed"; //$new_upgrade->author = $manifest['author']; $new_upgrade->name = $manifest['name']; $new_upgrade->description = $manifest['description']; $new_upgrade->id_name = $id_name; $serial_manifest = array(); $serial_manifest['manifest'] = (isset($manifest) ? $manifest : ''); $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : ''); $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : ''); $new_upgrade->manifest = base64_encode(serialize($serial_manifest)); //$new_upgrade->unique_key = (isset($manifest['unique_key'])) ? $manifest['unique_key'] : ''; $new_upgrade->save(); //unlink($file); }//fi } public function performUninstall($name) { $uh = new UpgradeHistory(); $uh->name = $name; $uh->id_name = $name; $found = $uh->checkForExisting($uh); if ($found != null) { global $sugar_config; global $mod_strings; global $current_language; $base_upgrade_dir = $this->upload_dir.'/upgrades'; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; if (is_file($found->filename)) { if (!isset($GLOBALS['mi_remove_tables'])) { $GLOBALS['mi_remove_tables'] = true; } $unzip_dir = mk_temp_dir($base_tmp_upgrade_dir); unzip($found->filename, $unzip_dir); $mi = new ModuleInstaller(); $mi->silent = true; $mi->uninstall("$unzip_dir"); $found->delete(); unlink(remove_file_extension($found->filename) . '-manifest.php'); unlink($found->filename); } else { //file(s_ have been deleted or are not found in the directory, allow database delete to happen but no need to change filesystem $found->delete(); } } } public function getUITextForType($type) { if ($type == "full") { return("Full Upgrade"); } if ($type == "langpack") { return("Language Pack"); } if ($type == "module") { return("Module"); } if ($type == "patch") { return("Patch"); } if ($type == "theme") { return("Theme"); } } public function getImageForType($type) { $icon = ""; switch ($type) { case "full": $icon = SugarThemeRegistry::current()->getImage("Upgrade", "", null, null, '.gif', "Upgrade"); break; case "langpack": $icon = SugarThemeRegistry::current()->getImage("LanguagePacks", "", null, null, '.gif', "Language Packs"); break; case "module": $icon = SugarThemeRegistry::current()->getImage("ModuleLoader", "", null, null, '.gif', "Module Loader"); break; case "patch": $icon = SugarThemeRegistry::current()->getImage("PatchUpgrades", "", null, null, '.gif', "Patch Upgrades"); break; case "theme": $icon = SugarThemeRegistry::current()->getImage("Themes", "", null, null, '.gif', "Themes"); break; default: break; } return($icon); } public function getPackagesInStaging($view = 'module') { global $sugar_config; global $current_language; $uh = new UpgradeHistory(); $base_upgrade_dir = "upload://upgrades"; $uContent = findAllFiles($base_upgrade_dir, array(), false, 'zip'); $upgrade_contents = array(); $content_values = array_values($uContent); $alreadyProcessed = array(); foreach ($content_values as $val) { if (empty($alreadyProcessed[$val])) { $upgrade_contents[] = $val; $alreadyProcessed[$val] = true; } } $upgrades_available = 0; $packages = array(); $mod_strings = return_module_language($current_language, "Administration"); foreach ($upgrade_contents as $upgrade_content) { if (!preg_match('#.*\.zip$#', strtolower($upgrade_content)) || preg_match("#.*./zips/.*#", strtolower($upgrade_content))) { continue; } $the_base = basename($upgrade_content); $the_md5 = md5_file($upgrade_content); $md5_matches = $uh->findByMd5($the_md5); $file_install = $upgrade_content; if (empty($md5_matches)) { $target_manifest = remove_file_extension($upgrade_content) . '-manifest.php'; if (file_exists($target_manifest)) { require_once($target_manifest); $name = empty($manifest['name']) ? $upgrade_content : $manifest['name']; $version = empty($manifest['version']) ? '' : $manifest['version']; $published_date = empty($manifest['published_date']) ? '' : $manifest['published_date']; $icon = ''; $description = empty($manifest['description']) ? 'None' : $manifest['description']; $uninstallable = empty($manifest['is_uninstallable']) ? 'No' : 'Yes'; $type = $this->getUITextForType($manifest['type']); $manifest_type = $manifest['type']; $dependencies = array(); if (isset($manifest['dependencies'])) { $dependencies = $manifest['dependencies']; } } //check dependencies first if (!empty($dependencies)) { $uh = new UpgradeHistory(); $not_found = $uh->checkDependencies($dependencies); if (!empty($not_found) && count($not_found) > 0) { $file_install = 'errors_'.$mod_strings['ERR_UW_NO_DEPENDENCY']."[".implode(',', $not_found)."]"; } } if ($view == 'default' && $manifest_type != 'patch') { continue; } if ($view == 'module' && $manifest_type != 'module' && $manifest_type != 'theme' && $manifest_type != 'langpack') { continue; } if (empty($manifest['icon'])) { $icon = $this->getImageForType($manifest['type']); } else { $path_parts = pathinfo($manifest['icon']); $icon = "<img src=\"" . remove_file_extension($upgrade_content) . "-icon." . $path_parts['extension'] . "\">"; } $upgrades_available++; $packages[] = array('name' => $name, 'version' => $version, 'published_date' => $published_date, 'description' => $description, 'uninstallable' =>$uninstallable, 'type' => $type, 'file' => fileToHash($upgrade_content), 'file_install' => fileToHash($upgrade_content), 'unFile' => fileToHash($upgrade_content)); }//fi }//rof return $packages; } public function getLicenseFromFile($file) { global $sugar_config; $base_upgrade_dir = $this->upload_dir.'/upgrades'; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; $license_file = $this->extractFile($file, 'LICENSE.txt', $base_tmp_upgrade_dir); if (is_file($license_file)) { $contents = file_get_contents($license_file); return $contents; } else { return null; } } /** * Run the query to obtain the list of installed types as specified by the type param * * @param type an array of types you would like to search for * type options include (theme, langpack, module, patch) * * @return an array of installed upgrade_history objects */ public function getInstalled($types = array('module')) { $uh = new UpgradeHistory(); $in = ""; for ($i = 0; $i < count($types); $i++) { $in .= "'".$types[$i]."'"; if (($i+1) < count($types)) { $in .= ","; } } $query = "SELECT * FROM ".$uh->table_name." WHERE type IN (".$in.")"; return $uh->getList($query); } public function getinstalledPackages($types = array('module', 'langpack')) { global $sugar_config; $installeds = $this->getInstalled($types); $packages = array(); $upgrades_installed = 0; $uh = new UpgradeHistory(); $base_upgrade_dir = $this->upload_dir.'/upgrades'; $base_tmp_upgrade_dir = "$base_upgrade_dir/temp"; foreach ($installeds as $installed) { $populate = false; $filename = from_html($installed->filename); $date_entered = $installed->date_entered; $type = $installed->type; $version = $installed->version; $uninstallable = false; $link = ""; $description = $installed->description; $name = $installed->name; $enabled = true; $enabled_string = 'ENABLED'; //if the name is empty then we should try to pull from manifest and populate upgrade_history_table if (empty($name)) { $populate = true; } $upgrades_installed++; switch ($type) { case "theme": case "langpack": case "module": case "patch": if ($populate) { $manifest_file = $this->extractManifest($filename, $base_tmp_upgrade_dir); require_once($manifest_file); $GLOBALS['log']->info("Filling in upgrade_history table"); $populate = false; if (isset($manifest['name'])) { $name = $manifest['name']; $installed->name = $name; } if (isset($manifest['description'])) { $description = $manifest['description']; $installed->description = $description; } if (isset($installdefs) && isset($installdefs['id'])) { $id_name = $installdefs['id']; $installed->id_name = $id_name; } $serial_manifest = array(); $serial_manifest['manifest'] = (isset($manifest) ? $manifest : ''); $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : ''); $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : ''); $installed->manifest = base64_encode(serialize($serial_manifest)); $installed->save(); } else { $serial_manifest = unserialize(base64_decode($installed->manifest)); $manifest = $serial_manifest['manifest']; } if (($upgrades_installed==0 || $uh->UninstallAvailable($installeds, $installed)) && is_file($filename) && !empty($manifest['is_uninstallable'])) { $uninstallable = true; } $enabled = $installed->enabled; if (!$enabled) { $enabled_string = 'DISABLED'; } $file_uninstall = $filename; if (!$uninstallable) { $file_uninstall = 'UNINSTALLABLE'; $enabled_string = 'UNINSTALLABLE'; } else { $file_uninstall = fileToHash($file_uninstall); } $packages[] = array( 'name' => $name, 'version' => $version, 'type' => $type, 'published_date' => $date_entered, 'description' => $description, 'uninstallable' =>$uninstallable, 'file_install' => $file_uninstall , 'file' => fileToHash($filename), 'enabled' => $enabled_string ); break; default: break; } }//rof return $packages; } }
agpl-3.0
cgi-eoss/ftep
third-party/resto/index.php
1344
<?php /* * Copyright 2014 Jérôme Gasperi * * 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. */ /* * Autoload controllers and modules */ function autoload($className) { foreach (array( 'include/resto/', 'include/resto/Drivers/', 'include/resto/Collections/', 'include/resto/Models/', 'include/resto/Dictionaries/', 'include/resto/Modules/', 'include/resto/Routes/', 'include/resto/Utils/', 'include/resto/XML/', 'lib/iTag/', 'lib/JWT/') as $current_dir) { $path = $current_dir . sprintf('%s.php', $className); if (file_exists($path)) { include $path; return; } } } spl_autoload_register('autoload'); /* * Launch RESTo */ new Resto(realpath(dirname(__FILE__)) . '/include/config.php');
agpl-3.0
oktupol/shopware
engine/Shopware/Components/Modules.php
4900
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * @category Shopware * * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class Shopware_Components_Modules extends Enlight_Class implements ArrayAccess { /** * @var sSystem */ protected $system; /** * Container that hold references to all modules already loaded * * @var array */ protected $modules_container = []; /** * @param string $name * @param null $value * * @return mixed */ public function __call($name, $value = null) { return $this->getModule($name); } /** * Set class property * * @param $system */ public function setSystem($system) { $this->system = $system; } /** * Reformat module name and return reference to module * * @param string $name * * @return mixed */ public function getModule($name) { if ($name[0] === 's') { $name = substr($name, 1); } if ($name !== 'RewriteTable') { $name = 's' . ucfirst(strtolower($name)); } else { $name = 's' . $name; } if (!isset($this->modules_container[$name])) { $this->loadModule($name); } return $this->modules_container[$name]; } /** * @param $offset * @param $value */ public function offsetSet($offset, $value) { } /** * @param $offset * * @return bool */ public function offsetExists($offset) { return (bool) $this->getModule($offset); } /** * @param $offset */ public function offsetUnset($offset) { } /** * @param $offset * * @return mixed */ public function offsetGet($offset) { return $this->getModule($offset); } /** * @return sArticles */ public function Articles() { return $this->getModule('Articles'); } /** * @return sCategories */ public function Categories() { return $this->getModule('Categories'); } /** * @return sBasket */ public function Basket() { return $this->getModule('Basket'); } /** * @return sMarketing */ public function Marketing() { return $this->getModule('Marketing'); } /** * @return sSystem */ public function System() { return $this->getModule('System'); } /** * @return sAdmin */ public function Admin() { return $this->getModule('Admin'); } /** * @return sOrder */ public function Order() { return $this->getModule('Order'); } /** * @return sCms */ public function Cms() { return $this->getModule('Cms'); } /** * @return sCore */ public function Core() { return $this->getModule('Core'); } /** * @return sRewriteTable */ public function RewriteTable() { return $this->getModule('RewriteTable'); } /** * @return sExport */ public function Export() { return $this->getModule('Export'); } /** * Load a module defined by $name * Possible values for $name - sBasket, sAdmin etc. * * @param $name */ private function loadModule($name) { if (isset($this->modules_container[$name])) { return; } $this->modules_container[$name] = null; $name = basename($name); if ($name == 'sSystem') { $this->modules_container[$name] = $this->system; return; } Shopware()->Hooks()->setAlias($name, $name); $proxy = Shopware()->Hooks()->getProxy($name); $this->modules_container[$name] = new $proxy(); $this->modules_container[$name]->sSYSTEM = $this->system; } }
agpl-3.0
freyes/juju
provider/manual/instance.go
1543
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package manual import ( "github.com/juju/juju/core/instance" corenetwork "github.com/juju/juju/core/network" "github.com/juju/juju/core/network/firewall" "github.com/juju/juju/core/status" "github.com/juju/juju/environs/context" "github.com/juju/juju/environs/manual" ) type manualBootstrapInstance struct { host string } func (manualBootstrapInstance) Id() instance.Id { return BootstrapInstanceId } func (manualBootstrapInstance) Status(ctx context.ProviderCallContext) instance.Status { // We assume that if we are deploying in manual provider the // underlying machine is clearly running. return instance.Status{ Status: status.Running, } } func (manualBootstrapInstance) Refresh(ctx context.ProviderCallContext) error { return nil } func (inst manualBootstrapInstance) Addresses(ctx context.ProviderCallContext) (corenetwork.ProviderAddresses, error) { addr, err := manual.HostAddress(inst.host) if err != nil { return nil, err } return []corenetwork.ProviderAddress{addr}, nil } func (manualBootstrapInstance) OpenPorts(ctx context.ProviderCallContext, machineId string, rules firewall.IngressRules) error { return nil } func (manualBootstrapInstance) ClosePorts(ctx context.ProviderCallContext, machineId string, rules firewall.IngressRules) error { return nil } func (manualBootstrapInstance) IngressRules(ctx context.ProviderCallContext, machineId string) (firewall.IngressRules, error) { return nil, nil }
agpl-3.0
unitystation/unitystation
UnityProject/Assets/Scripts/Core/Lifecycle/ClientDespawnInfo.cs
792
using UnityEngine; /// <summary> /// Holds details about how an object is being despawned on the client. This is mostly /// a placeholder which prevents having to change the signature of the lifecycle interfaces in the event /// that some component ends up needing some extra info about how it is being spawned. /// /// This is different from DespawnInfo because we don't necesarilly want the client to know the full extent /// of why something was despawned. /// </summary> public class ClientDespawnInfo { private static ClientDespawnInfo defaultInstance = new ClientDespawnInfo(null); //note: currently no data is needed but fields may be added lat private ClientDespawnInfo(GameObject clonedFrom) { } public static ClientDespawnInfo Default() { return defaultInstance; } }
agpl-3.0
fastio/pedis
cql3/attributes.hh
2903
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "exceptions/exceptions.hh" #include "cql3/term.hh" #include <experimental/optional> namespace cql3 { /** * Utility class for the Parser to gather attributes for modification * statements. */ class attributes final { private: const ::shared_ptr<term> _timestamp; const ::shared_ptr<term> _time_to_live; public: static std::unique_ptr<attributes> none(); private: attributes(::shared_ptr<term>&& timestamp, ::shared_ptr<term>&& time_to_live); public: bool uses_function(const sstring& ks_name, const sstring& function_name) const; bool is_timestamp_set() const; bool is_time_to_live_set() const; int64_t get_timestamp(int64_t now, const query_options& options); int32_t get_time_to_live(const query_options& options); void collect_marker_specification(::shared_ptr<variable_specifications> bound_names); class raw { public: ::shared_ptr<term::raw> timestamp; ::shared_ptr<term::raw> time_to_live; std::unique_ptr<attributes> prepare(database& db, const sstring& ks_name, const sstring& cf_name); private: ::shared_ptr<column_specification> timestamp_receiver(const sstring& ks_name, const sstring& cf_name); ::shared_ptr<column_specification> time_to_live_receiver(const sstring& ks_name, const sstring& cf_name); }; }; }
agpl-3.0
yscdaxian/goweb
limesurvey/admin/iterate_survey.php
4241
<?php /* * LimeSurvey * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz * All rights reserved. * License: GNU/GPL License v2 or later, see LICENSE.php * LimeSurvey is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: iterate_survey.php 11143 2011-10-11 19:14:02Z lemeur $ */ /* * Set completed answers to the incomplete state and reset the tokens to 'not used' so that * the survey can be published again to the same set of participants. * Partipants will see their previous answers and may change them. */ include_once('login_check.php'); include('html_functions.php'); if (!isset($surveyid)) {$surveyid=returnglobal('sid');} if (!isset($subaction)) { // subaction is not set, then display instructions $iteratesurveyoutput = browsemenubar($clang->gT('Iterate survey')); $iteratesurveyoutput .= "<div class='header ui-widget-header'>".$clang->gT("Iterate survey")."</div>\n"; $iteratesurveyoutput .= "<div class='messagebox ui-corner-all'><div class='header ui-widget-header'>".$clang->gT("Important instructions")."</div>" . "<br/>".$clang->gT("Click on the following button if you want to").":<br />\n" . "<ol>" . "<li>".$clang->gT("Delete all incomplete answers that correspond to a token for which a completed answers is already recorded")."</li>" . "<li>".$clang->gT("Reset the completed answers to the incomplete state")."</li>" . "<li>".$clang->gT("Reset all your tokens to the 'not used' state")."</li>" . "</ol><br />\n" . "<input type='button' onclick=\"if( confirm('".$clang->gT("Are you really sure you want to *delete* some incomplete answers and reset the completed state of both answers and tokens?","js")."')){".get2post("$scriptname?action=iteratesurvey&amp;sid=$surveyid&amp;subaction=unfinalizeanswers")."}\" value='".$clang->gT("Reset answers and token completed state")."' />" . "</div>"; } if ($subaction=='unfinalizeanswers') { $iteratesurveyoutput = browsemenubar($clang->gT('Iterate survey')); $baselang = GetBaseLanguageFromSurveyID($surveyid); $surveytable = db_table_name("survey_$surveyid"); // First delete incomplete answers that correspond to a token for which a completed answers is already recorded // subquery in delete or update are tricky things when using the same table for delete and Select // see http://www.developpez.net/forums/d494961/bases-donnees/mysql/requetes/cant-specify-target-in-from-clause/ $updateqr = "DELETE from $surveytable WHERE submitdate IS NULL AND token in (SELECT * FROM ( SELECT answ2.token from $surveytable AS answ2 WHERE answ2.submitdate IS NOT NULL) tmp );\n"; // $updateqr = "DELETE from $surveytable WHERE submitdate IS NULL AND token in (SELECT b.token from $surveytable AS b WHERE b.submitdate IS NOT NULL);\n"; //error_log("TIBO query = $updateqr"); $updateres = $connect->Execute($updateqr) or safe_die("Delete incomplete answers with duplicate tokens failed:<br />\n" . $connect->ErrorMsg() . "<br />$updateqr"); // Then set all remaining answers to incomplete state $updateqr = "UPDATE $surveytable SET submitdate=NULL, lastpage=NULL;\n"; $updateres = $connect->Execute($updateqr) or safe_die("UnFinilize answers failed:<br />\n" . $connect->ErrorMsg() . "<br />$updateqr"); // Finally, reset the token completed and sent status $updateqr="UPDATE ".db_table_name("tokens_$surveyid")." SET sent='N', remindersent='N', remindercount=0, completed='N', usesleft=1"; $updateres=$connect->Execute($updateqr) or safe_die ("Couldn't reset token completed state<br />$updateqr<br />".$connect->ErrorMsg()); $iteratesurveyoutput .= "<br />\n"; $iteratesurveyoutput .= "<div class='header ui-widget-header'>".$clang->gT("Iterate survey")."</div>\n"; $iteratesurveyoutput .= "<p style='width:100%;'>\n" . "<font class='successtitle'>".$clang->gT("Success")."</font><br />\n" . $clang->gT("Answers and tokens have been re-opened.")."<br />\n" . "</p>\n" . "<table><tr><td>"; }
agpl-3.0
lat-lon/geoeditor
backend/impl/src/main/java/org/geomajas/spring/ThreadScope.java
2398
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.spring; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.stereotype.Component; /** * Thread scope which allows putting data in thread scope and clearing up afterwards. * * @author Joachim Van der Auwera */ @Component public class ThreadScope implements Scope, DisposableBean { public ThreadScope() { ThreadScopeContextHolder.clear(); } /** * Get bean for given name in the "thread" scope. * * @param name name of bean * @param factory factory for new instances * @return bean for this scope */ public Object get(String name, ObjectFactory<?> factory) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); Object result = context.getBean(name); if (null == result) { result = factory.getObject(); context.setBean(name, result); } return result; } /** * Removes bean from scope. * * @param name bean name * @return previous value */ public Object remove(String name) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); return context.remove(name); } public void registerDestructionCallback(String name, Runnable callback) { ThreadScopeContextHolder.getContext().registerDestructionCallback(name, callback); } /** * Resolve the contextual object for the given key, if any. E.g. the HttpServletRequest object for key "request". * * @param key key * @return contextual object */ public Object resolveContextualObject(String key) { return null; } /** * Return the conversation ID for the current underlying scope, if any. * <p/> * In this case, it returns the thread name. * * @return thread name as conversation id */ public String getConversationId() { return Thread.currentThread().getName(); } public void destroy() throws Exception { ThreadScopeContextHolder.clear(); } }
agpl-3.0
jmertic/sugarplatformdemo
custom/Extension/modules/pos_Feedback/Ext/Language/en_us.POSSCON.php
135
<?php //THIS FILE IS AUTO GENERATED, DO NOT MODIFY $mod_strings['LBL_POS_SESSIONS_POS_FEEDBACK_FROM_POS_SESSIONS_TITLE'] = 'Sessions';
agpl-3.0
Endika/c2c-rd-addons
chricar_room/room.py
3108
# -*- coding: utf-8 -*- #!/usr/bin/python # -*- coding: utf-8 -*- ############################################## # # ChriCar Beteiligungs- und Beratungs- GmbH # Copyright (C) ChriCar Beteiligungs- und Beratungs- GmbH # all rights reserved # created 2009-07-11 12:22:10+02 # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs. # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company. # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, see <http://www.gnu.org/licenses/> or # write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################### import time from openerp.osv import fields,osv #import pooler class chricar_room(osv.osv): _name = "chricar.room" _columns = { 'top_id' : fields.many2one('chricar.top','Top', select=True, required=True), 'name' : fields.char ('Name', size=64, required=True), 'size' : fields.float ('Size', digits=(6,2)), 'height' : fields.float ('Height', digits=(4,2)), 'tv_cable' : fields.boolean ('TV Cable'), 'tv_sat' : fields.boolean ('TV Sat'), 'telephon' : fields.boolean ('Telephon'), 'windows' : fields.integer ('Windows'), 'balcony' : fields.integer ('Balconies'), 'terrace' : fields.integer ('Terrace'), 'garden_access' : fields.boolean ('Garden Access'), 'floor' : fields.selection([('unknown','unknown'), ('stone','Stone'), ('wood','Wood'), ('screed','Screed'), ('tiles','Tiles'), ('carpet','Carpet')], 'Floor'), 'note' : fields.text ('Notes'), 'sequence' : fields.integer ('Sequence'), } _defaults = { } _order = "sequence" chricar_room() class chricar_top(osv.osv): _inherit = "chricar.top" _columns = { 'room_ids': fields.one2many('chricar.room','top_id','Rooms'), } chricar_top()
agpl-3.0
fmbiete/Z-Push-contrib
lib/syncobjects/syncdeviceinformation.php
4003
<?php /*********************************************** * File : syncdeviceinformation.php * Project : Z-Push * Descr : WBXML appointment entities that can be * parsed directly (as a stream) from WBXML. * It is automatically decoded * according to $mapping, * and the Sync WBXML mappings * * Created : 08.11.2011 * * Copyright 2007 - 2013 Zarafa Deutschland GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation with the following additional * term according to sec. 7: * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "Zarafa" is a registered trademark of Zarafa B.V. * "Z-Push" is a registered trademark of Zarafa Deutschland GmbH * The licensing of the Program under the AGPL does not imply a trademark license. * Therefore any rights, title and interest in our trademarks remain entirely with us. * * However, if you propagate an unmodified version of the Program you are * allowed to use the term "Z-Push" to indicate that you distribute the Program. * Furthermore you may use our trademarks where it is necessary to indicate * the intended purpose of a product or service provided you use it in accordance * with honest practices in industrial or commercial matters. * If you want to propagate modified versions of the Program under the name "Z-Push", * you may only do so if you have a written permission by Zarafa Deutschland GmbH * (to acquire a permission please contact Zarafa at trademark@zarafa.com). * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Consult LICENSE file for details ************************************************/ class SyncDeviceInformation extends SyncObject { public $model; public $imei; public $friendlyname; public $os; public $oslanguage; public $phonenumber; public $useragent; //12.1 &14.0 public $mobileoperator; //14.0 public $enableoutboundsms; //14.0 public $Status; public function SyncDeviceInformation() { $mapping = array ( SYNC_SETTINGS_MODEL => array ( self::STREAMER_VAR => "model"), SYNC_SETTINGS_IMEI => array ( self::STREAMER_VAR => "imei"), SYNC_SETTINGS_FRIENDLYNAME => array ( self::STREAMER_VAR => "friendlyname"), SYNC_SETTINGS_OS => array ( self::STREAMER_VAR => "os"), SYNC_SETTINGS_OSLANGUAGE => array ( self::STREAMER_VAR => "oslanguage"), SYNC_SETTINGS_PHONENUMBER => array ( self::STREAMER_VAR => "phonenumber"), SYNC_SETTINGS_PROP_STATUS => array ( self::STREAMER_VAR => "Status", self::STREAMER_TYPE => self::STREAMER_TYPE_IGNORE) ); if (Request::GetProtocolVersion() >= 12.1) { $mapping[SYNC_SETTINGS_USERAGENT] = array ( self::STREAMER_VAR => "useragent"); } if (Request::GetProtocolVersion() >= 14.0) { $mapping[SYNC_SETTINGS_MOBILEOPERATOR] = array ( self::STREAMER_VAR => "mobileoperator"); $mapping[SYNC_SETTINGS_ENABLEOUTBOUNDSMS] = array ( self::STREAMER_VAR => "enableoutboundsms"); } parent::SyncObject($mapping); } }
agpl-3.0
maran/omniwallet
old-www/bower_components/sjcl/core/random.js
15768
/** @fileOverview Random number generator. * * @author Emily Stark * @author Mike Hamburg * @author Dan Boneh * @author Michael Brooks */ /** @constructor * @class Random number generator * @description * <b>Use sjcl.random as a singleton for this class!</b> * <p> * This random number generator is a derivative of Ferguson and Schneier's * generator Fortuna. It collects entropy from various events into several * pools, implemented by streaming SHA-256 instances. It differs from * ordinary Fortuna in a few ways, though. * </p> * * <p> * Most importantly, it has an entropy estimator. This is present because * there is a strong conflict here between making the generator available * as soon as possible, and making sure that it doesn't "run on empty". * In Fortuna, there is a saved state file, and the system is likely to have * time to warm up. * </p> * * <p> * Second, because users are unlikely to stay on the page for very long, * and to speed startup time, the number of pools increases logarithmically: * a new pool is created when the previous one is actually used for a reseed. * This gives the same asymptotic guarantees as Fortuna, but gives more * entropy to early reseeds. * </p> * * <p> * The entire mechanism here feels pretty klunky. Furthermore, there are * several improvements that should be made, including support for * dedicated cryptographic functions that may be present in some browsers; * state files in local storage; cookies containing randomness; etc. So * look for improvements in future versions. * </p> */ sjcl.prng = function(defaultParanoia) { /* private */ this._pools = [new sjcl.hash.sha256()]; this._poolEntropy = [0]; this._reseedCount = 0; this._robins = {}; this._eventId = 0; this._collectorIds = {}; this._collectorIdNext = 0; this._strength = 0; this._poolStrength = 0; this._nextReseed = 0; this._key = [0,0,0,0,0,0,0,0]; this._counter = [0,0,0,0]; this._cipher = undefined; this._defaultParanoia = defaultParanoia; /* event listener stuff */ this._collectorsStarted = false; this._callbacks = {progress: {}, seeded: {}}; this._callbackI = 0; /* constants */ this._NOT_READY = 0; this._READY = 1; this._REQUIRES_RESEED = 2; this._MAX_WORDS_PER_BURST = 65536; this._PARANOIA_LEVELS = [0,48,64,96,128,192,256,384,512,768,1024]; this._MILLISECONDS_PER_RESEED = 30000; this._BITS_PER_RESEED = 80; }; sjcl.prng.prototype = { /** Generate several random words, and return them in an array. * A word consists of 32 bits (4 bytes) * @param {Number} nwords The number of words to generate. */ randomWords: function (nwords, paranoia) { var out = [], i, readiness = this.isReady(paranoia), g; if (readiness === this._NOT_READY) { throw new sjcl.exception.notReady("generator isn't seeded"); } else if (readiness & this._REQUIRES_RESEED) { this._reseedFromPools(!(readiness & this._READY)); } for (i=0; i<nwords; i+= 4) { if ((i+1) % this._MAX_WORDS_PER_BURST === 0) { this._gate(); } g = this._gen4words(); out.push(g[0],g[1],g[2],g[3]); } this._gate(); return out.slice(0,nwords); }, setDefaultParanoia: function (paranoia, allowZeroParanoia) { if (paranoia === 0 && allowZeroParanoia !== "Setting paranoia=0 will ruin your security; use it only for testing") { throw "Setting paranoia=0 will ruin your security; use it only for testing"; } this._defaultParanoia = paranoia; }, /** * Add entropy to the pools. * @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string * @param {Number} estimatedEntropy The estimated entropy of data, in bits * @param {String} source The source of the entropy, eg "mouse" */ addEntropy: function (data, estimatedEntropy, source) { source = source || "user"; var id, i, tmp, t = (new Date()).valueOf(), robin = this._robins[source], oldReady = this.isReady(), err = 0, objName; id = this._collectorIds[source]; if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; } if (robin === undefined) { robin = this._robins[source] = 0; } this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length; switch(typeof(data)) { case "number": if (estimatedEntropy === undefined) { estimatedEntropy = 1; } this._pools[robin].update([id,this._eventId++,1,estimatedEntropy,t,1,data|0]); break; case "object": objName = Object.prototype.toString.call(data); if (objName === "[object Uint32Array]") { tmp = []; for (i = 0; i < data.length; i++) { tmp.push(data[i]); } data = tmp; } else { if (objName !== "[object Array]") { err = 1; } for (i=0; i<data.length && !err; i++) { if (typeof(data[i]) !== "number") { err = 1; } } } if (!err) { if (estimatedEntropy === undefined) { /* horrible entropy estimator */ estimatedEntropy = 0; for (i=0; i<data.length; i++) { tmp= data[i]; while (tmp>0) { estimatedEntropy++; tmp = tmp >>> 1; } } } this._pools[robin].update([id,this._eventId++,2,estimatedEntropy,t,data.length].concat(data)); } break; case "string": if (estimatedEntropy === undefined) { /* English text has just over 1 bit per character of entropy. * But this might be HTML or something, and have far less * entropy than English... Oh well, let's just say one bit. */ estimatedEntropy = data.length; } this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]); this._pools[robin].update(data); break; default: err=1; } if (err) { throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string"); } /* record the new strength */ this._poolEntropy[robin] += estimatedEntropy; this._poolStrength += estimatedEntropy; /* fire off events */ if (oldReady === this._NOT_READY) { if (this.isReady() !== this._NOT_READY) { this._fireEvent("seeded", Math.max(this._strength, this._poolStrength)); } this._fireEvent("progress", this.getProgress()); } }, /** Is the generator ready? */ isReady: function (paranoia) { var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ]; if (this._strength && this._strength >= entropyRequired) { return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ? this._REQUIRES_RESEED | this._READY : this._READY; } else { return (this._poolStrength >= entropyRequired) ? this._REQUIRES_RESEED | this._NOT_READY : this._NOT_READY; } }, /** Get the generator's progress toward readiness, as a fraction */ getProgress: function (paranoia) { var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ]; if (this._strength >= entropyRequired) { return 1.0; } else { return (this._poolStrength > entropyRequired) ? 1.0 : this._poolStrength / entropyRequired; } }, /** start the built-in entropy collectors */ startCollectors: function () { if (this._collectorsStarted) { return; } this._eventListener = { loadTimeCollector: this._bind(this._loadTimeCollector), mouseCollector: this._bind(this._mouseCollector), keyboardCollector: this._bind(this._keyboardCollector), accelerometerCollector: this._bind(this._accelerometerCollector) } if (window.addEventListener) { window.addEventListener("load", this._eventListener.loadTimeCollector, false); window.addEventListener("mousemove", this._eventListener.mouseCollector, false); window.addEventListener("keypress", this._eventListener.keyboardCollector, false); window.addEventListener("devicemotion", this._eventListener.accelerometerCollector, false); } else if (document.attachEvent) { document.attachEvent("onload", this._eventListener.loadTimeCollector); document.attachEvent("onmousemove", this._eventListener.mouseCollector); document.attachEvent("keypress", this._eventListener.keyboardCollector); } else { throw new sjcl.exception.bug("can't attach event"); } this._collectorsStarted = true; }, /** stop the built-in entropy collectors */ stopCollectors: function () { if (!this._collectorsStarted) { return; } if (window.removeEventListener) { window.removeEventListener("load", this._eventListener.loadTimeCollector, false); window.removeEventListener("mousemove", this._eventListener.mouseCollector, false); window.removeEventListener("keypress", this._eventListener.keyboardCollector, false); window.removeEventListener("devicemotion", this._eventListener.accelerometerCollector, false); } else if (document.detachEvent) { document.detachEvent("onload", this._eventListener.loadTimeCollector); document.detachEvent("onmousemove", this._eventListener.mouseCollector); document.detachEvent("keypress", this._eventListener.keyboardCollector); } this._collectorsStarted = false; }, /* use a cookie to store entropy. useCookie: function (all_cookies) { throw new sjcl.exception.bug("random: useCookie is unimplemented"); },*/ /** add an event listener for progress or seeded-ness. */ addEventListener: function (name, callback) { this._callbacks[name][this._callbackI++] = callback; }, /** remove an event listener for progress or seeded-ness */ removeEventListener: function (name, cb) { var i, j, cbs=this._callbacks[name], jsTemp=[]; /* I'm not sure if this is necessary; in C++, iterating over a * collection and modifying it at the same time is a no-no. */ for (j in cbs) { if (cbs.hasOwnProperty(j) && cbs[j] === cb) { jsTemp.push(j); } } for (i=0; i<jsTemp.length; i++) { j = jsTemp[i]; delete cbs[j]; } }, _bind: function (func) { var that = this; return function () { func.apply(that, arguments); }; }, /** Generate 4 random words, no reseed, no gate. * @private */ _gen4words: function () { for (var i=0; i<4; i++) { this._counter[i] = this._counter[i]+1 | 0; if (this._counter[i]) { break; } } return this._cipher.encrypt(this._counter); }, /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words. * @private */ _gate: function () { this._key = this._gen4words().concat(this._gen4words()); this._cipher = new sjcl.cipher.aes(this._key); }, /** Reseed the generator with the given words * @private */ _reseed: function (seedWords) { this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords)); this._cipher = new sjcl.cipher.aes(this._key); for (var i=0; i<4; i++) { this._counter[i] = this._counter[i]+1 | 0; if (this._counter[i]) { break; } } }, /** reseed the data from the entropy pools * @param full If set, use all the entropy pools in the reseed. */ _reseedFromPools: function (full) { var reseedData = [], strength = 0, i; this._nextReseed = reseedData[0] = (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED; for (i=0; i<16; i++) { /* On some browsers, this is cryptographically random. So we might * as well toss it in the pot and stir... */ reseedData.push(Math.random()*0x100000000|0); } for (i=0; i<this._pools.length; i++) { reseedData = reseedData.concat(this._pools[i].finalize()); strength += this._poolEntropy[i]; this._poolEntropy[i] = 0; if (!full && (this._reseedCount & (1<<i))) { break; } } /* if we used the last pool, push a new one onto the stack */ if (this._reseedCount >= 1 << this._pools.length) { this._pools.push(new sjcl.hash.sha256()); this._poolEntropy.push(0); } /* how strong was this reseed? */ this._poolStrength -= strength; if (strength > this._strength) { this._strength = strength; } this._reseedCount ++; this._reseed(reseedData); }, _keyboardCollector: function () { this._addCurrentTimeToEntropy(1); }, _mouseCollector: function (ev) { var x = ev.x || ev.clientX || ev.offsetX || 0, y = ev.y || ev.clientY || ev.offsetY || 0; sjcl.random.addEntropy([x,y], 2, "mouse"); this._addCurrentTimeToEntropy(0); }, _loadTimeCollector: function () { this._addCurrentTimeToEntropy(2); }, _addCurrentTimeToEntropy: function (estimatedEntropy) { if (window && window.performance && typeof window.performance.now === "function") { //how much entropy do we want to add here? sjcl.random.addEntropy(window.performance.now(), estimatedEntropy, "loadtime"); } else { sjcl.random.addEntropy((new Date()).valueOf(), estimatedEntropy, "loadtime"); } }, _accelerometerCollector: function (ev) { var ac = ev.accelerationIncludingGravity.x||ev.accelerationIncludingGravity.y||ev.accelerationIncludingGravity.z; var or = ""; if(window.orientation){ or = window.orientation; } sjcl.random.addEntropy([ac,or], 3, "accelerometer"); this._addCurrentTimeToEntropy(0); }, _fireEvent: function (name, arg) { var j, cbs=sjcl.random._callbacks[name], cbsTemp=[]; /* TODO: there is a race condition between removing collectors and firing them */ /* I'm not sure if this is necessary; in C++, iterating over a * collection and modifying it at the same time is a no-no. */ for (j in cbs) { if (cbs.hasOwnProperty(j)) { cbsTemp.push(cbs[j]); } } for (j=0; j<cbsTemp.length; j++) { cbsTemp[j](arg); } } }; /** an instance for the prng. * @see sjcl.prng */ sjcl.random = new sjcl.prng(6); (function(){ try { var buf, crypt, getRandomValues, ab; // get cryptographically strong entropy depending on runtime environment if (typeof module !== 'undefined' && module.exports) { // get entropy for node.js crypt = require('crypto'); buf = crypt.randomBytes(1024/8); sjcl.random.addEntropy(buf, 1024, "crypto.randomBytes"); } else if (window && Uint32Array) { ab = new Uint32Array(32); if (window.crypto && window.crypto.getRandomValues) { window.crypto.getRandomValues(ab); } else if (window.msCrypto && window.msCrypto.getRandomValues) { window.msCrypto.getRandomValues(ab); } else { return; } // get cryptographically strong entropy in Webkit sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues"); } else { // no getRandomValues :-( } } catch (e) { console.log("There was an error collecting entropy from the browser:"); console.log(e); //we do not want the library to fail due to randomness not being maintained. } }());
agpl-3.0
codegram/decidim
decidim-assemblies/app/cells/decidim/assemblies/assembly_member_cell.rb
458
# frozen_string_literal: true module Decidim module Assemblies # This cell renders the card for an instance of an Assembly member class AssemblyMemberCell < Decidim::ViewModel property :designation_date property :name property :nickname property :personal_information property :position property :profile_url private def has_profile? model.profile_url.present? end end end end
agpl-3.0
diydrones/apm_planner
libs/mavlink/include/mavlink/v2.0/ardupilotmega/mavlink_msg_mount_control.hpp
2659
// MESSAGE MOUNT_CONTROL support class #pragma once namespace mavlink { namespace ardupilotmega { namespace msg { /** * @brief MOUNT_CONTROL message * * Message to control a camera mount, directional antenna, etc. */ struct MOUNT_CONTROL : mavlink::Message { static constexpr msgid_t MSG_ID = 157; static constexpr size_t LENGTH = 15; static constexpr size_t MIN_LENGTH = 15; static constexpr uint8_t CRC_EXTRA = 21; static constexpr auto NAME = "MOUNT_CONTROL"; uint8_t target_system; /*< System ID */ uint8_t target_component; /*< Component ID */ int32_t input_a; /*< pitch(deg*100) or lat, depending on mount mode */ int32_t input_b; /*< roll(deg*100) or lon depending on mount mode */ int32_t input_c; /*< yaw(deg*100) or alt (in cm) depending on mount mode */ uint8_t save_position; /*< if "1" it will save current trimmed position on EEPROM (just valid for NEUTRAL and LANDING) */ inline std::string get_name(void) const override { return NAME; } inline Info get_message_info(void) const override { return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA }; } inline std::string to_yaml(void) const override { std::stringstream ss; ss << NAME << ":" << std::endl; ss << " target_system: " << +target_system << std::endl; ss << " target_component: " << +target_component << std::endl; ss << " input_a: " << input_a << std::endl; ss << " input_b: " << input_b << std::endl; ss << " input_c: " << input_c << std::endl; ss << " save_position: " << +save_position << std::endl; return ss.str(); } inline void serialize(mavlink::MsgMap &map) const override { map.reset(MSG_ID, LENGTH); map << input_a; // offset: 0 map << input_b; // offset: 4 map << input_c; // offset: 8 map << target_system; // offset: 12 map << target_component; // offset: 13 map << save_position; // offset: 14 } inline void deserialize(mavlink::MsgMap &map) override { map >> input_a; // offset: 0 map >> input_b; // offset: 4 map >> input_c; // offset: 8 map >> target_system; // offset: 12 map >> target_component; // offset: 13 map >> save_position; // offset: 14 } }; } // namespace msg } // namespace ardupilotmega } // namespace mavlink
agpl-3.0
usmschuck/canvas
vendor/bundle/ruby/1.9.1/gems/thrift-0.8.0/spec/nonblocking_server_spec.rb
7145
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # require File.expand_path("#{File.dirname(__FILE__)}/spec_helper") class ThriftNonblockingServerSpec < Spec::ExampleGroup include Thrift include SpecNamespace class Handler def initialize @queue = Queue.new end attr_accessor :server def greeting(english) if english SpecNamespace::Hello.new else SpecNamespace::Hello.new(:greeting => "Aloha!") end end def block @queue.pop end def unblock(n) n.times { @queue.push true } end def sleep(time) Kernel.sleep time end def shutdown @server.shutdown(0, false) end end class SpecTransport < BaseTransport def initialize(transport, queue) @transport = transport @queue = queue @flushed = false end def open? @transport.open? end def open @transport.open end def close @transport.close end def read(sz) @transport.read(sz) end def write(buf,sz=nil) @transport.write(buf, sz) end def flush @queue.push :flushed unless @flushed or @queue.nil? @flushed = true @transport.flush end end class SpecServerSocket < ServerSocket def initialize(host, port, queue) super(host, port) @queue = queue end def listen super @queue.push :listen end end describe Thrift::NonblockingServer do before(:each) do @port = 43251 handler = Handler.new processor = NonblockingService::Processor.new(handler) queue = Queue.new @transport = SpecServerSocket.new('localhost', @port, queue) transport_factory = FramedTransportFactory.new logger = Logger.new(STDERR) logger.level = Logger::WARN @server = NonblockingServer.new(processor, @transport, transport_factory, nil, 5, logger) handler.server = @server @server_thread = Thread.new(Thread.current) do |master_thread| begin @server.serve rescue => e p e puts e.backtrace * "\n" master_thread.raise e end end queue.pop @clients = [] @catch_exceptions = false end after(:each) do @clients.each { |client, trans| trans.close } # @server.shutdown(1) @server_thread.kill @transport.close end def setup_client(queue = nil) transport = SpecTransport.new(FramedTransport.new(Socket.new('localhost', @port)), queue) protocol = BinaryProtocol.new(transport) client = NonblockingService::Client.new(protocol) transport.open @clients << [client, transport] client end def setup_client_thread(result) queue = Queue.new Thread.new do begin client = setup_client while (cmd = queue.pop) msg, *args = cmd case msg when :block result << client.block when :unblock client.unblock(args.first) when :hello result << client.greeting(true) # ignore result when :sleep client.sleep(args[0] || 0.5) result << :slept when :shutdown client.shutdown when :exit result << :done break end end @clients.each { |c,t| t.close and break if c == client } #close the transport rescue => e raise e unless @catch_exceptions end end queue end it "should handle basic message passing" do client = setup_client client.greeting(true).should == Hello.new client.greeting(false).should == Hello.new(:greeting => 'Aloha!') @server.shutdown end it "should handle concurrent clients" do queue = Queue.new trans_queue = Queue.new 4.times do Thread.new(Thread.current) do |main_thread| begin queue.push setup_client(trans_queue).block rescue => e main_thread.raise e end end end 4.times { trans_queue.pop } setup_client.unblock(4) 4.times { queue.pop.should be_true } @server.shutdown end it "should handle messages from more than 5 long-lived connections" do queues = [] result = Queue.new 7.times do |i| queues << setup_client_thread(result) Thread.pass if i == 4 # give the server time to accept connections end client = setup_client # block 4 connections 4.times { |i| queues[i] << :block } queues[4] << :hello queues[5] << :hello queues[6] << :hello 3.times { result.pop.should == Hello.new } client.greeting(true).should == Hello.new queues[5] << [:unblock, 4] 4.times { result.pop.should be_true } queues[2] << :hello result.pop.should == Hello.new client.greeting(false).should == Hello.new(:greeting => 'Aloha!') 7.times { queues.shift << :exit } client.greeting(true).should == Hello.new @server.shutdown end it "should shut down when asked" do # connect first to ensure it's running client = setup_client client.greeting(false) # force a message pass @server.shutdown @server_thread.join(2).should be_an_instance_of(Thread) end it "should continue processing active messages when shutting down" do result = Queue.new client = setup_client_thread(result) client << :sleep sleep 0.1 # give the server time to start processing the client's message @server.shutdown @server_thread.join(2).should be_an_instance_of(Thread) result.pop.should == :slept end it "should kill active messages when they don't expire while shutting down" do result = Queue.new client = setup_client_thread(result) client << [:sleep, 10] sleep 0.1 # start processing the client's message @server.shutdown(1) @catch_exceptions = true @server_thread.join(3).should_not be_nil result.should be_empty end it "should allow shutting down in response to a message" do client = setup_client client.greeting(true).should == Hello.new client.shutdown @server_thread.join(2).should_not be_nil end end end
agpl-3.0
vikramvgarg/libmesh
src/error_estimation/kelly_error_estimator.C
6952
// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC #include <cmath> // for sqrt // Local Includes #include "libmesh/libmesh_common.h" #include "libmesh/kelly_error_estimator.h" #include "libmesh/error_vector.h" #include "libmesh/fe_base.h" #include "libmesh/libmesh_logging.h" #include "libmesh/elem.h" #include "libmesh/system.h" #include "libmesh/dense_vector.h" #include "libmesh/tensor_tools.h" namespace libMesh { void KellyErrorEstimator::init_context(FEMContext & c) { const unsigned int n_vars = c.n_vars(); for (unsigned int v=0; v<n_vars; v++) { // Possibly skip this variable if (error_norm.weight(v) == 0.0) continue; // FIXME: Need to generalize this to vector-valued elements. [PB] FEBase * side_fe = libmesh_nullptr; const std::set<unsigned char> & elem_dims = c.elem_dimensions(); for (std::set<unsigned char>::const_iterator dim_it = elem_dims.begin(); dim_it != elem_dims.end(); ++dim_it) { const unsigned char dim = *dim_it; fine_context->get_side_fe( v, side_fe, dim ); // We'll need gradients on both sides for flux jump computation side_fe->get_dphi(); // But we only need normal vectors from one side if (&c != coarse_context.get()) side_fe->get_normals(); } } } void KellyErrorEstimator::internal_side_integration () { const Elem & coarse_elem = coarse_context->get_elem(); const Elem & fine_elem = fine_context->get_elem(); FEBase * fe_fine = libmesh_nullptr; fine_context->get_side_fe( var, fe_fine, fine_elem.dim() ); FEBase * fe_coarse = libmesh_nullptr; coarse_context->get_side_fe( var, fe_coarse, fine_elem.dim() ); Real error = 1.e-30; unsigned int n_qp = fe_fine->n_quadrature_points(); std::vector<std::vector<RealGradient> > dphi_coarse = fe_coarse->get_dphi(); std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi(); std::vector<Point> face_normals = fe_fine->get_normals(); std::vector<Real> JxW_face = fe_fine->get_JxW(); for (unsigned int qp=0; qp != n_qp; ++qp) { // Calculate solution gradients on fine and coarse elements // at this quadrature point Gradient grad_fine = fine_context->side_gradient(var, qp), grad_coarse = coarse_context->side_gradient(var, qp); // Find the jump in the normal derivative // at this quadrature point const Number jump = (grad_fine - grad_coarse)*face_normals[qp]; const Real jump2 = TensorTools::norm_sq(jump); // Accumulate the jump integral error += JxW_face[qp] * jump2; } // Add the h-weighted jump integral to each error term fine_error = error * fine_elem.hmax() * error_norm.weight(var); coarse_error = error * coarse_elem.hmax() * error_norm.weight(var); } bool KellyErrorEstimator::boundary_side_integration () { const Elem & fine_elem = fine_context->get_elem(); FEBase * fe_fine = libmesh_nullptr; fine_context->get_side_fe( var, fe_fine, fine_elem.dim() ); const std::string & var_name = fine_context->get_system().variable_name(var); std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi(); std::vector<Point> face_normals = fe_fine->get_normals(); std::vector<Real> JxW_face = fe_fine->get_JxW(); std::vector<Point> qface_point = fe_fine->get_xyz(); // The reinitialization also recomputes the locations of // the quadrature points on the side. By checking if the // first quadrature point on the side is on a flux boundary // for a particular variable, we will determine if the whole // element is on a flux boundary (assuming quadrature points // are strictly contained in the side). if (this->_bc_function(fine_context->get_system(), qface_point[0], var_name).first) { const Real h = fine_elem.hmax(); // The number of quadrature points const unsigned int n_qp = fe_fine->n_quadrature_points(); // The error contribution from this face Real error = 1.e-30; // loop over the integration points on the face. for (unsigned int qp=0; qp<n_qp; qp++) { // Value of the imposed flux BC at this quadrature point. const std::pair<bool,Real> flux_bc = this->_bc_function(fine_context->get_system(), qface_point[qp], var_name); // Be sure the BC function still thinks we're on the // flux boundary. libmesh_assert_equal_to (flux_bc.first, true); // The solution gradient from each element Gradient grad_fine = fine_context->side_gradient(var, qp); // The difference between the desired BC and the approximate solution. const Number jump = flux_bc.second - grad_fine*face_normals[qp]; // The flux jump squared. If using complex numbers, // TensorTools::norm_sq(z) returns |z|^2, where |z| is the modulus of z. const Real jump2 = TensorTools::norm_sq(jump); // Integrate the error on the face. The error is // scaled by an additional power of h, where h is // the maximum side length for the element. This // arises in the definition of the indicator. error += JxW_face[qp]*jump2; } // End quadrature point loop fine_error = error*h*error_norm.weight(var); return true; } // end if side on flux boundary return false; } void KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System & system, const Point & p, const std::string & var_name)) { _bc_function = fptr; // We may be turning boundary side integration on or off if (fptr) integrate_boundary_sides = true; else integrate_boundary_sides = false; } } // namespace libMesh
lgpl-2.1
nexusformat/code
applications/NXtranslate/retriever.cpp
3614
#include <stdexcept> #include <map> #include "retriever.h" #include "nexus_retriever.h" #ifdef IPNS_RETRIEVER #include "IPNS_CPP/ipns_retriever.h" #endif #ifdef TEXT_PLAIN_RETRIEVER #include "text_plain/retriever.h" #endif #ifdef SPEC_RETRIEVER #include "spec/spec_retriever.h" #endif #ifdef EDF_RETRIEVER #include "esrf_edf/edf_retriever.h" #endif #ifdef TEXT_XML_RETRIEVER #include "text_xml/retriever.h" #endif #ifdef TEXT_COLLIST_RETRIEVER #include "text_collist/collist_retriever.h" #endif #ifdef BINARY_RETRIEVER #include "binary/BinaryRetriever.hpp" #endif #ifdef DYNAMIC_RETRIEVER #include "dynamic_retriever.h" #endif #ifdef SNS_HISTOGRAM_RETRIEVER #include "sns_histogram/retriever.h" #endif #ifdef FRM2_RETRIEVER #include "FRM2/frm2_retriever.h" #endif #ifdef LOOPY_RETRIEVER #include "loopy/retriever.h" #endif using std::map; using std::string; using std::invalid_argument; typedef Ptr<Retriever> RetrieverPtr; // hold a map of retrievers that have been instantiated so it can be cached map<string, RetrieverPtr> retrievers; RetrieverPtr getNewInstance(const string & type, const string & source) { // return appropriate retriever based on type if(type==NexusRetriever::MIME_TYPE){ RetrieverPtr ptr(new NexusRetriever(source)); return ptr; #ifdef IPNS_RETRIEVER }else if(type==IpnsRetriever::MIME_TYPE){ RetrieverPtr ptr(new IpnsRetriever(source)); return ptr; #endif #ifdef TEXT_PLAIN_RETRIEVER }else if(type==TextPlainRetriever::MIME_TYPE){ RetrieverPtr ptr(new TextPlainRetriever(source)); return ptr; #endif #ifdef SPEC_RETRIEVER }else if(type==SpecRetriever::MIME_TYPE){ RetrieverPtr ptr(new SpecRetriever(source)); return ptr; #endif #ifdef EDF_RETRIEVER }else if(type==EdfRetriever::MIME_TYPE){ RetrieverPtr ptr(new EdfRetriever(source)); return ptr; #endif #ifdef TEXT_COLLIST_RETRIEVER }else if(type==TextCollistRetriever::MIME_TYPE){ RetrieverPtr ptr(new TextCollistRetriever(source)); return ptr; #endif #ifdef TEXT_XML_RETRIEVER }else if(type==TextXmlRetriever::MIME_TYPE){ RetrieverPtr ptr(new TextXmlRetriever(source)); return ptr; #endif #ifdef BINARY_RETRIEVER }else if(type==BinaryRetriever::MIME_TYPE){ RetrieverPtr ptr(new BinaryRetriever(source)); return ptr; #endif #ifdef DYNAMIC_RETRIEVER }else if(type.substr(0,8) == "dynamic/"){ RetrieverPtr ptr(new DynamicRetriever(source, type)); return ptr; #endif #ifdef SNS_HISTOGRAM_RETRIEVER }else if(type==SnsHistogramRetriever::MIME_TYPE){ RetrieverPtr ptr(new SnsHistogramRetriever(source)); return ptr; #endif #ifdef FRM2_RETRIEVER }else if(type==Frm2Retriever::MIME_TYPE){ RetrieverPtr ptr(new Frm2Retriever(source)); return ptr; #endif #ifdef LOOPY_RETRIEVER }else if(type==LoopyRetriever::MIME_TYPE){ RetrieverPtr ptr(new LoopyRetriever(source)); return ptr; #endif } // if it gets this far the type is not understood throw invalid_argument("do not understand mime_type ("+type+") in retriever_factory"); } // Implementation of a pure virtual destructor. This makes the compiler happy. Retriever::~Retriever(){} // factory method Retriever::RetrieverPtr Retriever::getInstance(const string & type, const string &source){ map<string, RetrieverPtr>::iterator existing = retrievers.find(source); if (existing != retrievers.end()) { return (existing->second); } else { RetrieverPtr retriever = getNewInstance(type, source); retrievers.insert(make_pair(source, retriever)); return retriever; } }
lgpl-2.1
schernolyas/hibernate-ogm
mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/query/parsing/predicate/impl/MongoDBConjunctionPredicate.java
1348
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.datastore.mongodb.query.parsing.predicate.impl; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.hibernate.hql.ast.spi.predicate.ConjunctionPredicate; import org.hibernate.hql.ast.spi.predicate.NegatablePredicate; import org.hibernate.hql.ast.spi.predicate.Predicate; import org.bson.Document; /** * MongoDB-based implementation of {@link ConjunctionPredicate}. * * @author Gunnar Morling */ public class MongoDBConjunctionPredicate extends ConjunctionPredicate<Document> implements NegatablePredicate<Document> { @Override public Document getQuery() { List<Document> elements = new ArrayList<Document>(); for ( Predicate<Document> child : children ) { elements.add( child.getQuery() ); } return new Document( "$and", elements ); } @Override public Document getNegatedQuery() { List<Document> elements = new LinkedList<>(); for ( Predicate<Document> child : children ) { elements.add( ( (NegatablePredicate<Document>) child ).getNegatedQuery() ); } return new Document( "$or", elements ); } }
lgpl-2.1
yersan/wildfly-core
logging/src/main/java/org/jboss/as/logging/deployments/LoggingDeploymentResourceProcessor.java
5147
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.logging.deployments; import org.jboss.as.logging.CommonAttributes; import org.jboss.as.logging.deployments.resources.LoggingDeploymentResources; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentResourceSupport; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.logmanager.Configurator; import org.jboss.logmanager.LogContext; import org.jboss.logmanager.PropertyConfigurator; import org.jboss.logmanager.config.LogContextConfiguration; import org.jboss.modules.Module; import org.wildfly.security.manager.WildFlySecurityManager; /** * Process a deployment and ensures a logging configuration service has been added. * <p> * Note that in some cases the assumed logging configuration will be wrong. If a deployment is using a custom log * manager, such as logback, the configuration reported on the deployment will be the assumed configuration. * </p> * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class LoggingDeploymentResourceProcessor implements DeploymentUnitProcessor { /** * The attachment key used to attach the service. */ static final AttachmentKey<LoggingConfigurationService> LOGGING_CONFIGURATION_SERVICE_KEY = AttachmentKey.create(LoggingConfigurationService.class); @Override public final void deploy(final DeploymentPhaseContext phaseContext) { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (deploymentUnit.hasAttachment(Attachments.MODULE)) { LoggingConfigurationService loggingConfigurationService; if (deploymentUnit.hasAttachment(LOGGING_CONFIGURATION_SERVICE_KEY)) { loggingConfigurationService = deploymentUnit.getAttachment(LOGGING_CONFIGURATION_SERVICE_KEY); // Remove the attachment as it should no longer be needed deploymentUnit.removeAttachment(LOGGING_CONFIGURATION_SERVICE_KEY); } else { // Get the module final Module module = deploymentUnit.getAttachment(Attachments.MODULE); // Set the deployments class loader to ensure we get the correct log context final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader()); LogContextConfiguration logContextConfiguration = null; final LogContext logContext = LogContext.getLogContext(); final Configurator configurator = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, Configurator.ATTACHMENT_KEY); if (configurator instanceof LogContextConfiguration) { logContextConfiguration = (LogContextConfiguration) configurator; } else if (configurator instanceof PropertyConfigurator) { logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration(); } loggingConfigurationService = new LoggingConfigurationService(logContextConfiguration, "default"); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT); // Register the resources LoggingDeploymentResources.registerDeploymentResource(deploymentResourceSupport, loggingConfigurationService); phaseContext.getServiceTarget() .addService(deploymentUnit.getServiceName().append("logging", "configuration"), loggingConfigurationService) .install(); } } }
lgpl-2.1
bblacey/FreeCAD-MacOS-CI
src/Mod/TechDraw/Gui/QGIEdge.cpp
3905
/*************************************************************************** * Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #include <assert.h> #include <QGraphicsScene> #include <QGraphicsSceneHoverEvent> #include <QMouseEvent> #include <QPainter> #include <QPainterPathStroker> #include <QStyleOptionGraphicsItem> #endif #include <App/Application.h> #include <App/Material.h> #include <Base/Console.h> #include <Base/Parameter.h> #include "QGIEdge.h" using namespace TechDrawGui; QGIEdge::QGIEdge(int index) : projIndex(index), isCosmetic(false), isHiddenEdge(false), isSmoothEdge(false) { m_width = 1.0; setCosmetic(isCosmetic); } QRectF QGIEdge::boundingRect() const { return shape().controlPointRect(); } QPainterPath QGIEdge::shape() const { QPainterPath outline; QPainterPathStroker stroker; stroker.setWidth(2.0); outline = stroker.createStroke(path()); return outline; } void QGIEdge::setCosmetic(bool state) { isCosmetic = state; if (state) { setWidth(0.0); } } void QGIEdge::setHiddenEdge(bool b) { isHiddenEdge = b; if (b) { m_styleCurrent = getHiddenStyle(); } else { m_styleCurrent = Qt::SolidLine; } update(); } void QGIEdge::setPrettyNormal() { if (isHiddenEdge) { m_colCurrent = getHiddenColor(); } else { m_colCurrent = getNormalColor(); } update(); } QColor QGIEdge::getHiddenColor() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); App::Color fcColor = App::Color((uint32_t) hGrp->GetUnsigned("HiddenColor", 0x08080800)); return fcColor.asValue<QColor>(); } Qt::PenStyle QGIEdge::getHiddenStyle() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); Qt::PenStyle hidStyle = static_cast<Qt::PenStyle> (hGrp->GetInt("HiddenLine",2)); return hidStyle; } void QGIEdge::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { QStyleOptionGraphicsItem myOption(*option); myOption.state &= ~QStyle::State_Selected; QGIPrimPath::paint (painter, &myOption, widget); }
lgpl-2.1
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/engine/bcel/MethodFactory.java
2891
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2007 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.classfile.engine.bcel; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; /** * Method analysis engine to produce BCEL Method objects. * * @author David Hovemeyer */ public class MethodFactory extends AnalysisFactory<Method> { public MethodFactory() { super("Method factory", Method.class); } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.classfile.IAnalysisEngine#analyze(edu.umd.cs.findbugs * .classfile.IAnalysisCache, java.lang.Object) */ @Override public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor()); Method[] methodList = jclass.getMethods(); Method result = null; // As a side-effect, cache all of the Methods for this JavaClass for (Method method : methodList) { MethodDescriptor methodDescriptor = DescriptorFactory.instance().getMethodDescriptor( descriptor.getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic()); // Put in cache eagerly analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method); if (methodDescriptor.equals(descriptor)) { result = method; } } return result; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.classfile.IAnalysisEngine#registerWith(edu.umd.cs * .findbugs.classfile.IAnalysisCache) */ @Override public void registerWith(IAnalysisCache analysisCache) { analysisCache.registerMethodAnalysisEngine(Method.class, this); } }
lgpl-2.1
PatidarWeb/opencms-core
src-modules/org/opencms/workplace/tools/content/check/Messages.java
10753
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.workplace.tools.content.check; import org.opencms.i18n.A_CmsMessageBundle; import org.opencms.i18n.I_CmsMessageBundle; /** * Convenience class to access the localized messages of this OpenCms package.<p> * * @since 6.1.2 */ public final class Messages extends A_CmsMessageBundle { /** Message constant for key in the resource bundle. */ public static final String ERR_CHECK_CONTAINS_FILENAME_2 = "ERR_CHECK_CONTAINS_FILENAME_2"; /** Message constant for key in the resource bundle. */ public static final String ERR_CHECK_MATCH_3 = "ERR_CHECK_MATCH_3"; /** Message constant for key in the resource bundle. */ public static final String ERR_CHECK_NO_PROPERTYNAME_1 = "ERR_CHECK_NO_PROPERTYNAME_1"; /** Message constant for key in the resource bundle. */ public static final String ERR_CHECK_TOO_SHORT_3 = "ERR_CHECK_TOO_SHORT_3"; /** Message constant for key in the resource bundle. */ public static final String ERR_NO_TEST_0 = "ERR_NO_TEST_0"; /** Message constant for key in the resource bundle. */ public static final String ERR_NO_VFSPATH_0 = "ERR_NO_VFSPATH_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_CONFIGURATION_PROPERTY_HELP_0 = "GUI_CHECKCONTENT_CONFIGURATION_PROPERTY_HELP_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_HIDE_ERRORINFO_HELP_0 = "GUI_CHECKCONTENT_DETAIL_HIDE_ERRORINFO_HELP_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_HIDE_ERRORINFO_NAME_0 = "GUI_CHECKCONTENT_DETAIL_HIDE_ERRORINFO_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_HIDE_WARNINGINFO_HELP_0 = "GUI_CHECKCONTENT_DETAIL_HIDE_WARNINGINFO_HELP_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_HIDE_WARNINGINFO_NAME_0 = "GUI_CHECKCONTENT_DETAIL_HIDE_WARNINGINFO_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_SHOW_ERRORINFO_HELP_0 = "GUI_CHECKCONTENT_DETAIL_SHOW_ERRORINFO_HELP_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_SHOW_ERRORINFO_NAME_0 = "GUI_CHECKCONTENT_DETAIL_SHOW_ERRORINFO_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_SHOW_WARNINGINFO_HELP_0 = "GUI_CHECKCONTENT_DETAIL_SHOW_WARNINGINFO_HELP_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_DETAIL_SHOW_WARNINGINFO_NAME_0 = "GUI_CHECKCONTENT_DETAIL_SHOW_WARNINGINFO_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_LABEL_ERROR_0 = "GUI_CHECKCONTENT_LABEL_ERROR_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_LABEL_WARNING_0 = "GUI_CHECKCONTENT_LABEL_WARNING_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CHECKCONTENT_LIST_NAME_0 = "GUI_CHECKCONTENT_LIST_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String LOG_CANNOT_CREATE_PLUGIN_1 = "LOG_CANNOT_CREATE_PLUGIN_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_CANNOT_CREATE_PLUGIN_2 = "LOG_CANNOT_CREATE_PLUGIN_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_CREATE_PLUGIN_1 = "LOG_CREATE_PLUGIN_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CHECKLENGTH_2 = "LOG_DEBUG_PROPERTY_CHECKLENGTH_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIG_FILE_1 = "LOG_DEBUG_PROPERTY_CONFIG_FILE_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIG_FILENAME_1 = "LOG_DEBUG_PROPERTY_CONFIG_FILENAME_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIG_PROPERTY_3 = "LOG_DEBUG_PROPERTY_CONFIG_PROPERTY_3"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIG_XPATH_2 = "LOG_DEBUG_PROPERTY_CONFIG_XPATH_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIGURED_ERRORS_2 = "LOG_DEBUG_PROPERTY_CONFIGURED_ERRORS_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_CONFIGURED_WARNINGS_2 = "LOG_DEBUG_PROPERTY_CONFIGURED_WARNINGS_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_ISEMPTYCHECK_1 = "LOG_DEBUG_PROPERTY_ISEMPTYCHECK_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_ISFILENAME_1 = "LOG_DEBUG_PROPERTY_ISFILENAME_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_MATCHPATTERN_2 = "LOG_DEBUG_PROPERTY_MATCHPATTERN_2"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_PROPERTY_1 = "LOG_DEBUG_PROPERTY_PROPERTY_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_RESOURCE_1 = "LOG_DEBUG_PROPERTY_RESOURCE_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_DEBUG_PROPERTY_VALUE_1 = "LOG_DEBUG_PROPERTY_VALUE_1"; /** Message constant for key in the resource bundle. */ public static final String LOG_ERROR_PROCESSING_PROPERTIES_2 = "LOG_ERROR_PROCESSING_PROPERTIES_2"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_CHECK_BEGIN_0 = "RPT_CONTENT_CHECK_BEGIN_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_CHECK_END_0 = "RPT_CONTENT_CHECK_END_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_COLLECT_BEGIN_0 = "RPT_CONTENT_COLLECT_BEGIN_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_COLLECT_END_1 = "RPT_CONTENT_COLLECT_END_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_2 = "RPT_CONTENT_PROCESS_2"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_BEGIN_0 = "RPT_CONTENT_PROCESS_BEGIN_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_END_0 = "RPT_CONTENT_PROCESS_END_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_ERROR_0 = "RPT_CONTENT_PROCESS_ERROR_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_ERROR_1 = "RPT_CONTENT_PROCESS_ERROR_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_ERROR_2 = "RPT_CONTENT_PROCESS_ERROR_2"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_RESOURCE_1 = "RPT_CONTENT_PROCESS_RESOURCE_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_WARNING_0 = "RPT_CONTENT_PROCESS_WARNING_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_CONTENT_PROCESS_WARNING_1 = "RPT_CONTENT_PROCESS_WARNING_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_EMPTY_0 = "RPT_EMPTY_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_EXTRACT_FROM_PATH_1 = "RPT_EXTRACT_FROM_PATH_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_EXTRACT_FROM_PATH_BEGIN_1 = "RPT_EXTRACT_FROM_PATH_BEGIN_1"; /** Message constant for key in the resource bundle. */ public static final String RPT_EXTRACT_FROM_PATH_END_0 = "RPT_EXTRACT_FROM_PATH_END_0"; /** Message constant for key in the resource bundle. */ public static final String RPT_EXTRACT_FROM_PATH_ERROR_2 = "RPT_EXTRACT_FROM_PATH_ERROR_2"; /** Name of the used resource bundle. */ private static final String BUNDLE_NAME = "org.opencms.workplace.tools.content.check.messages"; /** Static instance member. */ private static final I_CmsMessageBundle INSTANCE = new Messages(); /** * Hides the public constructor for this utility class.<p> */ private Messages() { // hide the constructor } /** * Returns an instance of this localized message accessor.<p> * * @return an instance of this localized message accessor */ public static I_CmsMessageBundle get() { return INSTANCE; } /** * Returns the bundle name for this OpenCms package.<p> * * @return the bundle name for this OpenCms package */ public String getBundleName() { return BUNDLE_NAME; } }
lgpl-2.1
sbonoc/opencms-core
src-setup/org/opencms/setup/xml/v8/CmsXmlAddIconRules.java
6634
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.setup.xml.v8; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.configuration.CmsWorkplaceConfiguration; import org.opencms.configuration.I_CmsXmlConfiguration; import org.opencms.setup.CmsSetupBean; import org.opencms.setup.xml.A_CmsXmlWorkplace; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Node; /** * XML updater for adding icon rules to opencms-workplace.xml.<p> * * @since 8.0.0 */ public class CmsXmlAddIconRules extends A_CmsXmlWorkplace { /** List of xpaths to update. */ private List<String> m_xpaths; /** * @see org.opencms.setup.xml.I_CmsSetupXmlUpdate#getName() */ public String getName() { return "Adds icon rules for various explorer types."; } /** * @see org.opencms.setup.xml.I_CmsSetupXmlUpdate#validate(org.opencms.setup.CmsSetupBean) */ @Override public boolean validate(CmsSetupBean setupBean) throws Exception { return CmsStringUtil.isNotEmptyOrWhitespaceOnly(getCodeToChange(setupBean)); } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#executeUpdate(org.dom4j.Document, java.lang.String, boolean) */ @Override protected boolean executeUpdate(Document document, String xpath, boolean forReal) { Node node = document.selectSingleNode(xpath); if (node != null) { if (xpath.equals(getXPathsToUpdate().get(0))) { if (document.selectSingleNode(xpath + "/" + CmsWorkplaceConfiguration.N_ICONRULES) != null) { return false; } org.dom4j.Element explorerTypePlain = (org.dom4j.Element)document.selectSingleNode(xpath); org.dom4j.Element iconRules = explorerTypePlain.addElement(CmsWorkplaceConfiguration.N_ICONRULES); addIconRule(iconRules, "java", "java.png", "java_big.png"); addIconRule(iconRules, "js", "js.png", "js_big.png"); addIconRule(iconRules, "html", "html.png", "html_big.png"); addIconRule(iconRules, "xhtml", "html.png", "html_big.png"); addIconRule(iconRules, "htm", "html.png", "html_big.png"); addIconRule(iconRules, "txt", "text.png", "text_big.png"); addIconRule(iconRules, "xml", "xml.png", "xml_big.png"); return true; } else if (xpath.equals(getXPathsToUpdate().get(1))) { if (document.selectSingleNode(xpath + "/iconrules") != null) { return false; } // binary org.dom4j.Element explorerTypeBinary = (org.dom4j.Element)document.selectSingleNode(xpath); org.dom4j.Element iconRules = explorerTypeBinary.addElement(CmsWorkplaceConfiguration.N_ICONRULES); addIconRule(iconRules, "doc", "msword.png", "msword_big.png"); addIconRule(iconRules, "docx", "msword.png", "msword_big.png"); addIconRule(iconRules, "xls", "excel.png", "excel_big.png"); addIconRule(iconRules, "ppt", "powerpoint.png", "powerpoint_big.png"); addIconRule(iconRules, "zip", "archive.png", "archive_big.png"); addIconRule(iconRules, "rar", "archive.png", "archive_big.png"); addIconRule(iconRules, "pdf", "pdf.png", "pdf_big.png"); return true; } } return false; } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#getCommonPath() */ @Override protected String getCommonPath() { return "/" + CmsConfigurationManager.N_ROOT + "/" + CmsWorkplaceConfiguration.N_WORKPLACE + "/" + CmsWorkplaceConfiguration.N_EXPLORERTYPES; } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#getXPathsToUpdate() */ @Override protected List<String> getXPathsToUpdate() { if (m_xpaths == null) { m_xpaths = new ArrayList<String>(); m_xpaths.add(xpathForType("plain")); m_xpaths.add(xpathForType("binary")); } return m_xpaths; } /** * Adds an icon rule to the XML dom.<p> * * @param element the parent element * @param extension the extension * @param icon the icon name * @param bigicon the big icon name */ private void addIconRule(org.dom4j.Element element, String extension, String icon, String bigicon) { org.dom4j.Element ruleElem = element.addElement(CmsWorkplaceConfiguration.N_ICONRULE); ruleElem.addAttribute(CmsWorkplaceConfiguration.A_EXTENSION, extension); ruleElem.addAttribute(I_CmsXmlConfiguration.A_ICON, icon); ruleElem.addAttribute(CmsWorkplaceConfiguration.A_BIGICON, bigicon); } /** * Returns the xpath for a given explorer type.<p> * * @param explorerType the explorer type * * @return the xpath for that explorer type */ private String xpathForType(String explorerType) { return "/" + CmsConfigurationManager.N_ROOT + "/" + CmsWorkplaceConfiguration.N_WORKPLACE + "/" + CmsWorkplaceConfiguration.N_EXPLORERTYPES + "/" + CmsWorkplaceConfiguration.N_EXPLORERTYPE + "[@name='" + explorerType + "']"; } }
lgpl-2.1
golovnin/wildfly
ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/TimerResourceDefinition.java
18444
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.subsystem.deployment; import java.util.Date; import javax.ejb.NoMoreTimeoutsException; import javax.ejb.ScheduleExpression; import javax.ejb.TimerHandle; import org.jboss.as.controller.ObjectListAttributeDefinition; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.subsystem.EJB3Extension; import org.jboss.as.ejb3.subsystem.EJB3SubsystemModel; import org.jboss.as.ejb3.timerservice.TimerHandleImpl; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * {@link org.jboss.as.controller.ResourceDefinition} for the timer resource for runtime ejb deployment. This definition declares operations and * attributes of single timer. * * @author baranowb */ public class TimerResourceDefinition<T extends EJBComponent> extends SimpleResourceDefinition { private static final ResourceDescriptionResolver RESOURCE_DESCRIPTION_RESOLVER = EJB3Extension .getResourceDescriptionResolver(EJB3SubsystemModel.TIMER); // attributes, copy of TimerAttributeDefinition private static final SimpleAttributeDefinition TIME_REMAINING = new SimpleAttributeDefinitionBuilder("time-remaining", ModelType.LONG, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition NEXT_TIMEOUT = new SimpleAttributeDefinitionBuilder("next-timeout", ModelType.LONG, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition CALENDAR_TIMER = new SimpleAttributeDefinitionBuilder("calendar-timer", ModelType.BOOLEAN, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition PERSISTENT = new SimpleAttributeDefinitionBuilder("persistent", ModelType.BOOLEAN, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition ACTIVE = new SimpleAttributeDefinitionBuilder("active", ModelType.BOOLEAN, true).setStorageRuntime().build(); // schedule and its children private static final SimpleAttributeDefinition DAY_OF_MONTH = new SimpleAttributeDefinitionBuilder("day-of-month", ModelType.STRING, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition DAY_OF_WEEK = new SimpleAttributeDefinitionBuilder("day-of-week", ModelType.STRING, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition HOUR = new SimpleAttributeDefinitionBuilder("hour", ModelType.STRING, true) .setStorageRuntime().build(); private static final SimpleAttributeDefinition MINUTE = new SimpleAttributeDefinitionBuilder("minute", ModelType.STRING, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition SECOND = new SimpleAttributeDefinitionBuilder("second", ModelType.STRING, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition MONTH = new SimpleAttributeDefinitionBuilder("month", ModelType.STRING, true) .setStorageRuntime().build(); private static final SimpleAttributeDefinition YEAR = new SimpleAttributeDefinitionBuilder("year", ModelType.STRING, true) .setStorageRuntime().build(); private static final SimpleAttributeDefinition TIMEZONE = new SimpleAttributeDefinitionBuilder("timezone", ModelType.STRING, true).setStorageRuntime().build(); private static final SimpleAttributeDefinition START = new SimpleAttributeDefinitionBuilder("start", ModelType.LONG, true) .setStorageRuntime().build(); private static final SimpleAttributeDefinition END = new SimpleAttributeDefinitionBuilder("end", ModelType.LONG, true) .setStorageRuntime().build(); public static final ObjectListAttributeDefinition SCHEDULE = ObjectListAttributeDefinition.Builder.of( "schedule", ObjectTypeAttributeDefinition.Builder.of("schedule", YEAR, MONTH, DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, SECOND, TIMEZONE, START, END).build()).build(); // TimerConfig.info private static final SimpleAttributeDefinition INFO = new SimpleAttributeDefinitionBuilder("info", ModelType.STRING, true) .setStorageRuntime().build(); private static final SimpleAttributeDefinition PRIMARY_KEY = new SimpleAttributeDefinitionBuilder("primary-key", ModelType.STRING, true).setStorageRuntime().build(); // operations private static final OperationDefinition SUSPEND = new SimpleOperationDefinitionBuilder("suspend", RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build(); private static final OperationDefinition ACTIVATE = new SimpleOperationDefinitionBuilder("activate", RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build(); private static final OperationDefinition CANCEL = new SimpleOperationDefinitionBuilder("cancel", RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build(); private static final OperationDefinition TRIGGER = new SimpleOperationDefinitionBuilder("trigger", RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build(); private final AbstractEJBComponentRuntimeHandler<T> parentHandler; TimerResourceDefinition(AbstractEJBComponentRuntimeHandler<T> parentHandler) { super(EJB3SubsystemModel.TIMER_PATH, RESOURCE_DESCRIPTION_RESOLVER, null, null, OperationEntry.Flag.RESTART_NONE, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); this.parentHandler = parentHandler; } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { super.registerChildren(resourceRegistration); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(SUSPEND, new AbstractTimerHandler() { @Override void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException { final TimerImpl timer = getTimer(context, operation); timer.suspend(); context.completeStep(new OperationContext.RollbackHandler() { @Override public void handleRollback(OperationContext context, ModelNode operation) { timer.scheduleTimeout(true); } }); } }); resourceRegistration.registerOperationHandler(ACTIVATE, new AbstractTimerHandler() { @Override void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException { final TimerImpl timer = getTimer(context, operation); if (!timer.isActive()) { timer.scheduleTimeout(true); context.completeStep(new OperationContext.RollbackHandler() { @Override public void handleRollback(OperationContext context, ModelNode operation) { timer.suspend(); } }); } else { throw EjbLogger.ROOT_LOGGER.timerIsActive(timer); } } }); resourceRegistration.registerOperationHandler(CANCEL, new AbstractTimerHandler() { @Override void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException { final TimerImpl timer = getTimer(context, operation); // this is TX aware timer.cancel(); context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }); resourceRegistration.registerOperationHandler(TRIGGER, new AbstractTimerHandler() { @Override void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException { // This will invoke timer in 'management-handler-thread' final TimerImpl timer = getTimer(context, operation); try { timer.invokeOneOff(); } catch (Exception e) { throw EjbLogger.ROOT_LOGGER.timerInvocationFailed(e); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadOnlyAttribute(TIME_REMAINING, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } try { final long time = timer.getTimeRemaining(); toSet.set(time); } catch(NoMoreTimeoutsException nmte) { // leave undefined // the same will occur for next-timeout attribute, but let's log it only once if(EjbLogger.ROOT_LOGGER.isDebugEnabled()) EjbLogger.ROOT_LOGGER.debug("No more timeouts for timer " + timer); } } }); resourceRegistration.registerReadOnlyAttribute(NEXT_TIMEOUT, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } try { final Date d = timer.getNextTimeout(); if (d != null) { toSet.set(d.getTime()); } } catch(NoMoreTimeoutsException ignored) { // leave undefined } } }); resourceRegistration.registerReadOnlyAttribute(CALENDAR_TIMER, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } final boolean calendarTimer = timer.isCalendarTimer(); toSet.set(calendarTimer); } }); resourceRegistration.registerReadOnlyAttribute(PERSISTENT, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } final boolean persistent = timer.isPersistent(); toSet.set(persistent); } }); resourceRegistration.registerReadOnlyAttribute(ACTIVE, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { final boolean active = timer.isActive(); toSet.set(active); } }); resourceRegistration.registerReadOnlyAttribute(SCHEDULE, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled() || !timer.isCalendarTimer()) { return; } ScheduleExpression sched = timer.getSchedule(); addString(toSet, sched.getYear(), YEAR.getName()); addString(toSet, sched.getMonth(), MONTH.getName()); addString(toSet, sched.getDayOfMonth(), DAY_OF_MONTH.getName()); addString(toSet, sched.getDayOfWeek(), DAY_OF_WEEK.getName()); addString(toSet, sched.getHour(), HOUR.getName()); addString(toSet, sched.getMinute(), MINUTE.getName()); addString(toSet, sched.getSecond(), SECOND.getName()); addString(toSet, sched.getTimezone(), TIMEZONE.getName()); addDate(toSet, sched.getStart(), START.getName()); addDate(toSet, sched.getEnd(), END.getName()); } private void addString(ModelNode schedNode, String value, String name) { final ModelNode node = schedNode.get(name); if (value != null) { node.set(value); } } private void addDate(ModelNode schedNode, Date value, String name) { final ModelNode node = schedNode.get(name); if (value != null) { node.set(value.getTime()); } } }); resourceRegistration.registerReadOnlyAttribute(PRIMARY_KEY, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } final Object pk = timer.getPrimaryKey(); if (pk != null) { toSet.set(pk.toString()); } } }); resourceRegistration.registerReadOnlyAttribute(INFO, new AbstractReadAttributeHandler() { @Override protected void readAttribute(TimerImpl timer, ModelNode toSet) { if (timer.isCanceled()) { return; } if (timer.getInfo() != null) { toSet.set(timer.getInfo().toString()); } } }); } private abstract class AbstractTimerHandler implements OperationStepHandler { public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (context.isNormalServer()) { context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { executeRuntime(context, operation); } }, OperationContext.Stage.RUNTIME); } } protected TimerImpl getTimer(final OperationContext context, final ModelNode operation) throws OperationFailedException { final T ejbcomponent = parentHandler.getComponent(context, operation); final TimerServiceImpl timerService = (TimerServiceImpl) ejbcomponent.getTimerService(); final PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)); final String timerId = address.getLastElement().getValue(); final String timedInvokerObjectId = timerService.getTimedObjectInvoker().getValue().getTimedObjectId(); final TimerHandle handle = new TimerHandleImpl(timerId, timedInvokerObjectId, timerService); try { return timerService.getTimer(handle); } catch (Exception e) { throw new OperationFailedException(e, null); } } abstract void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException; } private abstract class AbstractReadAttributeHandler extends AbstractTimerHandler { void executeRuntime(final OperationContext context, final ModelNode operation) throws OperationFailedException { final String opName = operation.require(ModelDescriptionConstants.OP).asString(); if (!opName.equals(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION)) { throw EjbLogger.ROOT_LOGGER.unknownOperations(opName); } final TimerImpl timer = getTimer(context, operation); if(timer != null) { //the timer can expire at any point, so protect against an NPE readAttribute(timer, context.getResult()); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } protected abstract void readAttribute(final TimerImpl timer, final ModelNode toSet); } }
lgpl-2.1
danshapero/dealii
tests/manifold/composition_manifold_03.cc
2310
//------------------------------------------------------------------- // Copyright (C) 2016 by the deal.II authors. // // This file is subject to LGPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //------------------------------------------------------------------- // Test the combination of simple ChartManifolds: PolarManifold + // Rotation #include "../tests.h" // all include files you need here #include <deal.II/grid/manifold_lib.h> #include <deal.II/grid/composition_manifold.h> int main () { initlog(); std::ostream &out = deallog.get_file_stream(); const int dim=2, spacedim=2; PolarManifold<1,2> F; std::map<std::string, double> constants; constants["k"] = numbers::PI/3; FunctionManifold<2,2,2> G("cos( k)*x -sin( k)*y; sin( k)*x+cos( k)*y", "cos(-k)*x -sin(-k)*y; sin(-k)*x+cos(-k)*y", Point<2>(), constants); CompositionManifold<2,2,2,2,1> manifold(F,G); // Chart points. Point<2> cp[2]; cp[0][0] = 1.0; cp[1][0] = 1.0; cp[1][1] = numbers::PI/2; // Spacedim points std::vector<Point<spacedim> > sp(2); // Weights std::vector<double> w(2); sp[0] = manifold.push_forward(cp[0]); sp[1] = manifold.push_forward(cp[1]); for (unsigned int d=0; d<2; ++d) if (cp[d].distance(manifold.pull_back(sp[d])) > 1e-10) deallog << "Error!" << std::endl; unsigned int n_intermediates = 16; out << "set size ratio -1" << std::endl << "plot '-' with vectors " << std::endl; Point<2> center; out << center << " " << sp[0] << std::endl << center << " " << sp[1] << std::endl; for (unsigned int i=0; i<n_intermediates+1; ++i) { w[0] = 1.0-(double)i/((double)n_intermediates); w[1] = 1.0 - w[0]; Point<spacedim> ip = manifold.get_new_point(make_array_view(sp), make_array_view(w)); Tensor<1,spacedim> t1 = manifold.get_tangent_vector(ip, sp[0]); Tensor<1,spacedim> t2 = manifold.get_tangent_vector(ip, sp[1]); out << ip << " " << t2 << std::endl; } out << "e" << std::endl; return 0; }
lgpl-2.1
Mind2mind/MateCat
test/unit/TestEngine/GetInstanceTest.php
4729
<?php /** * @group regression * @covers Engine::getInstance * User: dinies * Date: 14/04/16 * Time: 17.45 */ class GetInstanceTest extends AbstractTest { protected $reflector; protected $property; /** * @var Database */ protected $database_instance; protected $sql_insert_user; protected $sql_insert_engine; protected $sql_delete_user; protected $sql_delete_engine; protected $id_user; protected $id_database; public function setUp() { parent::setUp(); $this->database_instance=Database::obtain(INIT::$DB_SERVER, INIT::$DB_USER, INIT::$DB_PASS, INIT::$DB_DATABASE ); /** * user insertion */ $this->sql_insert_user = "INSERT INTO ".INIT::$DB_DATABASE.".`users` (`uid`, `email`, `salt`, `pass`, `create_date`, `first_name`, `last_name`, `api_key` ) VALUES ('100044', 'bar@foo.net', '12345trewq', '987654321qwerty', '2016-04-11 13:41:54', 'Bar', 'Foo', '');"; $this->database_instance->query($this->sql_insert_user); $this->id_user=$this->database_instance->getConnection()->lastInsertId(); /** * engine insertion */ $this->sql_insert_engine = "INSERT INTO ".INIT::$DB_DATABASE.".`engines` (`id`, `name`, `type`, `description`, `base_url`, `translate_relative_url`, `contribute_relative_url`, `delete_relative_url`, `others`, `class_load`, `extra_parameters`, `google_api_compliant_version`, `penalty`, `active`, `uid`) VALUES ('10', 'DeepLingo En/Fr iwslt', 'MT', 'DeepLingo Engine', 'http://mtserver01.deeplingo.com:8019', 'translate', NULL, NULL, '{}', 'DeepLingo', '{\"client_secret\":\"gala15 \"}', '2', '14', '1', ".$this->id_user.");"; $this->database_instance->query($this->sql_insert_engine); $this->id_database=$this->database_instance->getConnection()->lastInsertId(); $this->sql_delete_user ="DELETE FROM users WHERE uid=".$this->id_user.";"; $this->sql_delete_engine ="DELETE FROM engines WHERE id=".$this->id_database.";"; } public function tearDown() { $this->database_instance->query($this->sql_delete_user); $this->database_instance->query($this->sql_delete_engine); $flusher= new Predis\Client(INIT::$REDIS_SERVERS); $flusher->flushdb(); parent::tearDown(); } /** * @param id of the engine previously constructed * @group regression * @covers Engine::getInstance */ public function test_getInstance_of_constructed_engine(){ $engine = Engine::getInstance($this->id_database); $this->assertTrue($engine instanceof Engines_DeepLingo); } /** * @param id of the engine previously constructed * @group regression * @covers Engine::getInstance */ public function test_getInstance_of_constructed_engine_my_memory(){ $engine = Engine::getInstance(1); $this->assertTrue($engine instanceof Engines_MyMemory); } /** * @param id of the engine previously constructed * @group regression * @covers Engine::getInstance */ public function test_getInstance_of_default_engine(){ $this->setExpectedException("Exception"); Engine::getInstance(0); } /** * @param '' * @group regression * @covers Engine::getInstance */ public function test_getInstance_without_id(){ $this->setExpectedException('Exception'); Engine::getInstance(''); } /** * @param null * @group regression * @covers Engine::getInstance */ public function test_getInstance_whit_null_id(){ $this->setExpectedException('Exception'); Engine::getInstance(null); } /** * @param 99 * @group regression * @covers Engine::getInstance */ public function test_getInstance_with_no_mach_for_engine_id(){ $this->setExpectedException('Exception'); Engine::getInstance($this->id_database+1); } /** * verify that the method name of engine not match the classes of known engines * @group regression * @covers Engine::getInstance */ public function test_getInstance_with_no_mach_for_engine_class_name(){ $sql_update_engine_class_name="UPDATE `engines` SET class_load='YourMemory' WHERE id=".$this->id_database.";"; require_once 'Predis/autoload.php'; $obliterator= new Predis\Client(INIT::$REDIS_SERVERS); $obliterator->del($sql_update_engine_class_name); $this->database_instance->query($sql_update_engine_class_name); $this->setExpectedException('\Exception'); Engine::getInstance($this->id_database); } }
lgpl-3.0
SciTools/iris
lib/iris/experimental/ugrid/cf.py
12667
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ Extensions to Iris' CF variable representation to represent CF UGrid variables. Eventual destination: :mod:`iris.fileformats.cf`. """ import logging from ...config import get_logger from ...fileformats import cf from .mesh import Connectivity # Configure the logger. logger = get_logger(__name__, propagate=True, handler=False) class CFUGridConnectivityVariable(cf.CFVariable): """ A CF_UGRID connectivity variable points to an index variable identifying for every element (edge/face/volume) the indices of its corner nodes. The connectivity array will thus be a matrix of size n-elements x n-corners. For the indexing one may use either 0- or 1-based indexing; the convention used should be specified using a ``start_index`` attribute to the index variable. For face elements: the corner nodes should be specified in anticlockwise direction as viewed from above. For volume elements: use the additional attribute ``volume_shape_type`` which points to a flag variable that specifies for every volume its shape. Identified by a CF-netCDF variable attribute equal to any one of the values in :attr:`~iris.experimental.ugrid.mesh.Connectivity.UGRID_CF_ROLES`. .. seealso:: The UGRID Conventions, https://ugrid-conventions.github.io/ugrid-conventions/ """ cf_identity = NotImplemented cf_identities = Connectivity.UGRID_CF_ROLES @classmethod def identify(cls, variables, ignore=None, target=None, warn=True): result = {} ignore, target = cls._identify_common(variables, ignore, target) # TODO: reconsider logging level when we have consistent practice. log_level = logging.WARNING if warn else logging.DEBUG # Identify all CF-UGRID connectivity variables. for nc_var_name, nc_var in target.items(): # Check for connectivity variable references, iterating through # the valid cf roles. for identity in cls.cf_identities: nc_var_att = getattr(nc_var, identity, None) if nc_var_att is not None: # UGRID only allows for one of each connectivity cf role. name = nc_var_att.strip() if name not in ignore: if name not in variables: message = ( f"Missing CF-UGRID connectivity variable " f"{name}, referenced by netCDF variable " f"{nc_var_name}" ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) else: # Restrict to non-string type i.e. not a # CFLabelVariable. if not cf._is_str_dtype(variables[name]): result[name] = CFUGridConnectivityVariable( name, variables[name] ) else: message = ( f"Ignoring variable {name}, identified " f"as a CF-UGRID connectivity - is a " f"CF-netCDF label variable." ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) return result class CFUGridAuxiliaryCoordinateVariable(cf.CFVariable): """ A CF-UGRID auxiliary coordinate variable is a CF-netCDF auxiliary coordinate variable representing the element (node/edge/face/volume) locations (latitude, longitude or other spatial coordinates, and optional elevation or other coordinates). These auxiliary coordinate variables will have length n-elements. For elements other than nodes, these auxiliary coordinate variables may have in turn a ``bounds`` attribute that specifies the bounding coordinates of the element (thereby duplicating the data in the ``node_coordinates`` variables). Identified by the CF-netCDF variable attribute ``node_``/``edge_``/``face_``/``volume_coordinates``. .. seealso:: The UGRID Conventions, https://ugrid-conventions.github.io/ugrid-conventions/ """ cf_identity = NotImplemented cf_identities = [ "node_coordinates", "edge_coordinates", "face_coordinates", "volume_coordinates", ] @classmethod def identify(cls, variables, ignore=None, target=None, warn=True): result = {} ignore, target = cls._identify_common(variables, ignore, target) # TODO: reconsider logging level when we have consistent practice. log_level = logging.WARNING if warn else logging.DEBUG # Identify any CF-UGRID-relevant auxiliary coordinate variables. for nc_var_name, nc_var in target.items(): # Check for UGRID auxiliary coordinate variable references. for identity in cls.cf_identities: nc_var_att = getattr(nc_var, identity, None) if nc_var_att is not None: for name in nc_var_att.split(): if name not in ignore: if name not in variables: message = ( f"Missing CF-netCDF auxiliary coordinate " f"variable {name}, referenced by netCDF " f"variable {nc_var_name}" ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) else: # Restrict to non-string type i.e. not a # CFLabelVariable. if not cf._is_str_dtype(variables[name]): result[ name ] = CFUGridAuxiliaryCoordinateVariable( name, variables[name] ) else: message = ( f"Ignoring variable {name}, " f"identified as a CF-netCDF " f"auxiliary coordinate - is a " f"CF-netCDF label variable." ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) return result class CFUGridMeshVariable(cf.CFVariable): """ A CF-UGRID mesh variable is a dummy variable for storing topology information as attributes. The mesh variable has the ``cf_role`` 'mesh_topology'. The UGRID conventions describe define the mesh topology as the interconnection of various geometrical elements of the mesh. The pure interconnectivity is independent of georeferencing the individual geometrical elements, but for the practical applications for which the UGRID CF extension is defined, coordinate data will always be added. Identified by the CF-netCDF variable attribute 'mesh'. .. seealso:: The UGRID Conventions, https://ugrid-conventions.github.io/ugrid-conventions/ """ cf_identity = "mesh" @classmethod def identify(cls, variables, ignore=None, target=None, warn=True): result = {} ignore, target = cls._identify_common(variables, ignore, target) # TODO: reconsider logging level when we have consistent practice. log_level = logging.WARNING if warn else logging.DEBUG # Identify all CF-UGRID mesh variables. all_vars = target == variables for nc_var_name, nc_var in target.items(): if all_vars: # SPECIAL BEHAVIOUR FOR MESH VARIABLES. # We are looking for all mesh variables. Check if THIS variable # is a mesh using its own attributes. if getattr(nc_var, "cf_role", "") == "mesh_topology": result[nc_var_name] = CFUGridMeshVariable( nc_var_name, nc_var ) # Check for mesh variable references. nc_var_att = getattr(nc_var, cls.cf_identity, None) if nc_var_att is not None: # UGRID only allows for 1 mesh per variable. name = nc_var_att.strip() if name not in ignore: if name not in variables: message = ( f"Missing CF-UGRID mesh variable {name}, " f"referenced by netCDF variable {nc_var_name}" ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) else: # Restrict to non-string type i.e. not a # CFLabelVariable. if not cf._is_str_dtype(variables[name]): result[name] = CFUGridMeshVariable( name, variables[name] ) else: message = ( f"Ignoring variable {name}, identified as a " f"CF-UGRID mesh - is a CF-netCDF label " f"variable." ) logger.log( level=log_level, msg=message, extra=dict(cls=cls.__name__), ) return result class CFUGridGroup(cf.CFGroup): """ Represents a collection of 'NetCDF Climate and Forecast (CF) Metadata Conventions' variables and netCDF global attributes. Specialisation of :class:`~iris.fileformats.cf.CFGroup` that includes extra collections for CF-UGRID-specific variable types. """ @property def connectivities(self): """Collection of CF-UGRID connectivity variables.""" return self._cf_getter(CFUGridConnectivityVariable) @property def ugrid_coords(self): """Collection of CF-UGRID-relevant auxiliary coordinate variables.""" return self._cf_getter(CFUGridAuxiliaryCoordinateVariable) @property def meshes(self): """Collection of CF-UGRID mesh variables.""" return self._cf_getter(CFUGridMeshVariable) @property def non_data_variable_names(self): """ :class:`set` of the names of the CF-netCDF/CF-UGRID variables that are not the data pay-load. """ extra_variables = (self.connectivities, self.ugrid_coords, self.meshes) extra_result = set() for variable in extra_variables: extra_result |= set(variable) return super().non_data_variable_names | extra_result class CFUGridReader(cf.CFReader): """ This class allows the contents of a netCDF file to be interpreted according to the 'NetCDF Climate and Forecast (CF) Metadata Conventions'. Specialisation of :class:`~iris.fileformats.cf.CFReader` that can also handle CF-UGRID-specific variable types. """ _variable_types = cf.CFReader._variable_types + ( CFUGridConnectivityVariable, CFUGridAuxiliaryCoordinateVariable, CFUGridMeshVariable, ) CFGroup = CFUGridGroup
lgpl-3.0
MagicDroidX/Nukkit
src/main/java/cn/nukkit/utils/MainLogger.java
11265
package cn.nukkit.utils; import cn.nukkit.Nukkit; import cn.nukkit.command.CommandReader; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; import java.io.*; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; /** * author: MagicDroidX * Nukkit */ public class MainLogger extends ThreadedLogger { protected final String logPath; protected final ConcurrentLinkedQueue<String> logBuffer = new ConcurrentLinkedQueue<>(); protected boolean shutdown; protected LogLevel logLevel = LogLevel.DEFAULT_LEVEL; private final Map<TextFormat, String> replacements = new EnumMap<>(TextFormat.class); private final TextFormat[] colors = TextFormat.values(); protected static MainLogger logger; public MainLogger(String logFile) { this(logFile, LogLevel.DEFAULT_LEVEL); } public MainLogger(String logFile, LogLevel logLevel) { if (logger != null) { throw new RuntimeException("MainLogger has been already created"); } logger = this; this.logPath = logFile; this.start(); } public MainLogger(String logFile, boolean logDebug) { this(logFile, logDebug ? LogLevel.DEBUG : LogLevel.INFO); } public static MainLogger getLogger() { return logger; } @Override public void emergency(String message) { if (LogLevel.EMERGENCY.getLevel() <= logLevel.getLevel()) this.send(TextFormat.RED + "[EMERGENCY] " + message); } @Override public void alert(String message) { if (LogLevel.ALERT.getLevel() <= logLevel.getLevel()) this.send(TextFormat.RED + "[ALERT] " + message); } @Override public void critical(String message) { if (LogLevel.CRITICAL.getLevel() <= logLevel.getLevel()) this.send(TextFormat.RED + "[CRITICAL] " + message); } @Override public void error(String message) { if (LogLevel.ERROR.getLevel() <= logLevel.getLevel()) this.send(TextFormat.DARK_RED + "[ERROR] " + message); } @Override public void warning(String message) { if (LogLevel.WARNING.getLevel() <= logLevel.getLevel()) this.send(TextFormat.YELLOW + "[WARNING] " + message); } @Override public void notice(String message) { if (LogLevel.NOTICE.getLevel() <= logLevel.getLevel()) this.send(TextFormat.AQUA + "[NOTICE] " + message); } @Override public void info(String message) { if (LogLevel.INFO.getLevel() <= logLevel.getLevel()) this.send(TextFormat.WHITE + "[INFO] " + message); } @Override public void debug(String message) { if (LogLevel.DEBUG.getLevel() <= logLevel.getLevel()) this.send(TextFormat.GRAY + "[DEBUG] " + message); } public void setLogDebug(Boolean logDebug) { this.logLevel = logDebug ? LogLevel.DEBUG : LogLevel.INFO; } public void logException(Exception e) { this.alert(Utils.getExceptionMessage(e)); } @Override public void log(LogLevel level, String message) { switch (level) { case EMERGENCY: this.emergency(message); break; case ALERT: this.alert(message); break; case CRITICAL: this.critical(message); break; case ERROR: this.error(message); break; case WARNING: this.warning(message); break; case NOTICE: this.notice(message); break; case INFO: this.info(message); break; case DEBUG: this.debug(message); break; } } public void shutdown() { this.shutdown = true; } protected void send(String message) { this.send(message, -1); synchronized (this) { this.notify(); } } protected void send(String message, int level) { logBuffer.add(message); } private String colorize(String string) { if (string.indexOf(TextFormat.ESCAPE) < 0) { return string; } else if (Nukkit.ANSI) { for (TextFormat color : colors) { if (replacements.containsKey(color)) { string = string.replaceAll("(?i)" + color, replacements.get(color)); } else { string = string.replaceAll("(?i)" + color, ""); } } } else { return TextFormat.clean(string); } return string + Ansi.ansi().reset(); } @Override public void run() { AnsiConsole.systemInstall(); File logFile = new File(logPath); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { this.logException(e); } } else { long date = logFile.lastModified(); String newName = new SimpleDateFormat("Y-M-d HH.mm.ss").format(new Date(date)) + ".log"; File oldLogs = new File(Nukkit.DATA_PATH, "logs"); if (!oldLogs.exists()) { oldLogs.mkdirs(); } logFile.renameTo(new File(oldLogs, newName)); logFile = new File(logPath); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { this.logException(e); } } } replacements.put(TextFormat.BLACK, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString()); replacements.put(TextFormat.DARK_BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString()); replacements.put(TextFormat.DARK_GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString()); replacements.put(TextFormat.DARK_AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString()); replacements.put(TextFormat.DARK_RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString()); replacements.put(TextFormat.DARK_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString()); replacements.put(TextFormat.GOLD, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString()); replacements.put(TextFormat.GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString()); replacements.put(TextFormat.DARK_GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString()); replacements.put(TextFormat.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString()); replacements.put(TextFormat.GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString()); replacements.put(TextFormat.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString()); replacements.put(TextFormat.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString()); replacements.put(TextFormat.LIGHT_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString()); replacements.put(TextFormat.YELLOW, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString()); replacements.put(TextFormat.WHITE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString()); replacements.put(TextFormat.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString()); replacements.put(TextFormat.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString()); replacements.put(TextFormat.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString()); replacements.put(TextFormat.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString()); replacements.put(TextFormat.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString()); this.shutdown = false; do { flushBuffer(logFile); } while (!this.shutdown); flushBuffer(logFile); } private void flushBuffer(File logFile) { if (logBuffer.isEmpty()) { try { synchronized (this) { wait(25000); // Wait for next message } Thread.sleep(5); // Buffer for 5ms to reduce back and forth between disk } catch (InterruptedException ignore) { } } try { Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8), 1024); Date now = new Date(); String consoleDateFormat = new SimpleDateFormat("HH:mm:ss ").format(now); String fileDateFormat = new SimpleDateFormat("Y-M-d HH:mm:ss ").format(now); int count = 0; while (!logBuffer.isEmpty()) { String message = logBuffer.poll(); if (message != null) { writer.write(fileDateFormat); writer.write(TextFormat.clean(message)); writer.write("\r\n"); CommandReader.getInstance().stashLine(); System.out.println(colorize(TextFormat.AQUA + consoleDateFormat + TextFormat.RESET + message + TextFormat.RESET)); CommandReader.getInstance().unstashLine(); } } writer.flush(); writer.close(); } catch (Exception e) { this.logException(e); } } @Override public void emergency(String message, Throwable t) { this.emergency(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void alert(String message, Throwable t) { this.alert(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void critical(String message, Throwable t) { this.critical(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void error(String message, Throwable t) { this.error(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void warning(String message, Throwable t) { this.warning(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void notice(String message, Throwable t) { this.notice(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void info(String message, Throwable t) { this.info(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void debug(String message, Throwable t) { this.debug(message + "\r\n" + Utils.getExceptionMessage(t)); } @Override public void log(LogLevel level, String message, Throwable t) { this.log(level, message + "\r\n" + Utils.getExceptionMessage(t)); } }
lgpl-3.0
SciTools/iris
lib/iris/tests/unit/common/lenient/__init__.py
254
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :mod:`iris.common.lenient` package."""
lgpl-3.0
tobyt42/brjs
brjs-sdk/sdk/libs/javascript/br-presenter/test-acceptance/tests/control/selectionfield/JQueryAutoCompleteControlTest.js
6959
(function() { var GwtTestRunner = require("br/test/GwtTestRunner"); GwtTestRunner.initialize(); describe("View to model interactions for JQueryAutoCompleteControlAdapter", function() { fixtures( require("br/presenter/PresenterFixtureFactory") ); it("starts enabled and visible by default", function() { given("demo.viewOpened = true"); then("demo.view.(#jqueryAutoCompleteBox).enabled = true"); and("demo.view.(#jqueryAutoCompleteBox).isVisible = true"); }); it("has the correct initial value", function() { given("demo.viewOpened = true"); then("demo.view.(#jqueryAutoCompleteBox).value = 'BB'"); and("demo.view.(#jqueryAutoCompleteBox).doesNotHaveClass = 'autocomplete-menu-open'"); }); it("correctly auto completes a valid input option", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox).typedValue => 'A'"); then("demo.view.(#autocomplete-container li:eq(0)).text = 'AA'"); }); it("shows no options for invalid text", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox).typedValue => 'D'"); then("demo.view.(#autocomplete-container li).count = '0'"); }); it("allows clicking on option to set the value", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox).typedValue => 'A'"); and("demo.view.(#autocomplete-container li:eq(0) a).clicked => true"); then("demo.model.jquerySelectionField.value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox).value = 'AA'"); }); it("sets the formatted value to the textbox", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox).typedValue => 'F'"); and("demo.view.(#autocomplete-container li:eq(0) a).clicked => true"); then("demo.view.(#jqueryAutoCompleteBox).value = 'Formatted'"); }); it("hides the dropdown when the page is scrolled", function() { given("test.continuesFrom = 'correctly auto completes a valid input option'"); when("test.page.(div:first).mouseWheel => '20'"); then("demo.view.(#autocomplete-container li).isVisible = false"); }); it("does not hide the dropdown when the menu is scrolled", function() { given("test.continuesFrom = 'correctly auto completes a valid input option'"); when("demo.view.(#autocomplete-container .ui-menu-item:first).mouseWheel => '20'"); then("demo.view.(#autocomplete-container li).isVisible = true"); }); it("adds a class to the input and when it opens", function() { given("test.continuesFrom = 'correctly auto completes a valid input option'"); then("demo.view.(#jqueryAutoCompleteBox).hasClass = 'autocomplete-menu-open'"); }); it("removes a class from the input when it closes", function() { given("test.continuesFrom = 'hides the dropdown when the page is scrolled'"); then("demo.view.(#jqueryAutoCompleteBox).doesNotHaveClass = 'autocomplete-menu-open'"); }); it("does not display any options if minCharAmount is set to 2", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox2).typedValue => 'A'"); then("demo.view.(#autocomplete-container2 li).count = '0'"); }); it("does display options if minCharAmount is set to 2 and typed text is at least 2 chars long", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox2).typedValue => 'AA'"); then("demo.view.(#autocomplete-container2 li:eq(0)).text = 'AA'"); }); it("does not blur the input after selection if blurAfterClick is not provided", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox).typedValue => 'A'"); and("demo.view.(#autocomplete-container li:eq(0) a).clicked => true"); then("demo.model.jquerySelectionField.value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox).value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox).focused = true"); }); it("does blur the input after selection is made by click if blurAfterClick is set to true", function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox3).typedValue => 'A'"); and("demo.view.(#autocomplete-container3 li:eq(0) a).clicked => true"); then("demo.model.jquerySelectionField.value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox3).value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox3).focused = false"); }); it("does not show the menu immediately when a delay option is given", function() { given("demo.viewOpened = true"); and("time.timeMode = 'Manual'"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox4).typedValue => 'A'"); then("demo.view.(#autocomplete-container4 li).count = '0'"); }); it("shows the menu after some time when a delay option is given", function() { given("test.continuesFrom = 'does not show the menu immediately when a delay option is given'"); when("time.passedBy => 200"); then("demo.view.(#autocomplete-container4 li).isVisible = true"); and("demo.view.(#autocomplete-container4 li:eq(0)).text = 'AA'"); }); it('clears the textbox after a valid option was chosen', function() { given("demo.viewOpened = true"); when("demo.model.jquerySelectionField.value => ''"); and("demo.view.(#jqueryAutoCompleteBox5).typedValue => 'A'"); and("demo.view.(#autocomplete-container5 li:eq(0) a).clicked => true"); then("demo.model.jquerySelectionField.value = 'AA'"); and("demo.view.(#jqueryAutoCompleteBox5).value = ''"); }); }); })();
lgpl-3.0
redbear/firmware
hal/src/photon/socket_hal.cpp
33218
/** ****************************************************************************** * @file socket_hal.c * @author Matthew McGowan * @version V1.0.0 * @date 09-Nov-2014 * @brief ****************************************************************************** Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #include "socket_hal.h" #include "wiced.h" #include "service_debug.h" #include "spark_macros.h" #include "delay_hal.h" #include <algorithm> #include <vector> #include "lwip/api.h" #include "network_interface.h" #include "spark_wiring_thread.h" #include "spark_wiring_vector.h" wiced_result_t wiced_last_error( wiced_tcp_socket_t* socket); /** * Socket handles * -------------- * * Each socket handle is a pointer to a dynamically allocated instance of socket_t. * This is so we don't impose any additional limits on the number of open sockets. * * The golden rule is that the socket_t instance is not deallocated until the caller * issues a socket_close() call. Specifically, if a client socket is closed by the other end, * the handle remains valid, although attempts to perform any socket IO will fail. * The handle isn't deallocated until the caller issues a socket_close() call. */ /** * int32_t negative values are used for errors. * Since all handles are allocated in RAM, they will be in the * 0x20xxxxxx range. */ const sock_handle_t SOCKET_MAX = 0x7FFFFFFF; /** * The handle value returned when a socket cannot be created. */ const sock_handle_t SOCKET_INVALID = (sock_handle_t)-1; /* Normalize differences between LwIP and NetX */ #ifndef WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS // the name of the array of sockets in wiced_tcp_server_t #define WICED_SOCKET_ARRAY accept_socket // the number of sockets in the above array #define WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS WICED_MAXIMUM_NUMBER_OF_ACCEPT_SOCKETS #else #define WICED_SOCKET_ARRAY socket #endif /** * Manages reading from a tcp packet. */ struct tcp_packet_t { /** * Any outstanding packet to retrieve data from. */ wiced_packet_t* packet; /** * The current offset of data already read from the packet. */ unsigned offset; tcp_packet_t() {} ~tcp_packet_t() { dispose_packet(); } void dispose_packet() { if (packet) { wiced_packet_delete(packet); packet = NULL; offset = 0; } } }; /** * The info we maintain for each socket. It wraps a WICED socket. * */ struct tcp_socket_t : public wiced_tcp_socket_t { tcp_packet_t packet; bool open; volatile bool closed_externally; tcp_socket_t() : open(false), closed_externally(false) {} ~tcp_socket_t() { wiced_tcp_delete_socket(this); } void connected() { open = true; } bool isClosed() { wiced_result_t last_err = wiced_last_error(this); return !open || closed_externally || last_err == WICED_CONNECTION_RESET || last_err == WICED_CONNECTION_CLOSED; } void notify_disconnected() { closed_externally = true; } void close() { if (open) { wiced_tcp_disconnect(this); open = false; } } }; struct udp_socket_t : wiced_udp_socket_t { ~udp_socket_t() { wiced_udp_delete_socket(this); } void close() { } }; struct tcp_server_t; /** * The handle that we provide to external clients. This ensures */ class tcp_server_client_t { wiced_tcp_socket_t* socket; tcp_server_t* server; volatile bool closed; public: tcp_packet_t packet; tcp_server_client_t(tcp_server_t* server, wiced_tcp_socket_t* socket) { this->socket = socket; this->server = server; this->closed = 0; memset(&packet, 0, sizeof(packet)); } wiced_tcp_socket_t* get_socket() { return socket; } wiced_result_t write(const void* buffer, size_t len, size_t* bytes_written, uint32_t flags, system_tick_t timeout, bool flush=false) { wiced_result_t result = WICED_TCPIP_INVALID_SOCKET; if (socket) { wiced_tcp_send_flags_t wiced_flags = timeout == 0 ? WICED_TCP_SEND_FLAG_NONBLOCK : WICED_TCP_SEND_FLAG_NONE; uint16_t bytes_sent = (uint16_t)len; result = wiced_tcp_send_buffer_ex(socket, buffer, &bytes_sent, wiced_flags, timeout); *bytes_written = bytes_sent; } return result; } bool isClosed() { if (closed) { close(); } return closed; } void close(); /** * Notification from the server that this socket has been disconnected. The server is * already in the process of cleaning up the socket. */ void notify_disconnected() { // flag that this is closed, but don't clean up, since this call is on the // wiced networking worker thread. we want all calls to be on one thread, so service // the close on the enxt call to isClosed() by the client. closed = true; } ~tcp_server_client_t(); }; struct tcp_server_t : public wiced_tcp_server_t { tcp_server_t() { os_mutex_create(&accept_lock); memset(clients, 0, sizeof(clients)); } ~tcp_server_t() { os_mutex_destroy(accept_lock); } /** * Find the index of the given client socket in our list of client sockets. * @param socket The socket to find. * @return The index of the socket (>=0) or -1 if not found. */ int index(wiced_tcp_socket_t* socket) { return (is_client(socket)) ? socket-this->WICED_SOCKET_ARRAY : -1; } /** * Determines if the given socket is a client socket associated with this server * socket. * @param socket * @return {@code true} if the given socket is a client. */ bool is_client(wiced_tcp_socket_t* socket) { // see if the address corresponds to the socket array return this->WICED_SOCKET_ARRAY<=socket && socket<this->WICED_SOCKET_ARRAY+arraySize(this->WICED_SOCKET_ARRAY); } wiced_result_t accept(wiced_tcp_socket_t* socket) { wiced_result_t result; if ((result=wiced_tcp_accept(socket))==WICED_SUCCESS) { os_mutex_lock(accept_lock); int idx = index(socket); if (idx>=0) { clients[idx] = new tcp_server_client_t(this, socket); to_accept.append(idx); } os_mutex_unlock(accept_lock); } return result; } /** * Fetches the next client socket from the accept queue. * @return The next client, or NULL */ tcp_server_client_t* next_accept() { os_mutex_lock(accept_lock); int index = -1; if (to_accept.size()) { index = *to_accept.begin(); to_accept.removeAt(0); } os_mutex_unlock(accept_lock); return index>=0 ? clients[index] : NULL; } /** * Asynchronous notification that the client socket has been closed. * @param socket * @return */ wiced_result_t notify_disconnected(wiced_tcp_socket_t* socket) { os_mutex_lock(accept_lock); int idx = index(socket); tcp_server_client_t* client = clients[idx]; if (client) client->notify_disconnected(); os_mutex_unlock(accept_lock); return WICED_SUCCESS; } /** * Called from the client to disconnect this server. * @param socket * @return */ wiced_result_t disconnect(wiced_tcp_socket_t* socket) { wiced_tcp_disconnect(socket); // remove from client array as this socket is getting closed and // subsequently destroyed int idx = index(socket); if (idx >= 0) { clients[idx] = NULL; } wiced_result_t result = wiced_tcp_server_disconnect_socket(this, socket); return result; } void close() { // close all clients first for (int i=0; i<WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS; i++) { tcp_server_client_t* client = clients[i]; if (client) { client->close(); clients[i] = NULL; } } wiced_tcp_server_stop(this); } private: // for each server instance, maintain an associated tcp_server_client_t instance tcp_server_client_t* clients[WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS]; os_mutex_t accept_lock; spark::Vector<int> to_accept; }; void tcp_server_client_t::close() { if (socket && server) { server->disconnect(socket); server = NULL; socket = NULL; } packet.dispose_packet(); } tcp_server_client_t::~tcp_server_client_t() { close(); } class socket_t { uint8_t type; bool closed; public: union all { tcp_socket_t tcp; udp_socket_t udp; tcp_server_t* tcp_server; tcp_server_client_t* tcp_client; all() {} ~all() {} } s; socket_t* next; enum socket_type_t { NONE, TCP, UDP, TCP_SERVER, TCP_CLIENT }; socket_t() { memset(this, 0, sizeof(*this)); } ~socket_t() { dispose(); } uint8_t get_type() { return type; } bool is_type(socket_type_t t) { return t==type; } void set_type(socket_type_t t) { type = t; } void set_server(tcp_server_t* server) { type = TCP_SERVER; s.tcp_server = server; } void set_client(tcp_server_client_t* client) { type = TCP_CLIENT; s.tcp_client = client; } void dispose() { close(); switch (type) { case TCP: s.tcp.~tcp_socket_t(); break; case UDP: s.udp.~udp_socket_t(); break; case TCP_SERVER: delete s.tcp_server; break; case TCP_CLIENT: delete s.tcp_client; break; } type = NONE; } void close() { if (!closed) { switch (type) { case TCP: s.tcp.close(); break; case UDP: s.udp.close(); break; case TCP_SERVER: s.tcp_server->close(); break; case TCP_CLIENT: s.tcp_client->close(); break; } closed = true; } } static wiced_result_t notify_connected(wiced_tcp_socket_t*, void* socket) { return WICED_SUCCESS; } static wiced_result_t notify_received(wiced_tcp_socket_t*, void* socket) { return WICED_SUCCESS; } static wiced_result_t notify_disconnected(wiced_tcp_socket_t*, void* socket); /** * Determines if the socket implementation is still open. * @return */ bool is_inner_open() { // TCP_SERVER closes this outer instance, and UDP is not connection based. switch (type) { case TCP_CLIENT : return !s.tcp_client->isClosed(); case TCP: return !s.tcp.isClosed(); default: return true; } } bool isOpen() { return !closed && is_inner_open(); } }; /** * Maintains a singly linked list of sockets. Access to the list is not * made thread-safe - callers should use SocketListLock to correctly serialize * access to the list. */ struct SocketList { socket_t* items; Mutex mutex; public: SocketList() : items(NULL) { } ~SocketList() { } /** * Adds an item to the linked list. * @param item * @param list */ void add(socket_t* item) { item->next = items; items = item; } bool exists(socket_t* item) { bool exists = false; socket_t* list = this->items; while (list) { if (item==list) { exists = true; break; } list = list->next; } return exists; } /** * Removes an item from the linked list. * @param item * @param list */ bool remove(socket_t* item) { bool removed = false; if (items==item) { items = item->next; removed = true; } else { socket_t* current = items; while (current) { if (current->next==item) { current->next = item->next; removed = true; break; } current = current->next; } } return removed; } void close_all() { socket_t* current = items; while (current) { socket_t* next = current->next; delete current; current = next; } items = NULL; } friend class SocketListLock; }; struct SocketListLock : std::lock_guard<Mutex> { SocketListLock(SocketList& list) : std::lock_guard<Mutex>(list.mutex) {}; }; class ServerSocketList : public SocketList { public: /** * * Low-level function to find the server that a given wiced tcp client * is associated with. The WICED callbacks provide the client socket, but * not the server it is associated with. * @param client * @return */ tcp_server_t* server_for_socket(wiced_tcp_socket_t* client) { socket_t* server = items; while (server) { if (server->s.tcp_server->is_client(client)) return server->s.tcp_server; server = server->next; } return NULL; } }; /** * Singly linked lists for servers and clients. Ensures we can completely shutdown * the socket layer when bringing down a network interface. */ static ServerSocketList servers; static SocketList clients; SocketList& list_for(socket_t* socket) { return (socket->get_type()==socket_t::TCP_SERVER) ? servers : clients; } void add_socket(socket_t* socket) { if (socket) { list_for(socket).add(socket); } } /** * Determines if the given socket still exists in the list of current sockets. */ bool exists_socket(socket_t* socket) { return socket && list_for(socket).exists(socket); } inline bool is_udp(socket_t* socket) { return socket && socket->is_type(socket_t::UDP); } inline bool is_tcp(socket_t* socket) { return socket && socket->is_type(socket_t::TCP); } inline bool is_client(socket_t* socket) { return socket && socket->is_type(socket_t::TCP_CLIENT); } inline bool is_server(socket_t* socket) { return socket && socket->is_type(socket_t::TCP_SERVER); } inline bool is_open(socket_t* socket) { return socket && socket->isOpen(); } inline tcp_socket_t* tcp(socket_t* socket) { return is_tcp(socket) ? &socket->s.tcp : NULL; } inline udp_socket_t* udp(socket_t* socket) { return is_udp(socket) ? &socket->s.udp : NULL; } inline tcp_server_client_t* client(socket_t* socket) { return is_client(socket) ? socket->s.tcp_client : NULL; } inline tcp_server_t* server(socket_t* socket) { return is_server(socket) ? socket->s.tcp_server : NULL; } wiced_result_t socket_t::notify_disconnected(wiced_tcp_socket_t*, void* socket) { if (socket && 0) { // replace with unique_lock once the multithreading changes have been incorporated SocketListLock lock(clients); if (exists_socket((socket_t*)socket)) { tcp_socket_t* tcp_socket = tcp((socket_t*)socket); if (tcp_socket) tcp_socket->notify_disconnected(); } } return WICED_SUCCESS; } wiced_tcp_socket_t* as_wiced_tcp_socket(socket_t* socket) { if (is_tcp(socket)) { return tcp(socket); } else if (is_client(socket)) { return socket->s.tcp_client->get_socket(); } return NULL; } /** * Determines if the given socket handle is valid. * @param handle The handle to test * @return {@code true} if the socket handle is valid, {@code false} otherwise. * Note that this doesn't guarantee the socket can be used, only that the handle * is within a valid range. To determine if a handle has an associated socket, * use {@link #from_handle} */ inline bool is_valid(sock_handle_t handle) { return handle<SOCKET_MAX; } uint8_t socket_handle_valid(sock_handle_t handle) { return is_valid(handle); } /** * Fetches the socket_t info from an opaque handle. * @return The socket_t pointer, or NULL if no socket is available for the * given handle. */ socket_t* from_handle(sock_handle_t handle) { return is_valid(handle) ? (socket_t*)handle : NULL; } /** * Discards a previously allocated socket. If the socket is already invalid, returns silently. * Once a socket has been passed to the client, this is the only time the object is * deleted. Since the client initiates this call, the client is aware can the * socket is no longer valid. * @param handle The handle to discard. * @return SOCKET_INVALID always. */ sock_handle_t socket_dispose(sock_handle_t handle) { if (socket_handle_valid(handle)) { socket_t* socket = from_handle(handle); SocketList& list = list_for(socket); SocketListLock lock(list); if (list.remove(socket)) delete socket; } return SOCKET_INVALID; } void close_all(SocketList& list) { SocketListLock lock(list); list.close_all(); } void socket_close_all() { close_all(clients); close_all(servers); } #define SOCKADDR_TO_PORT_AND_IPADDR(addr, addr_data, port, ip_addr) \ const uint8_t* addr_data = addr->sa_data; \ unsigned port = addr_data[0]<<8 | addr_data[1]; \ wiced_ip_address_t INITIALISER_IPV4_ADDRESS(ip_addr, MAKE_IPV4_ADDRESS(addr_data[2], addr_data[3], addr_data[4], addr_data[5])); sock_result_t as_sock_result(wiced_result_t result) { return -result; } sock_result_t as_sock_result(socket_t* socket) { return (sock_result_t)(socket); } /** * Connects the given socket to the address. * @param sd The socket handle to connect * @param addr The address to connect to * @param addrlen The length of the address details. * @return 0 on success. */ sock_result_t socket_connect(sock_handle_t sd, const sockaddr_t *addr, long addrlen) { wiced_result_t result = WICED_INVALID_SOCKET; socket_t* socket = from_handle(sd); tcp_socket_t* tcp_socket = tcp(socket); if (tcp_socket) { result = wiced_tcp_bind(tcp_socket, WICED_ANY_PORT); if (result==WICED_SUCCESS) { // WICED callbacks are broken //wiced_tcp_register_callbacks(tcp(socket), socket_t::notify_connected, socket_t::notify_received, socket_t::notify_disconnected, (void*)socket); SOCKADDR_TO_PORT_AND_IPADDR(addr, addr_data, port, ip_addr); unsigned timeout = 5*1000; result = wiced_tcp_connect(tcp_socket, &ip_addr, port, timeout); if (result==WICED_SUCCESS) { tcp_socket->connected(); } else { // Work around WICED bug that doesn't set connection handler to NULL after deleting // it, leading to deleting the same memory twice and a crash // WICED/network/LwIP/WICED/tcpip.c:920 tcp_socket->conn_handler = NULL; } } } return as_sock_result(result); } /** * Is there any way to unblock a blocking call on WICED? Perhaps shutdown the networking layer? * @return */ sock_result_t socket_reset_blocking_call() { return 0; } wiced_result_t read_packet(wiced_packet_t* packet, uint8_t* target, uint16_t target_len, uint16_t* read_len) { uint16_t read = 0; wiced_result_t result = WICED_SUCCESS; uint16_t fragment; uint16_t available; uint8_t* data; while (target_len!=0 && (result = wiced_packet_get_data(packet, read, &data, &fragment, &available))==WICED_SUCCESS && available!=0) { uint16_t to_read = std::min(fragment, target_len); memcpy(target+read, data, to_read); read += to_read; target_len -= to_read; available -= to_read; if (!available) break; } if (read_len!=NULL) *read_len = read; return result; } int read_packet_and_dispose(tcp_packet_t& packet, void* buffer, int len, wiced_tcp_socket_t* tcp_socket, int _timeout) { int bytes_read = 0; if (!packet.packet) { packet.offset = 0; wiced_result_t result = wiced_tcp_receive(tcp_socket, &packet.packet, _timeout); if (result!=WICED_SUCCESS && result!=WICED_TIMEOUT) { DEBUG("Socket %d receive fail %d", (int)(int)tcp_socket->socket, int(result)); return -result; } } uint8_t* data; uint16_t available; uint16_t total; bool dispose = true; if (packet.packet && (wiced_packet_get_data(packet.packet, packet.offset, &data, &available, &total)==WICED_SUCCESS)) { int read = std::min(uint16_t(len), available); packet.offset += read; memcpy(buffer, data, read); dispose = (total==read); bytes_read = read; DEBUG("Socket %d receive bytes %d of %d", (int)(int)tcp_socket->socket, int(bytes_read), int(available)); } if (dispose) { packet.dispose_packet(); } return bytes_read; } /** * Receives data from a socket. * @param sd * @param buffer * @param len * @param _timeout * @return The number of bytes read. -1 if the end of the stream is reached. */ sock_result_t socket_receive(sock_handle_t sd, void* buffer, socklen_t len, system_tick_t _timeout) { sock_result_t bytes_read = -1; socket_t* socket = from_handle(sd); if (is_open(socket)) { if (is_tcp(socket)) { tcp_socket_t* tcp_socket = tcp(socket); tcp_packet_t& packet = tcp_socket->packet; bytes_read = read_packet_and_dispose(packet, buffer, len, tcp_socket, _timeout); } else if (is_client(socket)) { tcp_server_client_t* server_client = client(socket); bytes_read = read_packet_and_dispose(server_client->packet, buffer, len, server_client->get_socket(), _timeout); } } if (bytes_read<0) DEBUG("socket_receive on %d returned %d", sd, bytes_read); return bytes_read; } /** * Notification from the networking thread that the given client socket connected * to the server. * @param socket */ wiced_result_t server_connected(wiced_tcp_socket_t* s, void* pv) { SocketListLock lock(servers); tcp_server_t* server = servers.server_for_socket(s); wiced_result_t result = WICED_ERROR; if (server) { result = server->accept(s); } return result; } /** * Notification that the client socket has data. * @param socket */ wiced_result_t server_received(wiced_tcp_socket_t* socket, void* pv) { return WICED_SUCCESS; } /** * Notification that the client socket closed the connection. * @param socket */ wiced_result_t server_disconnected(wiced_tcp_socket_t* s, void* pv) { SocketListLock lock(servers); tcp_server_t* server = servers.server_for_socket(s); wiced_result_t result = WICED_ERROR; if (server) { // disconnect the socket from the server, but maintain the client // socket handle. result = server->notify_disconnected(s); } return result; } sock_result_t socket_create_tcp_server(uint16_t port, network_interface_t nif) { socket_t* socket = new socket_t(); tcp_server_t* server = new tcp_server_t(); wiced_result_t result = WICED_OUT_OF_HEAP_SPACE; if (socket && server) { result = wiced_tcp_server_start(server, wiced_wlan_interface(nif), port, WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS, server_connected, server_received, server_disconnected, NULL); } if (result!=WICED_SUCCESS) { delete socket; socket = NULL; delete server; server = NULL; } else { socket->set_server(server); SocketListLock lock(list_for(socket)); add_socket(socket); } return socket ? as_sock_result(socket) : as_sock_result(result); } /** * Fetch the next waiting client socket from the server * @param sock * @return */ sock_result_t socket_accept(sock_handle_t sock) { sock_result_t result = SOCKET_INVALID; socket_t* socket = from_handle(sock); if (is_open(socket) && is_server(socket)) { tcp_server_t* server = socket->s.tcp_server; tcp_server_client_t* client = server->next_accept(); if (client) { socket_t* socket = new socket_t(); socket->set_client(client); { SocketListLock lock(list_for(socket)); add_socket(socket); } result = (sock_result_t)socket; } } return result; } /** * Determines if a given socket is bound. * @param sd The socket handle to test * @return non-zero if bound, 0 otherwise. */ uint8_t socket_active_status(sock_handle_t sd) { socket_t* socket = from_handle(sd); return (socket && socket->isOpen()) ? SOCKET_STATUS_ACTIVE : SOCKET_STATUS_INACTIVE; } /** * Closes the socket handle. * @param sock * @return */ sock_result_t socket_close(sock_handle_t sock) { sock_result_t result = WICED_SUCCESS; socket_t* socket = from_handle(sock); if (socket) { socket_dispose(sock); LOG_DEBUG(TRACE, "socket closed %x", int(sock)); } return result; } sock_result_t socket_shutdown(sock_handle_t sd, int how) { sock_result_t result = WICED_ERROR; socket_t* socket = from_handle(sd); if (socket && is_open(socket) && is_tcp(socket)) { result = wiced_tcp_close_shutdown(tcp(socket), (wiced_tcp_shutdown_flags_t)how); LOG_DEBUG(TRACE, "socket shutdown %x %x", sd, how); } return result; } /** * Create a new socket handle. * @param family Must be {@code AF_INET} * @param type Either SOCK_DGRAM or SOCK_STREAM * @param protocol Either IPPROTO_UDP or IPPROTO_TCP * @return */ sock_handle_t socket_create(uint8_t family, uint8_t type, uint8_t protocol, uint16_t port, network_interface_t nif) { if (family!=AF_INET || !((type==SOCK_DGRAM && protocol==IPPROTO_UDP) || (type==SOCK_STREAM && protocol==IPPROTO_TCP))) return SOCKET_INVALID; sock_handle_t result = SOCKET_INVALID; socket_t* socket = new socket_t(); if (socket) { wiced_result_t wiced_result; socket->set_type((protocol==IPPROTO_UDP ? socket_t::UDP : socket_t::TCP)); if (protocol==IPPROTO_TCP) { wiced_result = wiced_tcp_create_socket(tcp(socket), wiced_wlan_interface(nif)); } else { wiced_result = wiced_udp_create_socket(udp(socket), port, wiced_wlan_interface(nif)); } if (wiced_result!=WICED_SUCCESS) { socket->set_type(socket_t::NONE); delete socket; result = as_sock_result(wiced_result); } else { SocketListLock lock(list_for(socket)); add_socket(socket); result = as_sock_result(socket); } } return result; } /** * Send data to a socket. * @param sd The socket handle to send data to. * @param buffer The data to send * @param len The number of bytes to send * @return */ sock_result_t socket_send(sock_handle_t sd, const void* buffer, socklen_t len) { return socket_send_ex(sd, buffer, len, 0, SOCKET_WAIT_FOREVER, nullptr); } sock_result_t socket_send_ex(sock_handle_t sd, const void* buffer, socklen_t len, uint32_t flags, system_tick_t timeout, void* reserved) { sock_result_t result = SOCKET_INVALID; socket_t* socket = from_handle(sd); uint16_t bytes_sent = 0; if (is_open(socket)) { wiced_result_t wiced_result = WICED_TCPIP_INVALID_SOCKET; if (is_tcp(socket)) { wiced_tcp_send_flags_t wiced_flags = timeout == 0 ? WICED_TCP_SEND_FLAG_NONBLOCK : WICED_TCP_SEND_FLAG_NONE; bytes_sent = (uint16_t)len; wiced_result = wiced_tcp_send_buffer_ex(tcp(socket), buffer, &bytes_sent, wiced_flags, timeout); } else if (is_client(socket)) { tcp_server_client_t* server_client = client(socket); size_t written = 0; wiced_result = server_client->write(buffer, len, &written, flags, timeout); bytes_sent = (uint16_t)written; } if (!wiced_result) DEBUG("Write %d bytes to socket %d result=%d", (int)len, (int)sd, wiced_result); result = wiced_result ? as_sock_result(wiced_result) : bytes_sent; } return result; } sock_result_t socket_sendto(sock_handle_t sd, const void* buffer, socklen_t len, uint32_t flags, sockaddr_t* addr, socklen_t addr_size) { socket_t* socket = from_handle(sd); wiced_result_t result = WICED_INVALID_SOCKET; if (is_open(socket) && is_udp(socket)) { SOCKADDR_TO_PORT_AND_IPADDR(addr, addr_data, port, ip_addr); uint16_t available = 0; wiced_packet_t* packet = NULL; uint8_t* data; if ((result=wiced_packet_create_udp(udp(socket), len, &packet, &data, &available))==WICED_SUCCESS) { size_t size = std::min(available, uint16_t(len)); memcpy(data, buffer, size); /* Set the end of the data portion */ wiced_packet_set_data_end(packet, (uint8_t*) data + size); result = wiced_udp_send(udp(socket), &ip_addr, port, packet); len = size; } } // return negative value on error, or length if successful. return result ? -result : len; } sock_result_t socket_receivefrom(sock_handle_t sd, void* buffer, socklen_t bufLen, uint32_t flags, sockaddr_t* addr, socklen_t* addrsize) { socket_t* socket = from_handle(sd); volatile wiced_result_t result = WICED_INVALID_SOCKET; uint16_t read_len = 0; if (is_open(socket) && is_udp(socket)) { wiced_packet_t* packet = NULL; // UDP receive timeout changed to 0 sec so as not to block if ((result=wiced_udp_receive(udp(socket), &packet, WICED_NO_WAIT))==WICED_SUCCESS) { wiced_ip_address_t wiced_ip_addr; uint16_t port; if ((result=wiced_udp_packet_get_info(packet, &wiced_ip_addr, &port))==WICED_SUCCESS) { uint32_t ipv4 = GET_IPV4_ADDRESS(wiced_ip_addr); addr->sa_data[0] = (port>>8) & 0xFF; addr->sa_data[1] = port & 0xFF; addr->sa_data[2] = (ipv4 >> 24) & 0xFF; addr->sa_data[3] = (ipv4 >> 16) & 0xFF; addr->sa_data[4] = (ipv4 >> 8) & 0xFF; addr->sa_data[5] = ipv4 & 0xFF; result=read_packet(packet, (uint8_t*)buffer, bufLen, &read_len); } wiced_packet_delete(packet); } } return result!=WICED_SUCCESS && result!=WICED_TIMEOUT ? as_sock_result(result) : sock_result_t(read_len); } sock_handle_t socket_handle_invalid() { return SOCKET_INVALID; } sock_result_t socket_join_multicast(const HAL_IPAddress *address, network_interface_t nif, socket_multicast_info_t * /*reserved*/) { wiced_ip_address_t multicast_address; SET_IPV4_ADDRESS(multicast_address, address->ipv4); return as_sock_result(wiced_multicast_join(wiced_wlan_interface(nif), &multicast_address)); } sock_result_t socket_leave_multicast(const HAL_IPAddress *address, network_interface_t nif, socket_multicast_info_t * /*reserved*/) { wiced_ip_address_t multicast_address; SET_IPV4_ADDRESS(multicast_address, address->ipv4); return as_sock_result(wiced_multicast_leave(wiced_wlan_interface(nif), &multicast_address)); } /* WICED extension */ wiced_result_t wiced_last_error( wiced_tcp_socket_t* socket) { wiced_assert("Bad args", (socket != NULL)); if ( socket->conn_handler == NULL ) { return WICED_NOT_CONNECTED; } else { return LWIP_TO_WICED_ERR( netconn_err(socket->conn_handler) ); } } sock_result_t socket_peer(sock_handle_t sd, sock_peer_t* peer, void* reserved) { tcp_server_client_t* c = client(from_handle(sd)); sock_result_t result = WICED_INVALID_SOCKET; if (c && peer) { wiced_tcp_socket_t* wiced_sock = c->get_socket(); wiced_ip_address_t ip; result = wiced_tcp_server_peer( wiced_sock, &ip, &peer->port); if (result==WICED_SUCCESS) { peer->address.ipv4 = GET_IPV4_ADDRESS(ip); } } return result; }
lgpl-3.0
dotnetwiz/KalikoCMS.Core
KalikoCMS.Engine/Core/Collections/SortDirection.cs
823
#region License and copyright notice /* * Kaliko Content Management System * * Copyright (c) Fredrik Schultz * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * http://www.gnu.org/licenses/lgpl-3.0.html */ #endregion namespace KalikoCMS.Core.Collections { public enum SortDirection { Ascending = 0, Descending = 1 } }
lgpl-3.0
yugangw-msft/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/ConnectionMonitorsStartOperation.cs
2599
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.ResourceManager.Network { /// <summary> Starts the specified connection monitor. </summary> public partial class ConnectionMonitorsStartOperation : Operation<Response>, IOperationSource<Response> { private readonly ArmOperationHelpers<Response> _operation; internal ConnectionMonitorsStartOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<Response>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "ConnectionMonitorsStartOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override Response Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); Response IOperationSource<Response>.CreateResult(Response response, CancellationToken cancellationToken) { return response; } async ValueTask<Response> IOperationSource<Response>.CreateResultAsync(Response response, CancellationToken cancellationToken) { return await new ValueTask<Response>(response).ConfigureAwait(false); } } }
apache-2.0
haoyanjun21/jstorm
jstorm-core/src/main/java/storm/trident/operation/impl/ConsumerExecutor.java
1422
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 storm.trident.operation.impl; import storm.trident.operation.BaseOperation; import storm.trident.operation.Consumer; import storm.trident.operation.Function; import storm.trident.operation.TridentCollector; import storm.trident.tuple.TridentTuple; public class ConsumerExecutor extends BaseOperation implements Function { private final Consumer consumer; public ConsumerExecutor(Consumer consumer) { this.consumer = consumer; } @Override public void execute(TridentTuple tuple, TridentCollector collector) { consumer.accept(tuple); collector.emit(tuple); } }
apache-2.0
vishh/heapster-1
Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/replication_controllers_test.go
4548
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package client import ( "testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/labels" ) func getRCResourceName() string { return "replicationcontrollers" } func TestListControllers(t *testing.T) { ns := api.NamespaceAll c := &testClient{ Request: testRequest{ Method: "GET", Path: testapi.ResourcePath(getRCResourceName(), ns, ""), }, Response: Response{StatusCode: 200, Body: &api.ReplicationControllerList{ Items: []api.ReplicationController{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, Spec: api.ReplicationControllerSpec{ Replicas: 2, Template: &api.PodTemplateSpec{}, }, }, }, }, }, } receivedControllerList, err := c.Setup().ReplicationControllers(ns).List(labels.Everything()) c.Validate(t, receivedControllerList, err) } func TestGetController(t *testing.T) { ns := api.NamespaceDefault c := &testClient{ Request: testRequest{Method: "GET", Path: testapi.ResourcePath(getRCResourceName(), ns, "foo"), Query: buildQueryValues(ns, nil)}, Response: Response{ StatusCode: 200, Body: &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, Spec: api.ReplicationControllerSpec{ Replicas: 2, Template: &api.PodTemplateSpec{}, }, }, }, } receivedController, err := c.Setup().ReplicationControllers(ns).Get("foo") c.Validate(t, receivedController, err) } func TestGetControllerWithNoName(t *testing.T) { ns := api.NamespaceDefault c := &testClient{Error: true} receivedPod, err := c.Setup().ReplicationControllers(ns).Get("") if (err != nil) && (err.Error() != nameRequiredError) { t.Errorf("Expected error: %v, but got %v", nameRequiredError, err) } c.Validate(t, receivedPod, err) } func TestUpdateController(t *testing.T) { ns := api.NamespaceDefault requestController := &api.ReplicationController{ ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, } c := &testClient{ Request: testRequest{Method: "PUT", Path: testapi.ResourcePath(getRCResourceName(), ns, "foo"), Query: buildQueryValues(ns, nil)}, Response: Response{ StatusCode: 200, Body: &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, Spec: api.ReplicationControllerSpec{ Replicas: 2, Template: &api.PodTemplateSpec{}, }, }, }, } receivedController, err := c.Setup().ReplicationControllers(ns).Update(requestController) c.Validate(t, receivedController, err) } func TestDeleteController(t *testing.T) { ns := api.NamespaceDefault c := &testClient{ Request: testRequest{Method: "DELETE", Path: testapi.ResourcePath(getRCResourceName(), ns, "foo"), Query: buildQueryValues(ns, nil)}, Response: Response{StatusCode: 200}, } err := c.Setup().ReplicationControllers(ns).Delete("foo") c.Validate(t, nil, err) } func TestCreateController(t *testing.T) { ns := api.NamespaceDefault requestController := &api.ReplicationController{ ObjectMeta: api.ObjectMeta{Name: "foo"}, } c := &testClient{ Request: testRequest{Method: "POST", Path: testapi.ResourcePath(getRCResourceName(), ns, ""), Body: requestController, Query: buildQueryValues(ns, nil)}, Response: Response{ StatusCode: 200, Body: &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, Spec: api.ReplicationControllerSpec{ Replicas: 2, Template: &api.PodTemplateSpec{}, }, }, }, } receivedController, err := c.Setup().ReplicationControllers(ns).Create(requestController) c.Validate(t, receivedController, err) }
apache-2.0
kylehogan/haas
haas/ext/obm/mock.py
1972
# Copyright 2015-2016 Massachusetts Open Cloud Contributors # # 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. """MockObm driver for implementing out of band management. """ from sqlalchemy import Column, String, Integer, ForeignKey import schema from haas.model import Obm from haas.dev_support import no_dry_run from os.path import join, dirname from haas.migrations import paths paths[__name__] = join(dirname(__file__), 'migrations', 'mock') class MockObm(Obm): id = Column(Integer, ForeignKey('obm.id'), primary_key=True) host = Column(String, nullable=False) user = Column(String, nullable=False) password = Column(String, nullable=False) api_name = 'http://schema.massopencloud.org/haas/v0/obm/mock' __mapper_args__ = { 'polymorphic_identity': api_name, } @staticmethod def validate(kwargs): schema.Schema({ 'type': MockObm.api_name, 'host': basestring, 'user': basestring, 'password': basestring, }).validate(kwargs) @no_dry_run def power_cycle(self): return @no_dry_run def power_off(self): return @no_dry_run def start_console(self): return @no_dry_run def stop_console(self): return @no_dry_run def delete_console(self): return @no_dry_run def get_console(self): return @no_dry_run def get_console_log_filename(self): return
apache-2.0
mdanielwork/intellij-community
plugins/hg4idea/resources/python/prompthooks.py
8337
#!/usr/bin/env python #Mercurial extension to robustly integrate prompts with other processes #Copyright (C) 2010-2011 Willem Verstraeten # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import socket import struct import urllib2 from mercurial import ui, util, error from mercurial.i18n import _ try: from mercurial.url import passwordmgr except: from mercurial.httprepo import passwordmgr def sendInt( client, number): length = struct.pack('>L', number) client.sendall( length ) def send( client, data ): if data is None: sendInt(client, 0) else: # we need to send data length and data together because it may produce read problems, see org.zmlx.hg4idea.execution.SocketServer client.sendall(struct.pack('>L', len(data)) + data) def receiveIntWithMessage(client, message): requiredLength = struct.calcsize('>L') buffer = '' while len(buffer)<requiredLength: chunk = client.recv(requiredLength-len(buffer)) if chunk == '': raise error.Abort( message ) buffer = buffer + chunk # struct.unpack always returns a tuple, even if that tuple only contains a single # item. The trailing , is to destructure the tuple into its first element. intToReturn, = struct.unpack('>L', buffer) return intToReturn def receiveInt(client): return receiveIntWithMessage(client, "could not get information from server") def receive( client ): receiveWithMessage(client, "could not get information from server") def receiveWithMessage( client, message ): length = receiveIntWithMessage(client, message) buffer = '' while len(buffer) < length : chunk = client.recv(length - len(buffer)) if chunk == '': raise error.Abort( message) buffer = buffer+chunk return buffer # decorator to cleanly monkey patch methods in mercurial def monkeypatch_method(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def sendchoicestoidea(ui, msg, choices, default): port = int(ui.config( 'hg4ideaprompt', 'port', None, True)) if not port: raise error.Abort("No port was specified") if (type(choices) is int) and (type(msg) is str): # since Mercurial 2.7 the promptchoice method doesn't accept 'choices' as parameter, so we need to parse them from msg # see ui.py -> promptchoice(self, prompt, default=0) parts = msg.split('$$') msg = parts[0].rstrip(' ') choices = [p.strip(' ') for p in parts[1:]] numOfChoices = len(choices) if not numOfChoices: return default client = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) try: client.connect( ('127.0.0.1', port) ) send( client, msg ) sendInt( client, numOfChoices ) for choice in choices: send( client, choice ) sendInt( client, default ) answer = receiveInt( client ) if answer == -1: raise error.Abort("User cancelled") else: return answer except: raise # determine which method to monkey patch : # in Mercurial 1.4 the prompt method was renamed to promptchoice if getattr(ui.ui, 'promptchoice', None): @monkeypatch_method(ui.ui) def promptchoice(self, msg, choices=None, default=0): return sendchoicestoidea(self, msg, choices, default) else: @monkeypatch_method(ui.ui) def prompt(self, msg, choices=None, default="y"): resps = [s[s.index('&')+1].lower() for s in choices] defaultIndex = resps.index( default ) responseIndex = sendchoicestoidea( self, msg, choices, defaultIndex) return resps[responseIndex] original_warn = ui.ui.warn @monkeypatch_method(ui.ui) def warn(self, *msg): original_warn(self, *msg) hg4ideaWarnConfig = self.config('hg4ideawarn', 'port', None, True) if hg4ideaWarnConfig is None: return port = int(hg4ideaWarnConfig) if not port: raise error.Abort("No port was specified") self.debug( "hg4idea prompt server waiting on port %s" % port ) client = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) self.debug( "connecting ..." ) client.connect( ('127.0.0.1', port) ) self.debug( "connected, sending data ..." ) sendInt( client, len(msg) ) for message in msg: send( client, message ) def retrieve_pass_from_server(ui, uri,path, proposed_user): port = int(ui.config('hg4ideapass', 'port', None, True)) if port is None: raise error.Abort("No port was specified") client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ui.debug("connecting ...") client.connect(('127.0.0.1', port)) ui.debug("connected, sending data ...") send(client, "getpass") send(client, uri) send(client, path) send(client, proposed_user) user = receiveWithMessage(client, "http authorization required") password = receiveWithMessage(client, "http authorization required") return user, password original_retrievepass=passwordmgr.find_user_password @monkeypatch_method(passwordmgr) def find_user_password(self, realm, authuri): try: return original_retrievepass(self, realm, authuri) except error.Abort: # In mercurial 1.8 the readauthtoken method was replaced with # the readauthforuri method, which has different semantics if getattr(self, 'readauthtoken', None): def read_hgrc_authtoken(ui, authuri): return self.readauthtoken(authuri) else: def read_hgrc_authtoken(ui, authuri): try: # since hg 1.8 from mercurial.url import readauthforuri except ImportError: # hg 1.9: readauthforuri moved to httpconnection from mercurial.httpconnection import readauthforuri from inspect import getargspec args, _, _, _ = getargspec(readauthforuri) if len(args) == 2: res = readauthforuri(self.ui, authuri) else: # since hg 1.9.2 readauthforuri accepts 3 required arguments instead of 2 res = readauthforuri(self.ui, authuri, "") if res: group, auth = res return auth else: return None # After mercurial 3.8.3 urllib2.HTTPPasswordmgrwithdefaultrealm.find_user_password etc were changed to appropriate methods # in util.urlreq module with slightly different semantics newMerc = False if isinstance(self, urllib2.HTTPPasswordMgrWithDefaultRealm) else True if newMerc: user, password = util.urlreq.httppasswordmgrwithdefaultrealm().find_user_password(realm, authuri) else: user, password = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(self, realm, authuri) if user is None: auth = read_hgrc_authtoken(self.ui, authuri) if auth: user = auth.get("username") pmWithRealm = util.urlreq.httppasswordmgrwithdefaultrealm() if newMerc else self reduced_uri, path = pmWithRealm.reduce_uri(authuri, False) retrievedPass = retrieve_pass_from_server(self.ui, reduced_uri, path, user) if retrievedPass is None: raise error.Abort(_('http authorization required')) user, passwd = retrievedPass pmWithRealm.add_password(realm, authuri, user, passwd) return retrievedPass
apache-2.0
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/di/ServiceBuilderModule.java
606
package fr.free.nrw.commons.di; import dagger.Module; import dagger.android.ContributesAndroidInjector; import fr.free.nrw.commons.auth.WikiAccountAuthenticatorService; /** * This Class Represents the Module for dependency injection (using dagger) * so, if a developer needs to add a new Service to the commons app * then that must be mentioned here to inject the dependencies */ @Module @SuppressWarnings({"WeakerAccess", "unused"}) public abstract class ServiceBuilderModule { @ContributesAndroidInjector abstract WikiAccountAuthenticatorService bindWikiAccountAuthenticatorService(); }
apache-2.0
withinsoft/znc
modules/autoattach.cpp
7836
/* * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details. * * 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. */ #include <znc/Chan.h> #include <znc/Modules.h> using std::vector; class CAttachMatch { public: CAttachMatch(CModule *pModule, const CString& sChannels, const CString& sSearch, const CString& sHostmasks, bool bNegated) { m_pModule = pModule; m_sChannelWildcard = sChannels; m_sSearchWildcard = sSearch; m_sHostmaskWildcard = sHostmasks; m_bNegated = bNegated; if (m_sChannelWildcard.empty()) m_sChannelWildcard = "*"; if (m_sSearchWildcard.empty()) m_sSearchWildcard = "*"; if (m_sHostmaskWildcard.empty()) m_sHostmaskWildcard = "*!*@*"; } bool IsMatch(const CString& sChan, const CString& sHost, const CString& sMessage) const { if (!sHost.WildCmp(m_sHostmaskWildcard)) return false; if (!sChan.WildCmp(m_sChannelWildcard)) return false; if (!sMessage.WildCmp(m_pModule->ExpandString(m_sSearchWildcard))) return false; return true; } bool IsNegated() const { return m_bNegated; } const CString& GetHostMask() const { return m_sHostmaskWildcard; } const CString& GetSearch() const { return m_sSearchWildcard; } const CString& GetChans() const { return m_sChannelWildcard; } CString ToString() { CString sRes; if (m_bNegated) sRes += "!"; sRes += m_sChannelWildcard; sRes += " "; sRes += m_sSearchWildcard; sRes += " "; sRes += m_sHostmaskWildcard; return sRes; } private: bool m_bNegated; CModule *m_pModule; CString m_sChannelWildcard; CString m_sSearchWildcard; CString m_sHostmaskWildcard; }; class CChanAttach : public CModule { public: typedef vector<CAttachMatch> VAttachMatch; typedef VAttachMatch::iterator VAttachIter; private: void HandleAdd(const CString& sLine) { CString sMsg = sLine.Token(1, true); bool bHelp = false; bool bNegated = sMsg.TrimPrefix("!"); CString sChan = sMsg.Token(0); CString sSearch = sMsg.Token(1); CString sHost = sMsg.Token(2); if (sChan.empty()) { bHelp = true; } else if (Add(bNegated, sChan, sSearch, sHost)) { PutModule("Added to list"); } else { PutModule(sLine.Token(1, true) + " is already added"); bHelp = true; } if (bHelp) { PutModule("Usage: Add [!]<#chan> <search> <host>"); PutModule("Wildcards are allowed"); } } void HandleDel(const CString& sLine) { CString sMsg = sLine.Token(1, true); bool bNegated = sMsg.TrimPrefix("!"); CString sChan = sMsg.Token(0); CString sSearch = sMsg.Token(1); CString sHost = sMsg.Token(2); if (Del(bNegated, sChan, sSearch, sHost)) { PutModule("Removed " + sChan + " from list"); } else { PutModule("Usage: Del [!]<#chan> <search> <host>"); } } void HandleList(const CString& sLine) { CTable Table; Table.AddColumn("Neg"); Table.AddColumn("Chan"); Table.AddColumn("Search"); Table.AddColumn("Host"); VAttachIter it = m_vMatches.begin(); for (; it != m_vMatches.end(); ++it) { Table.AddRow(); Table.SetCell("Neg", it->IsNegated() ? "!" : ""); Table.SetCell("Chan", it->GetChans()); Table.SetCell("Search", it->GetSearch()); Table.SetCell("Host", it->GetHostMask()); } if (Table.size()) { PutModule(Table); } else { PutModule("You have no entries."); } } public: MODCONSTRUCTOR(CChanAttach) { AddHelpCommand(); AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CChanAttach::HandleAdd), "[!]<#chan> <search> <host>", "Add an entry, use !#chan to negate and * for wildcards"); AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CChanAttach::HandleDel), "[!]<#chan> <search> <host>", "Remove an entry, needs to be an exact match"); AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CChanAttach::HandleList), "", "List all entries"); } virtual ~CChanAttach() { } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { VCString vsChans; sArgs.Split(" ", vsChans, false); for (VCString::const_iterator it = vsChans.begin(); it != vsChans.end(); ++it) { CString sAdd = *it; bool bNegated = sAdd.TrimPrefix("!"); CString sChan = sAdd.Token(0); CString sSearch = sAdd.Token(1); CString sHost = sAdd.Token(2, true); if (!Add(bNegated, sChan, sSearch, sHost)) { PutModule("Unable to add [" + *it + "]"); } } // Load our saved settings, ignore errors MCString::iterator it; for (it = BeginNV(); it != EndNV(); ++it) { CString sAdd = it->first; bool bNegated = sAdd.TrimPrefix("!"); CString sChan = sAdd.Token(0); CString sSearch = sAdd.Token(1); CString sHost = sAdd.Token(2, true); Add(bNegated, sChan, sSearch, sHost); } return true; } void TryAttach(const CNick& Nick, CChan& Channel, CString& Message) { const CString& sChan = Channel.GetName(); const CString& sHost = Nick.GetHostMask(); const CString& sMessage = Message; VAttachIter it; if (!Channel.IsDetached()) return; // Any negated match? for (it = m_vMatches.begin(); it != m_vMatches.end(); ++it) { if (it->IsNegated() && it->IsMatch(sChan, sHost, sMessage)) return; } // Now check for a positive match for (it = m_vMatches.begin(); it != m_vMatches.end(); ++it) { if (!it->IsNegated() && it->IsMatch(sChan, sHost, sMessage)) { Channel.JoinUser(); return; } } } virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { TryAttach(Nick, Channel, sMessage); return CONTINUE; } virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { TryAttach(Nick, Channel, sMessage); return CONTINUE; } virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { TryAttach(Nick, Channel, sMessage); return CONTINUE; } VAttachIter FindEntry(const CString& sChan, const CString& sSearch, const CString& sHost) { VAttachIter it = m_vMatches.begin(); for (; it != m_vMatches.end(); ++it) { if (sHost.empty() || it->GetHostMask() != sHost) continue; if (sSearch.empty() || it->GetSearch() != sSearch) continue; if (sChan.empty() || it->GetChans() != sChan) continue; return it; } return m_vMatches.end(); } bool Add(bool bNegated, const CString& sChan, const CString& sSearch, const CString& sHost) { CAttachMatch attach(this, sChan, sSearch, sHost, bNegated); // Check for duplicates VAttachIter it = m_vMatches.begin(); for (; it != m_vMatches.end(); ++it) { if (it->GetHostMask() == attach.GetHostMask() && it->GetChans() == attach.GetChans() && it->GetSearch() == attach.GetSearch()) return false; } m_vMatches.push_back(attach); // Also save it for next module load SetNV(attach.ToString(), ""); return true; } bool Del(bool bNegated, const CString& sChan, const CString& sSearch, const CString& sHost) { VAttachIter it = FindEntry(sChan, sSearch, sHost); if (it == m_vMatches.end() || it->IsNegated() != bNegated) return false; DelNV(it->ToString()); m_vMatches.erase(it); return true; } private: VAttachMatch m_vMatches; }; template<> void TModInfo<CChanAttach>(CModInfo& Info) { Info.SetWikiPage("autoattach"); Info.SetHasArgs(true); Info.SetArgsHelpText("List of channel masks and channel masks with ! before them."); } USERMODULEDEFS(CChanAttach, "Reattaches you to channels on activity.")
apache-2.0
Xperia-Nicki/android_platform_sony_nicki
external/webkit/Source/WebCore/css/CSSParser.cpp
253030
/* * Copyright (C) 2003 Lars Knoll (knoll@kde.org) * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com> * Copyright (C) 2008 Eric Seidel <eric@webkit.org> * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "CSSParser.h" #include "CSSBorderImageValue.h" #include "CSSCanvasValue.h" #include "CSSCharsetRule.h" #include "CSSCursorImageValue.h" #include "CSSFontFaceRule.h" #include "CSSFontFaceSrcValue.h" #include "CSSGradientValue.h" #include "CSSImageValue.h" #include "CSSImportRule.h" #include "CSSInheritedValue.h" #include "CSSInitialValue.h" #include "CSSLineBoxContainValue.h" #include "CSSMediaRule.h" #include "CSSMutableStyleDeclaration.h" #include "CSSPageRule.h" #include "CSSPrimitiveValue.h" #include "CSSPrimitiveValueCache.h" #include "CSSProperty.h" #include "CSSPropertyNames.h" #include "CSSPropertySourceData.h" #include "CSSQuirkPrimitiveValue.h" #include "CSSReflectValue.h" #include "CSSRuleList.h" #include "CSSSelector.h" #include "CSSStyleRule.h" #include "CSSStyleSheet.h" #include "CSSTimingFunctionValue.h" #include "CSSUnicodeRangeValue.h" #include "CSSValueKeywords.h" #include "CSSValueList.h" #include "Counter.h" #include "Document.h" #include "FloatConversion.h" #include "FontFamilyValue.h" #include "FontValue.h" #include "HTMLParserIdioms.h" #include "HashTools.h" #include "MediaList.h" #include "MediaQueryExp.h" #include "Page.h" #include "Pair.h" #include "Rect.h" #include "RenderTheme.h" #include "ShadowValue.h" #include "WebKitCSSKeyframeRule.h" #include "WebKitCSSKeyframesRule.h" #include "WebKitCSSTransformValue.h" #include <limits.h> #include <wtf/HexNumber.h> #include <wtf/dtoa.h> #include <wtf/text/StringBuffer.h> #if ENABLE(DASHBOARD_SUPPORT) #include "DashboardRegion.h" #endif #define YYDEBUG 0 #if YYDEBUG > 0 extern int cssyydebug; #endif extern int cssyyparse(void* parser); using namespace std; using namespace WTF; namespace WebCore { static const unsigned INVALID_NUM_PARSED_PROPERTIES = UINT_MAX; static const double MAX_SCALE = 1000000; static bool equal(const CSSParserString& a, const char* b) { for (int i = 0; i < a.length; ++i) { if (!b[i]) return false; if (a.characters[i] != b[i]) return false; } return !b[a.length]; } static bool equalIgnoringCase(const CSSParserString& a, const char* b) { for (int i = 0; i < a.length; ++i) { if (!b[i]) return false; ASSERT(!isASCIIUpper(b[i])); if (toASCIILower(a.characters[i]) != b[i]) return false; } return !b[a.length]; } static bool hasPrefix(const char* string, unsigned length, const char* prefix) { for (unsigned i = 0; i < length; ++i) { if (!prefix[i]) return true; if (string[i] != prefix[i]) return false; } return false; } CSSParser::CSSParser(bool strictParsing) : m_strict(strictParsing) , m_important(false) , m_id(0) , m_styleSheet(0) , m_valueList(0) , m_parsedProperties(static_cast<CSSProperty**>(fastMalloc(32 * sizeof(CSSProperty*)))) , m_numParsedProperties(0) , m_maxParsedProperties(32) , m_numParsedPropertiesBeforeMarginBox(INVALID_NUM_PARSED_PROPERTIES) , m_inParseShorthand(0) , m_currentShorthand(0) , m_implicitShorthand(false) , m_hasFontFaceOnlyValues(false) , m_hadSyntacticallyValidCSSRule(false) , m_defaultNamespace(starAtom) , m_inStyleRuleOrDeclaration(false) , m_selectorListRange(0, 0) , m_ruleBodyRange(0, 0) , m_propertyRange(UINT_MAX, UINT_MAX) , m_ruleRangeMap(0) , m_currentRuleData(0) , m_data(0) , yy_start(1) , m_lineNumber(0) , m_lastSelectorLineNumber(0) , m_allowImportRules(true) , m_allowNamespaceDeclarations(true) { #if YYDEBUG > 0 cssyydebug = 1; #endif CSSPropertySourceData::init(); } CSSParser::~CSSParser() { clearProperties(); fastFree(m_parsedProperties); delete m_valueList; fastFree(m_data); fastDeleteAllValues(m_floatingSelectors); deleteAllValues(m_floatingSelectorVectors); deleteAllValues(m_floatingValueLists); deleteAllValues(m_floatingFunctions); } void CSSParserString::lower() { // FIXME: If we need Unicode lowercasing here, then we probably want the real kind // that can potentially change the length of the string rather than the character // by character kind. If we don't need Unicode lowercasing, it would be good to // simplify this function. if (charactersAreAllASCII(characters, length)) { // Fast case for all-ASCII. for (int i = 0; i < length; i++) characters[i] = toASCIILower(characters[i]); } else { for (int i = 0; i < length; i++) characters[i] = Unicode::toLower(characters[i]); } } void CSSParser::setupParser(const char* prefix, const String& string, const char* suffix) { int length = string.length() + strlen(prefix) + strlen(suffix) + 2; fastFree(m_data); m_data = static_cast<UChar*>(fastMalloc(length * sizeof(UChar))); for (unsigned i = 0; i < strlen(prefix); i++) m_data[i] = prefix[i]; memcpy(m_data + strlen(prefix), string.characters(), string.length() * sizeof(UChar)); unsigned start = strlen(prefix) + string.length(); unsigned end = start + strlen(suffix); for (unsigned i = start; i < end; i++) m_data[i] = suffix[i - start]; m_data[length - 1] = 0; m_data[length - 2] = 0; yy_hold_char = 0; yyleng = 0; yytext = yy_c_buf_p = m_data; yy_hold_char = *yy_c_buf_p; resetRuleBodyMarks(); } void CSSParser::parseSheet(CSSStyleSheet* sheet, const String& string, int startLineNumber, StyleRuleRangeMap* ruleRangeMap) { setStyleSheet(sheet); m_defaultNamespace = starAtom; // Reset the default namespace. m_ruleRangeMap = ruleRangeMap; if (ruleRangeMap) { m_currentRuleData = CSSRuleSourceData::create(); m_currentRuleData->styleSourceData = CSSStyleSourceData::create(); } m_lineNumber = startLineNumber; setupParser("", string, ""); cssyyparse(this); m_ruleRangeMap = 0; m_currentRuleData = 0; m_rule = 0; } PassRefPtr<CSSRule> CSSParser::parseRule(CSSStyleSheet* sheet, const String& string) { setStyleSheet(sheet); m_allowNamespaceDeclarations = false; setupParser("@-webkit-rule{", string, "} "); cssyyparse(this); return m_rule.release(); } PassRefPtr<CSSRule> CSSParser::parseKeyframeRule(CSSStyleSheet *sheet, const String &string) { setStyleSheet(sheet); setupParser("@-webkit-keyframe-rule{ ", string, "} "); cssyyparse(this); return m_keyframe.release(); } static inline bool isColorPropertyID(int propertyId) { switch (propertyId) { case CSSPropertyColor: case CSSPropertyBackgroundColor: case CSSPropertyBorderBottomColor: case CSSPropertyBorderLeftColor: case CSSPropertyBorderRightColor: case CSSPropertyBorderTopColor: case CSSPropertyOutlineColor: case CSSPropertyTextLineThroughColor: case CSSPropertyTextOverlineColor: case CSSPropertyTextUnderlineColor: case CSSPropertyWebkitBorderAfterColor: case CSSPropertyWebkitBorderBeforeColor: case CSSPropertyWebkitBorderEndColor: case CSSPropertyWebkitBorderStartColor: case CSSPropertyWebkitColumnRuleColor: case CSSPropertyWebkitTextEmphasisColor: case CSSPropertyWebkitTextFillColor: case CSSPropertyWebkitTextStrokeColor: return true; default: return false; } } static bool parseColorValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict) { if (!string.length()) return false; if (!isColorPropertyID(propertyId)) return false; CSSParserString cssString; cssString.characters = const_cast<UChar*>(string.characters()); cssString.length = string.length(); int valueID = cssValueKeywordID(cssString); bool validPrimitive = false; if (valueID == CSSValueWebkitText) validPrimitive = true; else if (valueID == CSSValueCurrentcolor) validPrimitive = true; else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu || (valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText && !strict)) { validPrimitive = true; } CSSStyleSheet* stylesheet = static_cast<CSSStyleSheet*>(declaration->stylesheet()); if (!stylesheet || !stylesheet->document()) return false; if (validPrimitive) { CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createIdentifierValue(valueID), important); declaration->addParsedProperty(property); return true; } RGBA32 color; if (!CSSParser::parseColor(string, color, strict && string[0] != '#')) return false; CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createColorValue(color), important); declaration->addParsedProperty(property); return true; } static inline bool isSimpleLengthPropertyID(int propertyId, bool& acceptsNegativeNumbers) { switch (propertyId) { case CSSPropertyFontSize: case CSSPropertyHeight: case CSSPropertyWidth: case CSSPropertyMinHeight: case CSSPropertyMinWidth: case CSSPropertyPaddingBottom: case CSSPropertyPaddingLeft: case CSSPropertyPaddingRight: case CSSPropertyPaddingTop: case CSSPropertyWebkitLogicalWidth: case CSSPropertyWebkitLogicalHeight: case CSSPropertyWebkitMinLogicalWidth: case CSSPropertyWebkitMinLogicalHeight: case CSSPropertyWebkitPaddingAfter: case CSSPropertyWebkitPaddingBefore: case CSSPropertyWebkitPaddingEnd: case CSSPropertyWebkitPaddingStart: acceptsNegativeNumbers = false; return true; case CSSPropertyBottom: case CSSPropertyLeft: case CSSPropertyMarginBottom: case CSSPropertyMarginLeft: case CSSPropertyMarginRight: case CSSPropertyMarginTop: case CSSPropertyRight: case CSSPropertyTextIndent: case CSSPropertyTop: case CSSPropertyWebkitMarginAfter: case CSSPropertyWebkitMarginBefore: case CSSPropertyWebkitMarginEnd: case CSSPropertyWebkitMarginStart: acceptsNegativeNumbers = true; return true; default: return false; } } static bool parseSimpleLengthValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict) { const UChar* characters = string.characters(); unsigned length = string.length(); if (!characters || !length) return false; bool acceptsNegativeNumbers; if (!isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers)) return false; CSSPrimitiveValue::UnitTypes unit = CSSPrimitiveValue::CSS_NUMBER; if (length > 2 && characters[length - 2] == 'p' && characters[length - 1] == 'x') { length -= 2; unit = CSSPrimitiveValue::CSS_PX; } else if (length > 1 && characters[length - 1] == '%') { length -= 1; unit = CSSPrimitiveValue::CSS_PERCENTAGE; } // We rely on charactersToDouble for validation as well. The function // will set "ok" to "false" if the entire passed-in character range does // not represent a double. bool ok; double number = charactersToDouble(characters, length, &ok); if (!ok) return false; if (unit == CSSPrimitiveValue::CSS_NUMBER) { if (number && strict) return false; unit = CSSPrimitiveValue::CSS_PX; } if (number < 0 && !acceptsNegativeNumbers) return false; CSSStyleSheet* stylesheet = static_cast<CSSStyleSheet*>(declaration->stylesheet()); if (!stylesheet || !stylesheet->document()) return false; CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createValue(number, unit), important); declaration->addParsedProperty(property); return true; } bool CSSParser::parseValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict) { if (parseSimpleLengthValue(declaration, propertyId, string, important, strict)) return true; if (parseColorValue(declaration, propertyId, string, important, strict)) return true; CSSParser parser(strict); return parser.parseValue(declaration, propertyId, string, important); } bool CSSParser::parseValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important) { ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet()); setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet())); setupParser("@-webkit-value{", string, "} "); m_id = propertyId; m_important = important; cssyyparse(this); m_rule = 0; bool ok = false; if (m_hasFontFaceOnlyValues) deleteFontFaceOnlyValues(); if (m_numParsedProperties) { ok = true; declaration->addParsedProperties(m_parsedProperties, m_numParsedProperties); clearProperties(); } return ok; } // color will only be changed when string contains a valid css color, making it // possible to set up a default color. bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict) { // First try creating a color specified by name, rgba(), rgb() or "#" syntax. if (parseColor(string, color, strict)) return true; CSSParser parser(true); RefPtr<CSSMutableStyleDeclaration> dummyStyleDeclaration = CSSMutableStyleDeclaration::create(); // Now try to create a color from rgba() syntax. if (!parser.parseColor(dummyStyleDeclaration.get(), string)) return false; CSSValue* value = parser.m_parsedProperties[0]->value(); if (value->cssValueType() != CSSValue::CSS_PRIMITIVE_VALUE) return false; CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value); if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_RGBCOLOR) return false; color = primitiveValue->getRGBA32Value(); return true; } bool CSSParser::parseColor(CSSMutableStyleDeclaration* declaration, const String& string) { ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet()); setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet())); setupParser("@-webkit-decls{color:", string, "} "); cssyyparse(this); m_rule = 0; return (m_numParsedProperties && m_parsedProperties[0]->m_id == CSSPropertyColor); } bool CSSParser::parseSystemColor(RGBA32& color, const String& string, Document* document) { if (!document || !document->page()) return false; CSSParserString cssColor; cssColor.characters = const_cast<UChar*>(string.characters()); cssColor.length = string.length(); int id = cssValueKeywordID(cssColor); if (id <= 0) return false; color = document->page()->theme()->systemColor(id).rgb(); return true; } void CSSParser::parseSelector(const String& string, Document* doc, CSSSelectorList& selectorList) { RefPtr<CSSStyleSheet> dummyStyleSheet = CSSStyleSheet::create(doc); setStyleSheet(dummyStyleSheet.get()); m_selectorListForParseSelector = &selectorList; setupParser("@-webkit-selector{", string, "}"); cssyyparse(this); m_selectorListForParseSelector = 0; // The style sheet will be deleted right away, so it won't outlive the document. ASSERT(dummyStyleSheet->hasOneRef()); } bool CSSParser::parseDeclaration(CSSMutableStyleDeclaration* declaration, const String& string, RefPtr<CSSStyleSourceData>* styleSourceData) { // Length of the "@-webkit-decls{" prefix. static const unsigned prefixLength = 15; ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet()); setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet())); if (styleSourceData) { m_currentRuleData = CSSRuleSourceData::create(); m_currentRuleData->styleSourceData = CSSStyleSourceData::create(); m_inStyleRuleOrDeclaration = true; } setupParser("@-webkit-decls{", string, "} "); cssyyparse(this); m_rule = 0; bool ok = false; if (m_hasFontFaceOnlyValues) deleteFontFaceOnlyValues(); if (m_numParsedProperties) { ok = true; declaration->addParsedProperties(m_parsedProperties, m_numParsedProperties); clearProperties(); } if (m_currentRuleData) { m_currentRuleData->styleSourceData->styleBodyRange.start = 0; m_currentRuleData->styleSourceData->styleBodyRange.end = string.length(); for (Vector<CSSPropertySourceData>::iterator it = m_currentRuleData->styleSourceData->propertyData.begin(), endIt = m_currentRuleData->styleSourceData->propertyData.end(); it != endIt; ++it) { (*it).range.start -= prefixLength; (*it).range.end -= prefixLength; } } if (styleSourceData) { *styleSourceData = m_currentRuleData->styleSourceData.release(); m_currentRuleData = 0; m_inStyleRuleOrDeclaration = false; } return ok; } bool CSSParser::parseMediaQuery(MediaList* queries, const String& string) { if (string.isEmpty()) return true; ASSERT(!m_mediaQuery); // can't use { because tokenizer state switches from mediaquery to initial state when it sees { token. // instead insert one " " (which is WHITESPACE in CSSGrammar.y) setupParser("@-webkit-mediaquery ", string, "} "); cssyyparse(this); bool ok = false; if (m_mediaQuery) { ok = true; queries->appendMediaQuery(m_mediaQuery.release()); } return ok; } void CSSParser::addProperty(int propId, PassRefPtr<CSSValue> value, bool important) { OwnPtr<CSSProperty> prop(new CSSProperty(propId, value, important, m_currentShorthand, m_implicitShorthand)); if (m_numParsedProperties >= m_maxParsedProperties) { m_maxParsedProperties += 32; if (m_maxParsedProperties > UINT_MAX / sizeof(CSSProperty*)) return; m_parsedProperties = static_cast<CSSProperty**>(fastRealloc(m_parsedProperties, m_maxParsedProperties * sizeof(CSSProperty*))); } m_parsedProperties[m_numParsedProperties++] = prop.leakPtr(); } void CSSParser::rollbackLastProperties(int num) { ASSERT(num >= 0); ASSERT(m_numParsedProperties >= static_cast<unsigned>(num)); for (int i = 0; i < num; ++i) delete m_parsedProperties[--m_numParsedProperties]; } void CSSParser::clearProperties() { for (unsigned i = 0; i < m_numParsedProperties; i++) delete m_parsedProperties[i]; m_numParsedProperties = 0; m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES; m_hasFontFaceOnlyValues = false; } void CSSParser::setStyleSheet(CSSStyleSheet* styleSheet) { m_styleSheet = styleSheet; m_primitiveValueCache = document() ? document()->cssPrimitiveValueCache() : CSSPrimitiveValueCache::create(); } Document* CSSParser::document() const { StyleBase* root = m_styleSheet; while (root && root->parent()) root = root->parent(); if (!root) return 0; if (!root->isCSSStyleSheet()) return 0; return static_cast<CSSStyleSheet*>(root)->document(); } bool CSSParser::validUnit(CSSParserValue* value, Units unitflags, bool strict) { bool b = false; switch (value->unit) { case CSSPrimitiveValue::CSS_NUMBER: b = (unitflags & FNumber); if (!b && ((unitflags & (FLength | FAngle | FTime)) && (value->fValue == 0 || !strict))) { value->unit = (unitflags & FLength) ? CSSPrimitiveValue::CSS_PX : ((unitflags & FAngle) ? CSSPrimitiveValue::CSS_DEG : CSSPrimitiveValue::CSS_MS); b = true; } if (!b && (unitflags & FInteger) && value->isInt) b = true; break; case CSSPrimitiveValue::CSS_PERCENTAGE: b = (unitflags & FPercent); break; case CSSParserValue::Q_EMS: case CSSPrimitiveValue::CSS_EMS: case CSSPrimitiveValue::CSS_REMS: case CSSPrimitiveValue::CSS_EXS: case CSSPrimitiveValue::CSS_PX: case CSSPrimitiveValue::CSS_CM: case CSSPrimitiveValue::CSS_MM: case CSSPrimitiveValue::CSS_IN: case CSSPrimitiveValue::CSS_PT: case CSSPrimitiveValue::CSS_PC: b = (unitflags & FLength); break; case CSSPrimitiveValue::CSS_MS: case CSSPrimitiveValue::CSS_S: b = (unitflags & FTime); break; case CSSPrimitiveValue::CSS_DEG: case CSSPrimitiveValue::CSS_RAD: case CSSPrimitiveValue::CSS_GRAD: case CSSPrimitiveValue::CSS_TURN: b = (unitflags & FAngle); break; case CSSPrimitiveValue::CSS_HZ: case CSSPrimitiveValue::CSS_KHZ: case CSSPrimitiveValue::CSS_DIMENSION: default: break; } if (b && unitflags & FNonNeg && value->fValue < 0) b = false; return b; } static int unitFromString(CSSParserValue* value) { if (value->unit != CSSPrimitiveValue::CSS_IDENT || value->id) return 0; if (equal(value->string, "em")) return CSSPrimitiveValue::CSS_EMS; if (equal(value->string, "rem")) return CSSPrimitiveValue::CSS_REMS; if (equal(value->string, "ex")) return CSSPrimitiveValue::CSS_EXS; if (equal(value->string, "px")) return CSSPrimitiveValue::CSS_PX; if (equal(value->string, "cm")) return CSSPrimitiveValue::CSS_CM; if (equal(value->string, "mm")) return CSSPrimitiveValue::CSS_MM; if (equal(value->string, "in")) return CSSPrimitiveValue::CSS_IN; if (equal(value->string, "pt")) return CSSPrimitiveValue::CSS_PT; if (equal(value->string, "pc")) return CSSPrimitiveValue::CSS_PC; if (equal(value->string, "deg")) return CSSPrimitiveValue::CSS_DEG; if (equal(value->string, "rad")) return CSSPrimitiveValue::CSS_RAD; if (equal(value->string, "grad")) return CSSPrimitiveValue::CSS_GRAD; if (equal(value->string, "turn")) return CSSPrimitiveValue::CSS_TURN; if (equal(value->string, "ms")) return CSSPrimitiveValue::CSS_MS; if (equal(value->string, "s")) return CSSPrimitiveValue::CSS_S; if (equal(value->string, "Hz")) return CSSPrimitiveValue::CSS_HZ; if (equal(value->string, "kHz")) return CSSPrimitiveValue::CSS_KHZ; return 0; } void CSSParser::checkForOrphanedUnits() { if (m_strict || inShorthand()) return; // The purpose of this code is to implement the WinIE quirk that allows unit types to be separated from their numeric values // by whitespace, so e.g., width: 20 px instead of width:20px. This is invalid CSS, so we don't do this in strict mode. CSSParserValue* numericVal = 0; unsigned size = m_valueList->size(); for (unsigned i = 0; i < size; i++) { CSSParserValue* value = m_valueList->valueAt(i); if (numericVal) { // Change the unit type of the numeric val to match. int unit = unitFromString(value); if (unit) { numericVal->unit = unit; numericVal = 0; // Now delete the bogus unit value. m_valueList->deleteValueAt(i); i--; // We're safe even though |i| is unsigned, since we only hit this code if we had a previous numeric value (so |i| is always > 0 here). size--; continue; } } numericVal = (value->unit == CSSPrimitiveValue::CSS_NUMBER) ? value : 0; } } bool CSSParser::parseValue(int propId, bool important) { if (!m_valueList) return false; CSSParserValue* value = m_valueList->current(); if (!value) return false; int id = value->id; // In quirks mode, we will look for units that have been incorrectly separated from the number they belong to // by a space. We go ahead and associate the unit with the number even though it is invalid CSS. checkForOrphanedUnits(); int num = inShorthand() ? 1 : m_valueList->size(); if (id == CSSValueInherit) { if (num != 1) return false; addProperty(propId, CSSInheritedValue::create(), important); return true; } else if (id == CSSValueInitial) { if (num != 1) return false; addProperty(propId, CSSInitialValue::createExplicit(), important); return true; } bool validPrimitive = false; RefPtr<CSSValue> parsedValue; switch (static_cast<CSSPropertyID>(propId)) { /* The comment to the left defines all valid value of this properties as defined * in CSS 2, Appendix F. Property index */ /* All the CSS properties are not supported by the renderer at the moment. * Note that all the CSS2 Aural properties are only checked, if CSS_AURAL is defined * (see parseAuralValues). As we don't support them at all this seems reasonable. */ case CSSPropertySize: // <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ] return parseSize(propId, important); case CSSPropertyQuotes: // [<string> <string>]+ | none | inherit if (id) validPrimitive = true; else return parseQuotes(propId, important); break; case CSSPropertyUnicodeBidi: // normal | embed | bidi-override | isolate | inherit if (id == CSSValueNormal || id == CSSValueEmbed || id == CSSValueBidiOverride || id == CSSValueWebkitIsolate) validPrimitive = true; break; case CSSPropertyPosition: // static | relative | absolute | fixed | inherit if (id == CSSValueStatic || id == CSSValueRelative || id == CSSValueAbsolute || id == CSSValueFixed) validPrimitive = true; break; case CSSPropertyPageBreakAfter: // auto | always | avoid | left | right | inherit case CSSPropertyPageBreakBefore: case CSSPropertyWebkitColumnBreakAfter: case CSSPropertyWebkitColumnBreakBefore: if (id == CSSValueAuto || id == CSSValueAlways || id == CSSValueAvoid || id == CSSValueLeft || id == CSSValueRight) validPrimitive = true; break; case CSSPropertyPageBreakInside: // avoid | auto | inherit case CSSPropertyWebkitColumnBreakInside: if (id == CSSValueAuto || id == CSSValueAvoid) validPrimitive = true; break; case CSSPropertyEmptyCells: // show | hide | inherit if (id == CSSValueShow || id == CSSValueHide) validPrimitive = true; break; case CSSPropertyContent: // [ <string> | <uri> | <counter> | attr(X) | open-quote | // close-quote | no-open-quote | no-close-quote ]+ | inherit return parseContent(propId, important); case CSSPropertyWhiteSpace: // normal | pre | nowrap | inherit if (id == CSSValueNormal || id == CSSValuePre || id == CSSValuePreWrap || id == CSSValuePreLine || id == CSSValueNowrap) validPrimitive = true; break; case CSSPropertyClip: // <shape> | auto | inherit if (id == CSSValueAuto) validPrimitive = true; else if (value->unit == CSSParserValue::Function) return parseShape(propId, important); break; /* Start of supported CSS properties with validation. This is needed for parseShorthand to work * correctly and allows optimization in WebCore::applyRule(..) */ case CSSPropertyCaptionSide: // top | bottom | left | right | inherit if (id == CSSValueLeft || id == CSSValueRight || id == CSSValueTop || id == CSSValueBottom) validPrimitive = true; break; case CSSPropertyBorderCollapse: // collapse | separate | inherit if (id == CSSValueCollapse || id == CSSValueSeparate) validPrimitive = true; break; case CSSPropertyVisibility: // visible | hidden | collapse | inherit if (id == CSSValueVisible || id == CSSValueHidden || id == CSSValueCollapse) validPrimitive = true; break; case CSSPropertyOverflow: { ShorthandScope scope(this, propId); if (num != 1 || !parseValue(CSSPropertyOverflowX, important)) return false; CSSValue* value = m_parsedProperties[m_numParsedProperties - 1]->value(); addProperty(CSSPropertyOverflowY, value, important); return true; } case CSSPropertyOverflowX: case CSSPropertyOverflowY: // visible | hidden | scroll | auto | marquee | overlay | inherit if (id == CSSValueVisible || id == CSSValueHidden || id == CSSValueScroll || id == CSSValueAuto || id == CSSValueOverlay || id == CSSValueWebkitMarquee) validPrimitive = true; break; case CSSPropertyListStylePosition: // inside | outside | inherit if (id == CSSValueInside || id == CSSValueOutside) validPrimitive = true; break; case CSSPropertyListStyleType: // See section CSS_PROP_LIST_STYLE_TYPE of file CSSValueKeywords.in // for the list of supported list-style-types. if ((id >= CSSValueDisc && id <= CSSValueKatakanaIroha) || id == CSSValueNone) validPrimitive = true; break; case CSSPropertyDisplay: // inline | block | list-item | run-in | inline-block | table | // inline-table | table-row-group | table-header-group | table-footer-group | table-row | // table-column-group | table-column | table-cell | table-caption | box | inline-box | none | inherit #if ENABLE(WCSS) if ((id >= CSSValueInline && id <= CSSValueWapMarquee) || id == CSSValueNone) #else if ((id >= CSSValueInline && id <= CSSValueWebkitInlineBox) || id == CSSValueNone) #endif validPrimitive = true; break; case CSSPropertyDirection: // ltr | rtl | inherit if (id == CSSValueLtr || id == CSSValueRtl) validPrimitive = true; break; case CSSPropertyTextTransform: // capitalize | uppercase | lowercase | none | inherit if ((id >= CSSValueCapitalize && id <= CSSValueLowercase) || id == CSSValueNone) validPrimitive = true; break; case CSSPropertyFloat: // left | right | none | inherit + center for buggy CSS if (id == CSSValueLeft || id == CSSValueRight || id == CSSValueNone || id == CSSValueCenter) validPrimitive = true; break; case CSSPropertyClear: // none | left | right | both | inherit if (id == CSSValueNone || id == CSSValueLeft || id == CSSValueRight|| id == CSSValueBoth) validPrimitive = true; break; case CSSPropertyTextAlign: // left | right | center | justify | webkit_left | webkit_right | webkit_center | webkit_match_parent | // start | end | <string> | inherit if ((id >= CSSValueWebkitAuto && id <= CSSValueWebkitMatchParent) || id == CSSValueStart || id == CSSValueEnd || value->unit == CSSPrimitiveValue::CSS_STRING) validPrimitive = true; break; case CSSPropertyOutlineStyle: // (<border-style> except hidden) | auto | inherit if (id == CSSValueAuto || id == CSSValueNone || (id >= CSSValueInset && id <= CSSValueDouble)) validPrimitive = true; break; case CSSPropertyBorderTopStyle: //// <border-style> | inherit case CSSPropertyBorderRightStyle: // Defined as: none | hidden | dotted | dashed | case CSSPropertyBorderBottomStyle: // solid | double | groove | ridge | inset | outset case CSSPropertyBorderLeftStyle: case CSSPropertyWebkitBorderStartStyle: case CSSPropertyWebkitBorderEndStyle: case CSSPropertyWebkitBorderBeforeStyle: case CSSPropertyWebkitBorderAfterStyle: case CSSPropertyWebkitColumnRuleStyle: if (id >= CSSValueNone && id <= CSSValueDouble) validPrimitive = true; break; case CSSPropertyFontWeight: // normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit return parseFontWeight(important); case CSSPropertyBorderSpacing: { const int properties[2] = { CSSPropertyWebkitBorderHorizontalSpacing, CSSPropertyWebkitBorderVerticalSpacing }; if (num == 1) { ShorthandScope scope(this, CSSPropertyBorderSpacing); if (!parseValue(properties[0], important)) return false; CSSValue* value = m_parsedProperties[m_numParsedProperties-1]->value(); addProperty(properties[1], value, important); return true; } else if (num == 2) { ShorthandScope scope(this, CSSPropertyBorderSpacing); if (!parseValue(properties[0], important) || !parseValue(properties[1], important)) return false; return true; } return false; } case CSSPropertyWebkitBorderHorizontalSpacing: case CSSPropertyWebkitBorderVerticalSpacing: validPrimitive = validUnit(value, FLength | FNonNeg, m_strict); break; case CSSPropertyOutlineColor: // <color> | invert | inherit // Outline color has "invert" as additional keyword. // Also, we want to allow the special focus color even in strict parsing mode. if (id == CSSValueInvert || id == CSSValueWebkitFocusRingColor) { validPrimitive = true; break; } /* nobreak */ case CSSPropertyBackgroundColor: // <color> | inherit case CSSPropertyBorderTopColor: // <color> | inherit case CSSPropertyBorderRightColor: case CSSPropertyBorderBottomColor: case CSSPropertyBorderLeftColor: case CSSPropertyWebkitBorderStartColor: case CSSPropertyWebkitBorderEndColor: case CSSPropertyWebkitBorderBeforeColor: case CSSPropertyWebkitBorderAfterColor: case CSSPropertyColor: // <color> | inherit case CSSPropertyTextLineThroughColor: // CSS3 text decoration colors case CSSPropertyTextUnderlineColor: case CSSPropertyTextOverlineColor: case CSSPropertyWebkitColumnRuleColor: case CSSPropertyWebkitTextEmphasisColor: case CSSPropertyWebkitTextFillColor: case CSSPropertyWebkitTextStrokeColor: if (id == CSSValueWebkitText) validPrimitive = true; // Always allow this, even when strict parsing is on, // since we use this in our UA sheets. else if (id == CSSValueCurrentcolor) validPrimitive = true; else if ((id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu || (id >= CSSValueWebkitFocusRingColor && id < CSSValueWebkitText && !m_strict)) { validPrimitive = true; } else { parsedValue = parseColor(); if (parsedValue) m_valueList->next(); } break; case CSSPropertyCursor: { // [<uri>,]* [ auto | crosshair | default | pointer | progress | move | e-resize | ne-resize | // nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | ew-resize | // ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | text | wait | help | // vertical-text | cell | context-menu | alias | copy | no-drop | not-allowed | -webkit-zoom-in // -webkit-zoom-out | all-scroll | -webkit-grab | -webkit-grabbing ] ] | inherit RefPtr<CSSValueList> list; while (value && value->unit == CSSPrimitiveValue::CSS_URI) { if (!list) list = CSSValueList::createCommaSeparated(); String uri = value->string; Vector<int> coords; value = m_valueList->next(); while (value && value->unit == CSSPrimitiveValue::CSS_NUMBER) { coords.append(int(value->fValue)); value = m_valueList->next(); } IntPoint hotSpot(-1, -1); int nrcoords = coords.size(); if (nrcoords > 0 && nrcoords != 2) return false; if (nrcoords == 2) hotSpot = IntPoint(coords[0], coords[1]); if (!uri.isNull() && m_styleSheet) { // FIXME: The completeURL call should be done when using the CSSCursorImageValue, // not when creating it. list->append(CSSCursorImageValue::create(m_styleSheet->completeURL(uri), hotSpot)); } if ((m_strict && !value) || (value && !(value->unit == CSSParserValue::Operator && value->iValue == ','))) return false; value = m_valueList->next(); // comma } if (list) { if (!value) { // no value after url list (MSIE 5 compatibility) if (list->length() != 1) return false; } else if (!m_strict && value->id == CSSValueHand) // MSIE 5 compatibility :/ list->append(primitiveValueCache()->createIdentifierValue(CSSValuePointer)); else if (value && ((value->id >= CSSValueAuto && value->id <= CSSValueWebkitGrabbing) || value->id == CSSValueCopy || value->id == CSSValueNone)) list->append(primitiveValueCache()->createIdentifierValue(value->id)); m_valueList->next(); parsedValue = list.release(); break; } id = value->id; if (!m_strict && value->id == CSSValueHand) { // MSIE 5 compatibility :/ id = CSSValuePointer; validPrimitive = true; } else if ((value->id >= CSSValueAuto && value->id <= CSSValueWebkitGrabbing) || value->id == CSSValueCopy || value->id == CSSValueNone) validPrimitive = true; break; } case CSSPropertyBackgroundAttachment: case CSSPropertyBackgroundClip: case CSSPropertyWebkitBackgroundClip: case CSSPropertyWebkitBackgroundComposite: case CSSPropertyBackgroundImage: case CSSPropertyBackgroundOrigin: case CSSPropertyWebkitBackgroundOrigin: case CSSPropertyBackgroundPosition: case CSSPropertyBackgroundPositionX: case CSSPropertyBackgroundPositionY: case CSSPropertyBackgroundSize: case CSSPropertyWebkitBackgroundSize: case CSSPropertyBackgroundRepeat: case CSSPropertyBackgroundRepeatX: case CSSPropertyBackgroundRepeatY: case CSSPropertyWebkitMaskAttachment: case CSSPropertyWebkitMaskClip: case CSSPropertyWebkitMaskComposite: case CSSPropertyWebkitMaskImage: case CSSPropertyWebkitMaskOrigin: case CSSPropertyWebkitMaskPosition: case CSSPropertyWebkitMaskPositionX: case CSSPropertyWebkitMaskPositionY: case CSSPropertyWebkitMaskSize: case CSSPropertyWebkitMaskRepeat: case CSSPropertyWebkitMaskRepeatX: case CSSPropertyWebkitMaskRepeatY: { RefPtr<CSSValue> val1; RefPtr<CSSValue> val2; int propId1, propId2; bool result = false; if (parseFillProperty(propId, propId1, propId2, val1, val2)) { OwnPtr<ShorthandScope> shorthandScope; if (propId == CSSPropertyBackgroundPosition || propId == CSSPropertyBackgroundRepeat || propId == CSSPropertyWebkitMaskPosition || propId == CSSPropertyWebkitMaskRepeat) { shorthandScope.set(new ShorthandScope(this, propId)); } addProperty(propId1, val1.release(), important); if (val2) addProperty(propId2, val2.release(), important); result = true; } m_implicitShorthand = false; return result; } case CSSPropertyListStyleImage: // <uri> | none | inherit if (id == CSSValueNone) { parsedValue = CSSImageValue::create(); m_valueList->next(); } else if (value->unit == CSSPrimitiveValue::CSS_URI) { if (m_styleSheet) { // FIXME: The completeURL call should be done when using the CSSImageValue, // not when creating it. parsedValue = CSSImageValue::create(m_styleSheet->completeURL(value->string)); m_valueList->next(); } } else if (isGeneratedImageValue(value)) { if (parseGeneratedImage(parsedValue)) m_valueList->next(); else return false; } break; case CSSPropertyWebkitTextStrokeWidth: case CSSPropertyOutlineWidth: // <border-width> | inherit case CSSPropertyBorderTopWidth: //// <border-width> | inherit case CSSPropertyBorderRightWidth: // Which is defined as case CSSPropertyBorderBottomWidth: // thin | medium | thick | <length> case CSSPropertyBorderLeftWidth: case CSSPropertyWebkitBorderStartWidth: case CSSPropertyWebkitBorderEndWidth: case CSSPropertyWebkitBorderBeforeWidth: case CSSPropertyWebkitBorderAfterWidth: case CSSPropertyWebkitColumnRuleWidth: if (id == CSSValueThin || id == CSSValueMedium || id == CSSValueThick) validPrimitive = true; else validPrimitive = validUnit(value, FLength | FNonNeg, m_strict); break; case CSSPropertyLetterSpacing: // normal | <length> | inherit case CSSPropertyWordSpacing: // normal | <length> | inherit if (id == CSSValueNormal) validPrimitive = true; else validPrimitive = validUnit(value, FLength, m_strict); break; case CSSPropertyWordBreak: // normal | break-all | break-word (this is a custom extension) if (id == CSSValueNormal || id == CSSValueBreakAll || id == CSSValueBreakWord) validPrimitive = true; break; case CSSPropertyWordWrap: // normal | break-word if (id == CSSValueNormal || id == CSSValueBreakWord) validPrimitive = true; break; case CSSPropertySpeak: // none | normal | spell-out | digits | literal-punctuation | no-punctuation | inherit if (id == CSSValueNone || id == CSSValueNormal || id == CSSValueSpellOut || id == CSSValueDigits || id == CSSValueLiteralPunctuation || id == CSSValueNoPunctuation) validPrimitive = true; break; case CSSPropertyTextIndent: // <length> | <percentage> | inherit validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict)); break; case CSSPropertyPaddingTop: //// <padding-width> | inherit case CSSPropertyPaddingRight: // Which is defined as case CSSPropertyPaddingBottom: // <length> | <percentage> case CSSPropertyPaddingLeft: //// case CSSPropertyWebkitPaddingStart: case CSSPropertyWebkitPaddingEnd: case CSSPropertyWebkitPaddingBefore: case CSSPropertyWebkitPaddingAfter: validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict)); break; case CSSPropertyMaxHeight: // <length> | <percentage> | none | inherit case CSSPropertyMaxWidth: // <length> | <percentage> | none | inherit case CSSPropertyWebkitMaxLogicalWidth: case CSSPropertyWebkitMaxLogicalHeight: if (id == CSSValueNone || id == CSSValueIntrinsic || id == CSSValueMinIntrinsic) { validPrimitive = true; break; } /* nobreak */ case CSSPropertyMinHeight: // <length> | <percentage> | inherit case CSSPropertyMinWidth: // <length> | <percentage> | inherit case CSSPropertyWebkitMinLogicalWidth: case CSSPropertyWebkitMinLogicalHeight: if (id == CSSValueIntrinsic || id == CSSValueMinIntrinsic) validPrimitive = true; else validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict)); break; case CSSPropertyFontSize: // <absolute-size> | <relative-size> | <length> | <percentage> | inherit if (id >= CSSValueXxSmall && id <= CSSValueLarger) validPrimitive = true; else validPrimitive = (validUnit(value, FLength | FPercent | FNonNeg, m_strict)); break; case CSSPropertyFontStyle: // normal | italic | oblique | inherit return parseFontStyle(important); case CSSPropertyFontVariant: // normal | small-caps | inherit return parseFontVariant(important); case CSSPropertyVerticalAlign: // baseline | sub | super | top | text-top | middle | bottom | text-bottom | // <percentage> | <length> | inherit if (id >= CSSValueBaseline && id <= CSSValueWebkitBaselineMiddle) validPrimitive = true; else validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict)); break; case CSSPropertyHeight: // <length> | <percentage> | auto | inherit case CSSPropertyWidth: // <length> | <percentage> | auto | inherit case CSSPropertyWebkitLogicalWidth: case CSSPropertyWebkitLogicalHeight: if (id == CSSValueAuto || id == CSSValueIntrinsic || id == CSSValueMinIntrinsic) validPrimitive = true; else // ### handle multilength case where we allow relative units validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict)); break; case CSSPropertyBottom: // <length> | <percentage> | auto | inherit case CSSPropertyLeft: // <length> | <percentage> | auto | inherit case CSSPropertyRight: // <length> | <percentage> | auto | inherit case CSSPropertyTop: // <length> | <percentage> | auto | inherit case CSSPropertyMarginTop: //// <margin-width> | inherit case CSSPropertyMarginRight: // Which is defined as case CSSPropertyMarginBottom: // <length> | <percentage> | auto | inherit case CSSPropertyMarginLeft: //// case CSSPropertyWebkitMarginStart: case CSSPropertyWebkitMarginEnd: case CSSPropertyWebkitMarginBefore: case CSSPropertyWebkitMarginAfter: if (id == CSSValueAuto) validPrimitive = true; else validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict)); break; case CSSPropertyZIndex: // auto | <integer> | inherit if (id == CSSValueAuto) { validPrimitive = true; break; } /* nobreak */ case CSSPropertyOrphans: // <integer> | inherit case CSSPropertyWidows: // <integer> | inherit // ### not supported later on validPrimitive = (!id && validUnit(value, FInteger, false)); break; case CSSPropertyLineHeight: // normal | <number> | <length> | <percentage> | inherit if (id == CSSValueNormal) validPrimitive = true; else validPrimitive = (!id && validUnit(value, FNumber | FLength | FPercent | FNonNeg, m_strict)); break; case CSSPropertyCounterIncrement: // [ <identifier> <integer>? ]+ | none | inherit if (id != CSSValueNone) return parseCounter(propId, 1, important); validPrimitive = true; break; case CSSPropertyCounterReset: // [ <identifier> <integer>? ]+ | none | inherit if (id != CSSValueNone) return parseCounter(propId, 0, important); validPrimitive = true; break; case CSSPropertyFontFamily: // [[ <family-name> | <generic-family> ],]* [<family-name> | <generic-family>] | inherit { parsedValue = parseFontFamily(); break; } case CSSPropertyTextDecoration: case CSSPropertyWebkitTextDecorationsInEffect: // none | [ underline || overline || line-through || blink ] | inherit if (id == CSSValueNone) { validPrimitive = true; } else { RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated(); bool isValid = true; while (isValid && value) { switch (value->id) { case CSSValueBlink: break; case CSSValueUnderline: case CSSValueOverline: case CSSValueLineThrough: list->append(primitiveValueCache()->createIdentifierValue(value->id)); break; default: isValid = false; } value = m_valueList->next(); } if (list->length() && isValid) { parsedValue = list.release(); m_valueList->next(); } } break; case CSSPropertyZoom: // normal | reset | document | <number> | <percentage> | inherit if (id == CSSValueNormal || id == CSSValueReset || id == CSSValueDocument) validPrimitive = true; else validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, true)); break; case CSSPropertyTableLayout: // auto | fixed | inherit if (id == CSSValueAuto || id == CSSValueFixed) validPrimitive = true; break; case CSSPropertySrc: // Only used within @font-face, so cannot use inherit | initial or be !important. This is a list of urls or local references. return parseFontFaceSrc(); case CSSPropertyUnicodeRange: return parseFontFaceUnicodeRange(); /* CSS3 properties */ case CSSPropertyWebkitAppearance: if ((id >= CSSValueCheckbox && id <= CSSValueTextarea) || id == CSSValueNone) validPrimitive = true; break; case CSSPropertyWebkitBorderImage: case CSSPropertyWebkitMaskBoxImage: if (id == CSSValueNone) validPrimitive = true; else { RefPtr<CSSValue> result; if (parseBorderImage(propId, important, result)) { addProperty(propId, result, important); return true; } } break; case CSSPropertyBorderTopRightRadius: case CSSPropertyBorderTopLeftRadius: case CSSPropertyBorderBottomLeftRadius: case CSSPropertyBorderBottomRightRadius: { if (num != 1 && num != 2) return false; validPrimitive = validUnit(value, FLength | FPercent, m_strict); if (!validPrimitive) return false; RefPtr<CSSPrimitiveValue> parsedValue1 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); RefPtr<CSSPrimitiveValue> parsedValue2; if (num == 2) { value = m_valueList->next(); validPrimitive = validUnit(value, FLength | FPercent, m_strict); if (!validPrimitive) return false; parsedValue2 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); } else parsedValue2 = parsedValue1; RefPtr<Pair> pair = Pair::create(parsedValue1.release(), parsedValue2.release()); RefPtr<CSSPrimitiveValue> val = primitiveValueCache()->createValue(pair.release()); addProperty(propId, val.release(), important); return true; } case CSSPropertyBorderRadius: case CSSPropertyWebkitBorderRadius: return parseBorderRadius(propId, important); case CSSPropertyOutlineOffset: validPrimitive = validUnit(value, FLength | FPercent, m_strict); break; case CSSPropertyTextShadow: // CSS2 property, dropped in CSS2.1, back in CSS3, so treat as CSS3 case CSSPropertyBoxShadow: case CSSPropertyWebkitBoxShadow: if (id == CSSValueNone) validPrimitive = true; else return parseShadow(propId, important); break; case CSSPropertyWebkitBoxReflect: if (id == CSSValueNone) validPrimitive = true; else return parseReflect(propId, important); break; case CSSPropertyOpacity: validPrimitive = validUnit(value, FNumber, m_strict); break; case CSSPropertyWebkitBoxAlign: if (id == CSSValueStretch || id == CSSValueStart || id == CSSValueEnd || id == CSSValueCenter || id == CSSValueBaseline) validPrimitive = true; break; case CSSPropertyWebkitBoxDirection: if (id == CSSValueNormal || id == CSSValueReverse) validPrimitive = true; break; case CSSPropertyWebkitBoxLines: if (id == CSSValueSingle || id == CSSValueMultiple) validPrimitive = true; break; case CSSPropertyWebkitBoxOrient: if (id == CSSValueHorizontal || id == CSSValueVertical || id == CSSValueInlineAxis || id == CSSValueBlockAxis) validPrimitive = true; break; case CSSPropertyWebkitBoxPack: if (id == CSSValueStart || id == CSSValueEnd || id == CSSValueCenter || id == CSSValueJustify) validPrimitive = true; break; case CSSPropertyWebkitBoxFlex: validPrimitive = validUnit(value, FNumber, m_strict); break; case CSSPropertyWebkitBoxFlexGroup: case CSSPropertyWebkitBoxOrdinalGroup: validPrimitive = validUnit(value, FInteger | FNonNeg, true); break; case CSSPropertyBoxSizing: validPrimitive = id == CSSValueBorderBox || id == CSSValueContentBox; break; case CSSPropertyWebkitColorCorrection: validPrimitive = id == CSSValueSrgb || id == CSSValueDefault; break; case CSSPropertyWebkitMarquee: { const int properties[5] = { CSSPropertyWebkitMarqueeDirection, CSSPropertyWebkitMarqueeIncrement, CSSPropertyWebkitMarqueeRepetition, CSSPropertyWebkitMarqueeStyle, CSSPropertyWebkitMarqueeSpeed }; return parseShorthand(propId, properties, 5, important); } case CSSPropertyWebkitMarqueeDirection: if (id == CSSValueForwards || id == CSSValueBackwards || id == CSSValueAhead || id == CSSValueReverse || id == CSSValueLeft || id == CSSValueRight || id == CSSValueDown || id == CSSValueUp || id == CSSValueAuto) validPrimitive = true; break; case CSSPropertyWebkitMarqueeIncrement: if (id == CSSValueSmall || id == CSSValueLarge || id == CSSValueMedium) validPrimitive = true; else validPrimitive = validUnit(value, FLength | FPercent, m_strict); break; case CSSPropertyWebkitMarqueeStyle: if (id == CSSValueNone || id == CSSValueSlide || id == CSSValueScroll || id == CSSValueAlternate) validPrimitive = true; break; case CSSPropertyWebkitMarqueeRepetition: if (id == CSSValueInfinite) validPrimitive = true; else validPrimitive = validUnit(value, FInteger | FNonNeg, m_strict); break; case CSSPropertyWebkitMarqueeSpeed: if (id == CSSValueNormal || id == CSSValueSlow || id == CSSValueFast) validPrimitive = true; else validPrimitive = validUnit(value, FTime | FInteger | FNonNeg, m_strict); break; #if ENABLE(WCSS) case CSSPropertyWapMarqueeDir: if (id == CSSValueLtr || id == CSSValueRtl) validPrimitive = true; break; case CSSPropertyWapMarqueeStyle: if (id == CSSValueNone || id == CSSValueSlide || id == CSSValueScroll || id == CSSValueAlternate) validPrimitive = true; break; case CSSPropertyWapMarqueeLoop: if (id == CSSValueInfinite) validPrimitive = true; else validPrimitive = validUnit(value, FInteger | FNonNeg, m_strict); break; case CSSPropertyWapMarqueeSpeed: if (id == CSSValueNormal || id == CSSValueSlow || id == CSSValueFast) validPrimitive = true; else validPrimitive = validUnit(value, FTime | FInteger | FNonNeg, m_strict); break; #endif case CSSPropertyWebkitUserDrag: // auto | none | element if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueElement) validPrimitive = true; break; case CSSPropertyWebkitUserModify: // read-only | read-write if (id == CSSValueReadOnly || id == CSSValueReadWrite || id == CSSValueReadWritePlaintextOnly) validPrimitive = true; break; case CSSPropertyWebkitUserSelect: // auto | none | text if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueText) validPrimitive = true; break; case CSSPropertyTextOverflow: // clip | ellipsis if (id == CSSValueClip || id == CSSValueEllipsis) validPrimitive = true; break; case CSSPropertyWebkitTransform: if (id == CSSValueNone) validPrimitive = true; else { PassRefPtr<CSSValue> val = parseTransform(); if (val) { addProperty(propId, val, important); return true; } return false; } break; case CSSPropertyWebkitTransformOrigin: case CSSPropertyWebkitTransformOriginX: case CSSPropertyWebkitTransformOriginY: case CSSPropertyWebkitTransformOriginZ: { RefPtr<CSSValue> val1; RefPtr<CSSValue> val2; RefPtr<CSSValue> val3; int propId1, propId2, propId3; if (parseTransformOrigin(propId, propId1, propId2, propId3, val1, val2, val3)) { addProperty(propId1, val1.release(), important); if (val2) addProperty(propId2, val2.release(), important); if (val3) addProperty(propId3, val3.release(), important); return true; } return false; } case CSSPropertyWebkitTransformStyle: if (value->id == CSSValueFlat || value->id == CSSValuePreserve3d) validPrimitive = true; break; case CSSPropertyWebkitBackfaceVisibility: if (value->id == CSSValueVisible || value->id == CSSValueHidden) validPrimitive = true; break; case CSSPropertyWebkitPerspective: if (id == CSSValueNone) validPrimitive = true; else { // Accepting valueless numbers is a quirk of the -webkit prefixed version of the property. if (validUnit(value, FNumber | FLength | FNonNeg, m_strict)) { RefPtr<CSSValue> val = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); if (val) { addProperty(propId, val.release(), important); return true; } return false; } } break; case CSSPropertyWebkitPerspectiveOrigin: case CSSPropertyWebkitPerspectiveOriginX: case CSSPropertyWebkitPerspectiveOriginY: { RefPtr<CSSValue> val1; RefPtr<CSSValue> val2; int propId1, propId2; if (parsePerspectiveOrigin(propId, propId1, propId2, val1, val2)) { addProperty(propId1, val1.release(), important); if (val2) addProperty(propId2, val2.release(), important); return true; } return false; } case CSSPropertyWebkitAnimationDelay: case CSSPropertyWebkitAnimationDirection: case CSSPropertyWebkitAnimationDuration: case CSSPropertyWebkitAnimationFillMode: case CSSPropertyWebkitAnimationName: case CSSPropertyWebkitAnimationPlayState: case CSSPropertyWebkitAnimationIterationCount: case CSSPropertyWebkitAnimationTimingFunction: case CSSPropertyWebkitTransitionDelay: case CSSPropertyWebkitTransitionDuration: case CSSPropertyWebkitTransitionTimingFunction: case CSSPropertyWebkitTransitionProperty: { RefPtr<CSSValue> val; if (parseAnimationProperty(propId, val)) { addProperty(propId, val.release(), important); return true; } return false; } case CSSPropertyWebkitMarginCollapse: { const int properties[2] = { CSSPropertyWebkitMarginBeforeCollapse, CSSPropertyWebkitMarginAfterCollapse }; if (num == 1) { ShorthandScope scope(this, CSSPropertyWebkitMarginCollapse); if (!parseValue(properties[0], important)) return false; CSSValue* value = m_parsedProperties[m_numParsedProperties-1]->value(); addProperty(properties[1], value, important); return true; } else if (num == 2) { ShorthandScope scope(this, CSSPropertyWebkitMarginCollapse); if (!parseValue(properties[0], important) || !parseValue(properties[1], important)) return false; return true; } return false; } case CSSPropertyWebkitMarginBeforeCollapse: case CSSPropertyWebkitMarginAfterCollapse: case CSSPropertyWebkitMarginTopCollapse: case CSSPropertyWebkitMarginBottomCollapse: if (id == CSSValueCollapse || id == CSSValueSeparate || id == CSSValueDiscard) validPrimitive = true; break; case CSSPropertyTextLineThroughMode: case CSSPropertyTextOverlineMode: case CSSPropertyTextUnderlineMode: if (id == CSSValueContinuous || id == CSSValueSkipWhiteSpace) validPrimitive = true; break; case CSSPropertyTextLineThroughStyle: case CSSPropertyTextOverlineStyle: case CSSPropertyTextUnderlineStyle: if (id == CSSValueNone || id == CSSValueSolid || id == CSSValueDouble || id == CSSValueDashed || id == CSSValueDotDash || id == CSSValueDotDotDash || id == CSSValueWave) validPrimitive = true; break; case CSSPropertyTextRendering: // auto | optimizeSpeed | optimizeLegibility | geometricPrecision if (id == CSSValueAuto || id == CSSValueOptimizespeed || id == CSSValueOptimizelegibility || id == CSSValueGeometricprecision) validPrimitive = true; break; case CSSPropertyTextLineThroughWidth: case CSSPropertyTextOverlineWidth: case CSSPropertyTextUnderlineWidth: if (id == CSSValueAuto || id == CSSValueNormal || id == CSSValueThin || id == CSSValueMedium || id == CSSValueThick) validPrimitive = true; else validPrimitive = !id && validUnit(value, FNumber | FLength | FPercent, m_strict); break; case CSSPropertyResize: // none | both | horizontal | vertical | auto if (id == CSSValueNone || id == CSSValueBoth || id == CSSValueHorizontal || id == CSSValueVertical || id == CSSValueAuto) validPrimitive = true; break; case CSSPropertyWebkitColumnCount: if (id == CSSValueAuto) validPrimitive = true; else validPrimitive = !id && validUnit(value, FInteger | FNonNeg, false); break; case CSSPropertyWebkitColumnGap: // normal | <length> if (id == CSSValueNormal) validPrimitive = true; else validPrimitive = validUnit(value, FLength | FNonNeg, m_strict); break; case CSSPropertyWebkitColumnSpan: // all | 1 if (id == CSSValueAll) validPrimitive = true; else validPrimitive = validUnit(value, FNumber | FNonNeg, m_strict) && value->fValue == 1; break; case CSSPropertyWebkitColumnWidth: // auto | <length> if (id == CSSValueAuto) validPrimitive = true; else // Always parse this property in strict mode, since it would be ambiguous otherwise when used in the 'columns' shorthand property. validPrimitive = validUnit(value, FLength, true); break; case CSSPropertyPointerEvents: // none | visiblePainted | visibleFill | visibleStroke | visible | // painted | fill | stroke | auto | all | inherit if (id == CSSValueVisible || id == CSSValueNone || id == CSSValueAll || id == CSSValueAuto || (id >= CSSValueVisiblepainted && id <= CSSValueStroke)) validPrimitive = true; break; // End of CSS3 properties // Apple specific properties. These will never be standardized and are purely to // support custom WebKit-based Apple applications. case CSSPropertyWebkitLineClamp: // When specifying number of lines, don't allow 0 as a valid value // When specifying either type of unit, require non-negative integers validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, false)); break; case CSSPropertyWebkitTextSizeAdjust: if (id == CSSValueAuto || id == CSSValueNone) validPrimitive = true; break; case CSSPropertyWebkitRtlOrdering: if (id == CSSValueLogical || id == CSSValueVisual) validPrimitive = true; break; case CSSPropertyWebkitFontSizeDelta: // <length> validPrimitive = validUnit(value, FLength, m_strict); break; case CSSPropertyWebkitNbspMode: // normal | space if (id == CSSValueNormal || id == CSSValueSpace) validPrimitive = true; break; case CSSPropertyWebkitLineBreak: // normal | after-white-space if (id == CSSValueNormal || id == CSSValueAfterWhiteSpace) validPrimitive = true; break; case CSSPropertyWebkitMatchNearestMailBlockquoteColor: // normal | match if (id == CSSValueNormal || id == CSSValueMatch) validPrimitive = true; break; case CSSPropertyWebkitHighlight: if (id == CSSValueNone || value->unit == CSSPrimitiveValue::CSS_STRING) validPrimitive = true; break; case CSSPropertyWebkitHyphens: if (id == CSSValueNone || id == CSSValueManual || id == CSSValueAuto) validPrimitive = true; break; case CSSPropertyWebkitHyphenateCharacter: if (id == CSSValueAuto || value->unit == CSSPrimitiveValue::CSS_STRING) validPrimitive = true; break; case CSSPropertyWebkitHyphenateLimitBefore: case CSSPropertyWebkitHyphenateLimitAfter: if (id == CSSValueAuto || validUnit(value, FInteger | FNonNeg, true)) validPrimitive = true; break; case CSSPropertyWebkitLocale: if (id == CSSValueAuto || value->unit == CSSPrimitiveValue::CSS_STRING) validPrimitive = true; break; case CSSPropertyWebkitBorderFit: if (id == CSSValueBorder || id == CSSValueLines) validPrimitive = true; break; case CSSPropertyWebkitTextSecurity: // disc | circle | square | none | inherit if (id == CSSValueDisc || id == CSSValueCircle || id == CSSValueSquare|| id == CSSValueNone) validPrimitive = true; break; case CSSPropertyWebkitFontSmoothing: if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueAntialiased || id == CSSValueSubpixelAntialiased) validPrimitive = true; break; #if ENABLE(DASHBOARD_SUPPORT) case CSSPropertyWebkitDashboardRegion: // <dashboard-region> | <dashboard-region> if (value->unit == CSSParserValue::Function || id == CSSValueNone) return parseDashboardRegions(propId, important); break; #endif // End Apple-specific properties /* shorthand properties */ case CSSPropertyBackground: { // Position must come before color in this array because a plain old "0" is a legal color // in quirks mode but it's usually the X coordinate of a position. // FIXME: Add CSSPropertyBackgroundSize to the shorthand. const int properties[] = { CSSPropertyBackgroundImage, CSSPropertyBackgroundRepeat, CSSPropertyBackgroundAttachment, CSSPropertyBackgroundPosition, CSSPropertyBackgroundOrigin, CSSPropertyBackgroundClip, CSSPropertyBackgroundColor }; return parseFillShorthand(propId, properties, 7, important); } case CSSPropertyWebkitMask: { const int properties[] = { CSSPropertyWebkitMaskImage, CSSPropertyWebkitMaskRepeat, CSSPropertyWebkitMaskAttachment, CSSPropertyWebkitMaskPosition, CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskClip }; return parseFillShorthand(propId, properties, 6, important); } case CSSPropertyBorder: // [ 'border-width' || 'border-style' || <color> ] | inherit { const int properties[3] = { CSSPropertyBorderWidth, CSSPropertyBorderStyle, CSSPropertyBorderColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyBorderTop: // [ 'border-top-width' || 'border-style' || <color> ] | inherit { const int properties[3] = { CSSPropertyBorderTopWidth, CSSPropertyBorderTopStyle, CSSPropertyBorderTopColor}; return parseShorthand(propId, properties, 3, important); } case CSSPropertyBorderRight: // [ 'border-right-width' || 'border-style' || <color> ] | inherit { const int properties[3] = { CSSPropertyBorderRightWidth, CSSPropertyBorderRightStyle, CSSPropertyBorderRightColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyBorderBottom: // [ 'border-bottom-width' || 'border-style' || <color> ] | inherit { const int properties[3] = { CSSPropertyBorderBottomWidth, CSSPropertyBorderBottomStyle, CSSPropertyBorderBottomColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyBorderLeft: // [ 'border-left-width' || 'border-style' || <color> ] | inherit { const int properties[3] = { CSSPropertyBorderLeftWidth, CSSPropertyBorderLeftStyle, CSSPropertyBorderLeftColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitBorderStart: { const int properties[3] = { CSSPropertyWebkitBorderStartWidth, CSSPropertyWebkitBorderStartStyle, CSSPropertyWebkitBorderStartColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitBorderEnd: { const int properties[3] = { CSSPropertyWebkitBorderEndWidth, CSSPropertyWebkitBorderEndStyle, CSSPropertyWebkitBorderEndColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitBorderBefore: { const int properties[3] = { CSSPropertyWebkitBorderBeforeWidth, CSSPropertyWebkitBorderBeforeStyle, CSSPropertyWebkitBorderBeforeColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitBorderAfter: { const int properties[3] = { CSSPropertyWebkitBorderAfterWidth, CSSPropertyWebkitBorderAfterStyle, CSSPropertyWebkitBorderAfterColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyOutline: // [ 'outline-color' || 'outline-style' || 'outline-width' ] | inherit { const int properties[3] = { CSSPropertyOutlineWidth, CSSPropertyOutlineStyle, CSSPropertyOutlineColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyBorderColor: // <color>{1,4} | inherit { const int properties[4] = { CSSPropertyBorderTopColor, CSSPropertyBorderRightColor, CSSPropertyBorderBottomColor, CSSPropertyBorderLeftColor }; return parse4Values(propId, properties, important); } case CSSPropertyBorderWidth: // <border-width>{1,4} | inherit { const int properties[4] = { CSSPropertyBorderTopWidth, CSSPropertyBorderRightWidth, CSSPropertyBorderBottomWidth, CSSPropertyBorderLeftWidth }; return parse4Values(propId, properties, important); } case CSSPropertyBorderStyle: // <border-style>{1,4} | inherit { const int properties[4] = { CSSPropertyBorderTopStyle, CSSPropertyBorderRightStyle, CSSPropertyBorderBottomStyle, CSSPropertyBorderLeftStyle }; return parse4Values(propId, properties, important); } case CSSPropertyMargin: // <margin-width>{1,4} | inherit { const int properties[4] = { CSSPropertyMarginTop, CSSPropertyMarginRight, CSSPropertyMarginBottom, CSSPropertyMarginLeft }; return parse4Values(propId, properties, important); } case CSSPropertyPadding: // <padding-width>{1,4} | inherit { const int properties[4] = { CSSPropertyPaddingTop, CSSPropertyPaddingRight, CSSPropertyPaddingBottom, CSSPropertyPaddingLeft }; return parse4Values(propId, properties, important); } case CSSPropertyFont: // [ [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]? // 'font-family' ] | caption | icon | menu | message-box | small-caption | status-bar | inherit if (id >= CSSValueCaption && id <= CSSValueStatusBar) validPrimitive = true; else return parseFont(important); break; case CSSPropertyListStyle: { const int properties[3] = { CSSPropertyListStyleType, CSSPropertyListStylePosition, CSSPropertyListStyleImage }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitColumns: { const int properties[2] = { CSSPropertyWebkitColumnWidth, CSSPropertyWebkitColumnCount }; return parseShorthand(propId, properties, 2, important); } case CSSPropertyWebkitColumnRule: { const int properties[3] = { CSSPropertyWebkitColumnRuleWidth, CSSPropertyWebkitColumnRuleStyle, CSSPropertyWebkitColumnRuleColor }; return parseShorthand(propId, properties, 3, important); } case CSSPropertyWebkitTextStroke: { const int properties[2] = { CSSPropertyWebkitTextStrokeWidth, CSSPropertyWebkitTextStrokeColor }; return parseShorthand(propId, properties, 2, important); } case CSSPropertyWebkitAnimation: return parseAnimationShorthand(important); case CSSPropertyWebkitTransition: return parseTransitionShorthand(important); case CSSPropertyInvalid: return false; case CSSPropertyPage: return parsePage(propId, important); case CSSPropertyFontStretch: case CSSPropertyTextLineThrough: case CSSPropertyTextOverline: case CSSPropertyTextUnderline: return false; #if ENABLE(WCSS) case CSSPropertyWapInputFormat: validPrimitive = true; break; case CSSPropertyWapInputRequired: parsedValue = parseWCSSInputProperty(); break; #endif // CSS Text Layout Module Level 3: Vertical writing support case CSSPropertyWebkitWritingMode: if (id >= CSSValueHorizontalTb && id <= CSSValueHorizontalBt) validPrimitive = true; break; case CSSPropertyWebkitTextCombine: if (id == CSSValueNone || id == CSSValueHorizontal) validPrimitive = true; break; case CSSPropertyWebkitTextEmphasis: { const int properties[] = { CSSPropertyWebkitTextEmphasisStyle, CSSPropertyWebkitTextEmphasisColor }; return parseShorthand(propId, properties, WTF_ARRAY_LENGTH(properties), important); } case CSSPropertyWebkitTextEmphasisPosition: if (id == CSSValueOver || id == CSSValueUnder) validPrimitive = true; break; case CSSPropertyWebkitTextEmphasisStyle: return parseTextEmphasisStyle(important); case CSSPropertyWebkitTextOrientation: // FIXME: For now just support upright and vertical-right. if (id == CSSValueVerticalRight || id == CSSValueUpright) validPrimitive = true; break; case CSSPropertyWebkitLineBoxContain: if (id == CSSValueNone) validPrimitive = true; else return parseLineBoxContain(important); break; #ifdef ANDROID_CSS_TAP_HIGHLIGHT_COLOR case CSSPropertyWebkitTapHighlightColor: parsedValue = parseColor(); if (parsedValue) m_valueList->next(); break; #endif #if ENABLE(SVG) default: return parseSVGValue(propId, important); #endif } if (validPrimitive) { if (id != 0) parsedValue = primitiveValueCache()->createIdentifierValue(id); else if (value->unit == CSSPrimitiveValue::CSS_STRING) parsedValue = primitiveValueCache()->createValue(value->string, (CSSPrimitiveValue::UnitTypes) value->unit); else if (value->unit >= CSSPrimitiveValue::CSS_NUMBER && value->unit <= CSSPrimitiveValue::CSS_KHZ) parsedValue = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit); else if (value->unit >= CSSPrimitiveValue::CSS_TURN && value->unit <= CSSPrimitiveValue::CSS_REMS) parsedValue = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit); else if (value->unit >= CSSParserValue::Q_EMS) parsedValue = CSSQuirkPrimitiveValue::create(value->fValue, CSSPrimitiveValue::CSS_EMS); m_valueList->next(); } if (parsedValue) { if (!m_valueList->current() || inShorthand()) { addProperty(propId, parsedValue.release(), important); return true; } } return false; } #if ENABLE(WCSS) PassRefPtr<CSSValue> CSSParser::parseWCSSInputProperty() { RefPtr<CSSValue> parsedValue = 0; CSSParserValue* value = m_valueList->current(); String inputProperty; if (value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT) inputProperty = String(value->string); if (!inputProperty.isEmpty()) parsedValue = primitiveValueCache()->createValue(inputProperty, CSSPrimitiveValue::CSS_STRING); while (m_valueList->next()) { // pass all other values, if any. If we don't do this, // the parser will think that it's not done and won't process this property } return parsedValue; } #endif void CSSParser::addFillValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval) { if (lval) { if (lval->isValueList()) static_cast<CSSValueList*>(lval.get())->append(rval); else { PassRefPtr<CSSValue> oldlVal(lval.release()); PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated(); list->append(oldlVal); list->append(rval); lval = list; } } else lval = rval; } static bool parseBackgroundClip(CSSParserValue* parserValue, RefPtr<CSSValue>& cssValue, CSSPrimitiveValueCache* primitiveValueCache) { if (parserValue->id == CSSValueBorderBox || parserValue->id == CSSValuePaddingBox || parserValue->id == CSSValueContentBox || parserValue->id == CSSValueWebkitText) { cssValue = primitiveValueCache->createIdentifierValue(parserValue->id); return true; } return false; } const int cMaxFillProperties = 9; bool CSSParser::parseFillShorthand(int propId, const int* properties, int numProperties, bool important) { ASSERT(numProperties <= cMaxFillProperties); if (numProperties > cMaxFillProperties) return false; ShorthandScope scope(this, propId); bool parsedProperty[cMaxFillProperties] = { false }; RefPtr<CSSValue> values[cMaxFillProperties]; RefPtr<CSSValue> clipValue; RefPtr<CSSValue> positionYValue; RefPtr<CSSValue> repeatYValue; bool foundClip = false; int i; while (m_valueList->current()) { CSSParserValue* val = m_valueList->current(); if (val->unit == CSSParserValue::Operator && val->iValue == ',') { // We hit the end. Fill in all remaining values with the initial value. m_valueList->next(); for (i = 0; i < numProperties; ++i) { if (properties[i] == CSSPropertyBackgroundColor && parsedProperty[i]) // Color is not allowed except as the last item in a list for backgrounds. // Reject the entire property. return false; if (!parsedProperty[i] && properties[i] != CSSPropertyBackgroundColor) { addFillValue(values[i], CSSInitialValue::createImplicit()); if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition) addFillValue(positionYValue, CSSInitialValue::createImplicit()); if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat) addFillValue(repeatYValue, CSSInitialValue::createImplicit()); if ((properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) && !parsedProperty[i]) { // If background-origin wasn't present, then reset background-clip also. addFillValue(clipValue, CSSInitialValue::createImplicit()); } } parsedProperty[i] = false; } if (!m_valueList->current()) break; } bool found = false; for (i = 0; !found && i < numProperties; ++i) { if (!parsedProperty[i]) { RefPtr<CSSValue> val1; RefPtr<CSSValue> val2; int propId1, propId2; CSSParserValue* parserValue = m_valueList->current(); if (parseFillProperty(properties[i], propId1, propId2, val1, val2)) { parsedProperty[i] = found = true; addFillValue(values[i], val1.release()); if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition) addFillValue(positionYValue, val2.release()); if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat) addFillValue(repeatYValue, val2.release()); if (properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) { // Reparse the value as a clip, and see if we succeed. if (parseBackgroundClip(parserValue, val1, primitiveValueCache())) addFillValue(clipValue, val1.release()); // The property parsed successfully. else addFillValue(clipValue, CSSInitialValue::createImplicit()); // Some value was used for origin that is not supported by clip. Just reset clip instead. } if (properties[i] == CSSPropertyBackgroundClip || properties[i] == CSSPropertyWebkitMaskClip) { // Update clipValue addFillValue(clipValue, val1.release()); foundClip = true; } } } } // if we didn't find at least one match, this is an // invalid shorthand and we have to ignore it if (!found) return false; } // Fill in any remaining properties with the initial value. for (i = 0; i < numProperties; ++i) { if (!parsedProperty[i]) { addFillValue(values[i], CSSInitialValue::createImplicit()); if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition) addFillValue(positionYValue, CSSInitialValue::createImplicit()); if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat) addFillValue(repeatYValue, CSSInitialValue::createImplicit()); if ((properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) && !parsedProperty[i]) { // If background-origin wasn't present, then reset background-clip also. addFillValue(clipValue, CSSInitialValue::createImplicit()); } } } // Now add all of the properties we found. for (i = 0; i < numProperties; i++) { if (properties[i] == CSSPropertyBackgroundPosition) { addProperty(CSSPropertyBackgroundPositionX, values[i].release(), important); // it's OK to call positionYValue.release() since we only see CSSPropertyBackgroundPosition once addProperty(CSSPropertyBackgroundPositionY, positionYValue.release(), important); } else if (properties[i] == CSSPropertyWebkitMaskPosition) { addProperty(CSSPropertyWebkitMaskPositionX, values[i].release(), important); // it's OK to call positionYValue.release() since we only see CSSPropertyWebkitMaskPosition once addProperty(CSSPropertyWebkitMaskPositionY, positionYValue.release(), important); } else if (properties[i] == CSSPropertyBackgroundRepeat) { addProperty(CSSPropertyBackgroundRepeatX, values[i].release(), important); // it's OK to call repeatYValue.release() since we only see CSSPropertyBackgroundPosition once addProperty(CSSPropertyBackgroundRepeatY, repeatYValue.release(), important); } else if (properties[i] == CSSPropertyWebkitMaskRepeat) { addProperty(CSSPropertyWebkitMaskRepeatX, values[i].release(), important); // it's OK to call repeatYValue.release() since we only see CSSPropertyBackgroundPosition once addProperty(CSSPropertyWebkitMaskRepeatY, repeatYValue.release(), important); } else if ((properties[i] == CSSPropertyBackgroundClip || properties[i] == CSSPropertyWebkitMaskClip) && !foundClip) // Value is already set while updating origin continue; else addProperty(properties[i], values[i].release(), important); // Add in clip values when we hit the corresponding origin property. if (properties[i] == CSSPropertyBackgroundOrigin && !foundClip) addProperty(CSSPropertyBackgroundClip, clipValue.release(), important); else if (properties[i] == CSSPropertyWebkitMaskOrigin && !foundClip) addProperty(CSSPropertyWebkitMaskClip, clipValue.release(), important); } return true; } void CSSParser::addAnimationValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval) { if (lval) { if (lval->isValueList()) static_cast<CSSValueList*>(lval.get())->append(rval); else { PassRefPtr<CSSValue> oldVal(lval.release()); PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated(); list->append(oldVal); list->append(rval); lval = list; } } else lval = rval; } bool CSSParser::parseAnimationShorthand(bool important) { const int properties[] = { CSSPropertyWebkitAnimationName, CSSPropertyWebkitAnimationDuration, CSSPropertyWebkitAnimationTimingFunction, CSSPropertyWebkitAnimationDelay, CSSPropertyWebkitAnimationIterationCount, CSSPropertyWebkitAnimationDirection, CSSPropertyWebkitAnimationFillMode }; const int numProperties = WTF_ARRAY_LENGTH(properties); ShorthandScope scope(this, CSSPropertyWebkitAnimation); bool parsedProperty[numProperties] = { false }; // compiler will repeat false as necessary RefPtr<CSSValue> values[numProperties]; int i; while (m_valueList->current()) { CSSParserValue* val = m_valueList->current(); if (val->unit == CSSParserValue::Operator && val->iValue == ',') { // We hit the end. Fill in all remaining values with the initial value. m_valueList->next(); for (i = 0; i < numProperties; ++i) { if (!parsedProperty[i]) addAnimationValue(values[i], CSSInitialValue::createImplicit()); parsedProperty[i] = false; } if (!m_valueList->current()) break; } bool found = false; for (i = 0; !found && i < numProperties; ++i) { if (!parsedProperty[i]) { RefPtr<CSSValue> val; if (parseAnimationProperty(properties[i], val)) { parsedProperty[i] = found = true; addAnimationValue(values[i], val.release()); } } } // if we didn't find at least one match, this is an // invalid shorthand and we have to ignore it if (!found) return false; } // Fill in any remaining properties with the initial value. for (i = 0; i < numProperties; ++i) { if (!parsedProperty[i]) addAnimationValue(values[i], CSSInitialValue::createImplicit()); } // Now add all of the properties we found. for (i = 0; i < numProperties; i++) addProperty(properties[i], values[i].release(), important); return true; } bool CSSParser::parseTransitionShorthand(bool important) { const int properties[] = { CSSPropertyWebkitTransitionProperty, CSSPropertyWebkitTransitionDuration, CSSPropertyWebkitTransitionTimingFunction, CSSPropertyWebkitTransitionDelay }; const int numProperties = WTF_ARRAY_LENGTH(properties); ShorthandScope scope(this, CSSPropertyWebkitTransition); bool parsedProperty[numProperties] = { false }; // compiler will repeat false as necessary RefPtr<CSSValue> values[numProperties]; int i; while (m_valueList->current()) { CSSParserValue* val = m_valueList->current(); if (val->unit == CSSParserValue::Operator && val->iValue == ',') { // We hit the end. Fill in all remaining values with the initial value. m_valueList->next(); for (i = 0; i < numProperties; ++i) { if (!parsedProperty[i]) addAnimationValue(values[i], CSSInitialValue::createImplicit()); parsedProperty[i] = false; } if (!m_valueList->current()) break; } bool found = false; for (i = 0; !found && i < numProperties; ++i) { if (!parsedProperty[i]) { RefPtr<CSSValue> val; if (parseAnimationProperty(properties[i], val)) { parsedProperty[i] = found = true; addAnimationValue(values[i], val.release()); } } } // if we didn't find at least one match, this is an // invalid shorthand and we have to ignore it if (!found) return false; } // Fill in any remaining properties with the initial value. for (i = 0; i < numProperties; ++i) { if (!parsedProperty[i]) addAnimationValue(values[i], CSSInitialValue::createImplicit()); } // Now add all of the properties we found. for (i = 0; i < numProperties; i++) addProperty(properties[i], values[i].release(), important); return true; } bool CSSParser::parseShorthand(int propId, const int *properties, int numProperties, bool important) { // We try to match as many properties as possible // We set up an array of booleans to mark which property has been found, // and we try to search for properties until it makes no longer any sense. ShorthandScope scope(this, propId); bool found = false; bool fnd[6]; // Trust me ;) for (int i = 0; i < numProperties; i++) fnd[i] = false; while (m_valueList->current()) { found = false; for (int propIndex = 0; !found && propIndex < numProperties; ++propIndex) { if (!fnd[propIndex]) { if (parseValue(properties[propIndex], important)) fnd[propIndex] = found = true; } } // if we didn't find at least one match, this is an // invalid shorthand and we have to ignore it if (!found) return false; } // Fill in any remaining properties with the initial value. m_implicitShorthand = true; for (int i = 0; i < numProperties; ++i) { if (!fnd[i]) addProperty(properties[i], CSSInitialValue::createImplicit(), important); } m_implicitShorthand = false; return true; } bool CSSParser::parse4Values(int propId, const int *properties, bool important) { /* From the CSS 2 specs, 8.3 * If there is only one value, it applies to all sides. If there are two values, the top and * bottom margins are set to the first value and the right and left margins are set to the second. * If there are three values, the top is set to the first value, the left and right are set to the * second, and the bottom is set to the third. If there are four values, they apply to the top, * right, bottom, and left, respectively. */ int num = inShorthand() ? 1 : m_valueList->size(); ShorthandScope scope(this, propId); // the order is top, right, bottom, left switch (num) { case 1: { if (!parseValue(properties[0], important)) return false; CSSValue *value = m_parsedProperties[m_numParsedProperties-1]->value(); m_implicitShorthand = true; addProperty(properties[1], value, important); addProperty(properties[2], value, important); addProperty(properties[3], value, important); m_implicitShorthand = false; break; } case 2: { if (!parseValue(properties[0], important) || !parseValue(properties[1], important)) return false; CSSValue *value = m_parsedProperties[m_numParsedProperties-2]->value(); m_implicitShorthand = true; addProperty(properties[2], value, important); value = m_parsedProperties[m_numParsedProperties-2]->value(); addProperty(properties[3], value, important); m_implicitShorthand = false; break; } case 3: { if (!parseValue(properties[0], important) || !parseValue(properties[1], important) || !parseValue(properties[2], important)) return false; CSSValue *value = m_parsedProperties[m_numParsedProperties-2]->value(); m_implicitShorthand = true; addProperty(properties[3], value, important); m_implicitShorthand = false; break; } case 4: { if (!parseValue(properties[0], important) || !parseValue(properties[1], important) || !parseValue(properties[2], important) || !parseValue(properties[3], important)) return false; break; } default: { return false; } } return true; } // auto | <identifier> bool CSSParser::parsePage(int propId, bool important) { ASSERT(propId == CSSPropertyPage); if (m_valueList->size() != 1) return false; CSSParserValue* value = m_valueList->current(); if (!value) return false; if (value->id == CSSValueAuto) { addProperty(propId, primitiveValueCache()->createIdentifierValue(value->id), important); return true; } else if (value->id == 0 && value->unit == CSSPrimitiveValue::CSS_IDENT) { addProperty(propId, primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING), important); return true; } return false; } // <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ] bool CSSParser::parseSize(int propId, bool important) { ASSERT(propId == CSSPropertySize); if (m_valueList->size() > 2) return false; CSSParserValue* value = m_valueList->current(); if (!value) return false; RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated(); // First parameter. SizeParameterType paramType = parseSizeParameter(parsedValues.get(), value, None); if (paramType == None) return false; // Second parameter, if any. value = m_valueList->next(); if (value) { paramType = parseSizeParameter(parsedValues.get(), value, paramType); if (paramType == None) return false; } addProperty(propId, parsedValues.release(), important); return true; } CSSParser::SizeParameterType CSSParser::parseSizeParameter(CSSValueList* parsedValues, CSSParserValue* value, SizeParameterType prevParamType) { switch (value->id) { case CSSValueAuto: if (prevParamType == None) { parsedValues->append(primitiveValueCache()->createIdentifierValue(value->id)); return Auto; } return None; case CSSValueLandscape: case CSSValuePortrait: if (prevParamType == None || prevParamType == PageSize) { parsedValues->append(primitiveValueCache()->createIdentifierValue(value->id)); return Orientation; } return None; case CSSValueA3: case CSSValueA4: case CSSValueA5: case CSSValueB4: case CSSValueB5: case CSSValueLedger: case CSSValueLegal: case CSSValueLetter: if (prevParamType == None || prevParamType == Orientation) { // Normalize to Page Size then Orientation order by prepending. // This is not specified by the CSS3 Paged Media specification, but for simpler processing later (CSSStyleSelector::applyPageSizeProperty). parsedValues->prepend(primitiveValueCache()->createIdentifierValue(value->id)); return PageSize; } return None; case 0: if (validUnit(value, FLength | FNonNeg, m_strict) && (prevParamType == None || prevParamType == Length)) { parsedValues->append(primitiveValueCache()->createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit))); return Length; } return None; default: return None; } } // [ <string> <string> ]+ | inherit | none // inherit and none are handled in parseValue. bool CSSParser::parseQuotes(int propId, bool important) { RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated(); while (CSSParserValue* val = m_valueList->current()) { RefPtr<CSSValue> parsedValue; if (val->unit == CSSPrimitiveValue::CSS_STRING) parsedValue = CSSPrimitiveValue::create(val->string, CSSPrimitiveValue::CSS_STRING); else break; values->append(parsedValue.release()); m_valueList->next(); } if (values->length()) { addProperty(propId, values.release(), important); m_valueList->next(); return true; } return false; } // [ <string> | <uri> | <counter> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit // in CSS 2.1 this got somewhat reduced: // [ <string> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit bool CSSParser::parseContent(int propId, bool important) { RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated(); while (CSSParserValue* val = m_valueList->current()) { RefPtr<CSSValue> parsedValue; if (val->unit == CSSPrimitiveValue::CSS_URI && m_styleSheet) { // url // FIXME: The completeURL call should be done when using the CSSImageValue, // not when creating it. parsedValue = CSSImageValue::create(m_styleSheet->completeURL(val->string)); } else if (val->unit == CSSParserValue::Function) { // attr(X) | counter(X [,Y]) | counters(X, Y, [,Z]) | -webkit-gradient(...) CSSParserValueList* args = val->function->args.get(); if (!args) return false; if (equalIgnoringCase(val->function->name, "attr(")) { parsedValue = parseAttr(args); if (!parsedValue) return false; } else if (equalIgnoringCase(val->function->name, "counter(")) { parsedValue = parseCounterContent(args, false); if (!parsedValue) return false; } else if (equalIgnoringCase(val->function->name, "counters(")) { parsedValue = parseCounterContent(args, true); if (!parsedValue) return false; } else if (isGeneratedImageValue(val)) { if (!parseGeneratedImage(parsedValue)) return false; } else return false; } else if (val->unit == CSSPrimitiveValue::CSS_IDENT) { // open-quote // close-quote // no-open-quote // no-close-quote // inherit // FIXME: These are not yet implemented (http://bugs.webkit.org/show_bug.cgi?id=6503). // none // normal switch (val->id) { case CSSValueOpenQuote: case CSSValueCloseQuote: case CSSValueNoOpenQuote: case CSSValueNoCloseQuote: case CSSValueNone: case CSSValueNormal: parsedValue = primitiveValueCache()->createIdentifierValue(val->id); } } else if (val->unit == CSSPrimitiveValue::CSS_STRING) { parsedValue = primitiveValueCache()->createValue(val->string, CSSPrimitiveValue::CSS_STRING); } if (!parsedValue) break; values->append(parsedValue.release()); m_valueList->next(); } if (values->length()) { addProperty(propId, values.release(), important); m_valueList->next(); return true; } return false; } PassRefPtr<CSSValue> CSSParser::parseAttr(CSSParserValueList* args) { if (args->size() != 1) return 0; CSSParserValue* a = args->current(); if (a->unit != CSSPrimitiveValue::CSS_IDENT) return 0; String attrName = a->string; // CSS allows identifiers with "-" at the start, like "-webkit-mask-image". // But HTML attribute names can't have those characters, and we should not // even parse them inside attr(). if (attrName[0] == '-') return 0; if (document() && document()->isHTMLDocument()) attrName = attrName.lower(); return primitiveValueCache()->createValue(attrName, CSSPrimitiveValue::CSS_ATTR); } PassRefPtr<CSSValue> CSSParser::parseBackgroundColor() { int id = m_valueList->current()->id; if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu || id == CSSValueCurrentcolor || (id >= CSSValueGrey && id < CSSValueWebkitText && !m_strict)) return primitiveValueCache()->createIdentifierValue(id); return parseColor(); } bool CSSParser::parseFillImage(RefPtr<CSSValue>& value) { if (m_valueList->current()->id == CSSValueNone) { value = CSSImageValue::create(); return true; } if (m_valueList->current()->unit == CSSPrimitiveValue::CSS_URI) { // FIXME: The completeURL call should be done when using the CSSImageValue, // not when creating it. if (m_styleSheet) value = CSSImageValue::create(m_styleSheet->completeURL(m_valueList->current()->string)); return true; } if (isGeneratedImageValue(m_valueList->current())) return parseGeneratedImage(value); return false; } PassRefPtr<CSSValue> CSSParser::parseFillPositionX(CSSParserValueList* valueList) { int id = valueList->current()->id; if (id == CSSValueLeft || id == CSSValueRight || id == CSSValueCenter) { int percent = 0; if (id == CSSValueRight) percent = 100; else if (id == CSSValueCenter) percent = 50; return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE); } if (validUnit(valueList->current(), FPercent | FLength, m_strict)) return primitiveValueCache()->createValue(valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)valueList->current()->unit); return 0; } PassRefPtr<CSSValue> CSSParser::parseFillPositionY(CSSParserValueList* valueList) { int id = valueList->current()->id; if (id == CSSValueTop || id == CSSValueBottom || id == CSSValueCenter) { int percent = 0; if (id == CSSValueBottom) percent = 100; else if (id == CSSValueCenter) percent = 50; return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE); } if (validUnit(valueList->current(), FPercent | FLength, m_strict)) return primitiveValueCache()->createValue(valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)valueList->current()->unit); return 0; } PassRefPtr<CSSValue> CSSParser::parseFillPositionComponent(CSSParserValueList* valueList, unsigned& cumulativeFlags, FillPositionFlag& individualFlag) { int id = valueList->current()->id; if (id == CSSValueLeft || id == CSSValueTop || id == CSSValueRight || id == CSSValueBottom || id == CSSValueCenter) { int percent = 0; if (id == CSSValueLeft || id == CSSValueRight) { if (cumulativeFlags & XFillPosition) return 0; cumulativeFlags |= XFillPosition; individualFlag = XFillPosition; if (id == CSSValueRight) percent = 100; } else if (id == CSSValueTop || id == CSSValueBottom) { if (cumulativeFlags & YFillPosition) return 0; cumulativeFlags |= YFillPosition; individualFlag = YFillPosition; if (id == CSSValueBottom) percent = 100; } else if (id == CSSValueCenter) { // Center is ambiguous, so we're not sure which position we've found yet, an x or a y. percent = 50; cumulativeFlags |= AmbiguousFillPosition; individualFlag = AmbiguousFillPosition; } return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE); } if (validUnit(valueList->current(), FPercent | FLength, m_strict)) { if (!cumulativeFlags) { cumulativeFlags |= XFillPosition; individualFlag = XFillPosition; } else if (cumulativeFlags & (XFillPosition | AmbiguousFillPosition)) { cumulativeFlags |= YFillPosition; individualFlag = YFillPosition; } else return 0; return primitiveValueCache()->createValue(valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)valueList->current()->unit); } return 0; } void CSSParser::parseFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2) { CSSParserValue* value = valueList->current(); // Parse the first value. We're just making sure that it is one of the valid keywords or a percentage/length. unsigned cumulativeFlags = 0; FillPositionFlag value1Flag = InvalidFillPosition; FillPositionFlag value2Flag = InvalidFillPosition; value1 = parseFillPositionComponent(valueList, cumulativeFlags, value1Flag); if (!value1) return; // It only takes one value for background-position to be correctly parsed if it was specified in a shorthand (since we // can assume that any other values belong to the rest of the shorthand). If we're not parsing a shorthand, though, the // value was explicitly specified for our property. value = valueList->next(); // First check for the comma. If so, we are finished parsing this value or value pair. if (value && value->unit == CSSParserValue::Operator && value->iValue == ',') value = 0; if (value) { value2 = parseFillPositionComponent(valueList, cumulativeFlags, value2Flag); if (value2) valueList->next(); else { if (!inShorthand()) { value1.clear(); return; } } } if (!value2) // Only one value was specified. If that value was not a keyword, then it sets the x position, and the y position // is simply 50%. This is our default. // For keywords, the keyword was either an x-keyword (left/right), a y-keyword (top/bottom), or an ambiguous keyword (center). // For left/right/center, the default of 50% in the y is still correct. value2 = primitiveValueCache()->createValue(50, CSSPrimitiveValue::CSS_PERCENTAGE); if (value1Flag == YFillPosition || value2Flag == XFillPosition) value1.swap(value2); } void CSSParser::parseFillRepeat(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2) { CSSParserValue* value = m_valueList->current(); int id = m_valueList->current()->id; if (id == CSSValueRepeatX) { m_implicitShorthand = true; value1 = primitiveValueCache()->createIdentifierValue(CSSValueRepeat); value2 = primitiveValueCache()->createIdentifierValue(CSSValueNoRepeat); m_valueList->next(); return; } if (id == CSSValueRepeatY) { m_implicitShorthand = true; value1 = primitiveValueCache()->createIdentifierValue(CSSValueNoRepeat); value2 = primitiveValueCache()->createIdentifierValue(CSSValueRepeat); m_valueList->next(); return; } if (id == CSSValueRepeat || id == CSSValueNoRepeat || id == CSSValueRound || id == CSSValueSpace) value1 = primitiveValueCache()->createIdentifierValue(id); else { value1 = 0; return; } value = m_valueList->next(); // First check for the comma. If so, we are finished parsing this value or value pair. if (value && value->unit == CSSParserValue::Operator && value->iValue == ',') value = 0; if (value) id = m_valueList->current()->id; if (value && (id == CSSValueRepeat || id == CSSValueNoRepeat || id == CSSValueRound || id == CSSValueSpace)) { value2 = primitiveValueCache()->createIdentifierValue(id); m_valueList->next(); } else { // If only one value was specified, value2 is the same as value1. m_implicitShorthand = true; value2 = primitiveValueCache()->createIdentifierValue(static_cast<CSSPrimitiveValue*>(value1.get())->getIdent()); } } PassRefPtr<CSSValue> CSSParser::parseFillSize(int propId, bool& allowComma) { allowComma = true; CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueContain || value->id == CSSValueCover) return primitiveValueCache()->createIdentifierValue(value->id); RefPtr<CSSPrimitiveValue> parsedValue1; if (value->id == CSSValueAuto) parsedValue1 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN); else { if (!validUnit(value, FLength | FPercent, m_strict)) return 0; parsedValue1 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); } CSSPropertyID property = static_cast<CSSPropertyID>(propId); RefPtr<CSSPrimitiveValue> parsedValue2; if ((value = m_valueList->next())) { if (value->id == CSSValueAuto) parsedValue2 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN); else if (value->unit == CSSParserValue::Operator && value->iValue == ',') allowComma = false; else { if (!validUnit(value, FLength | FPercent, m_strict)) return 0; parsedValue2 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); } } if (!parsedValue2) { if (property == CSSPropertyWebkitBackgroundSize || property == CSSPropertyWebkitMaskSize) parsedValue2 = parsedValue1; else parsedValue2 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN); } return primitiveValueCache()->createValue(Pair::create(parsedValue1.release(), parsedValue2.release())); } bool CSSParser::parseFillProperty(int propId, int& propId1, int& propId2, RefPtr<CSSValue>& retValue1, RefPtr<CSSValue>& retValue2) { RefPtr<CSSValueList> values; RefPtr<CSSValueList> values2; CSSParserValue* val; RefPtr<CSSValue> value; RefPtr<CSSValue> value2; bool allowComma = false; retValue1 = retValue2 = 0; propId1 = propId; propId2 = propId; if (propId == CSSPropertyBackgroundPosition) { propId1 = CSSPropertyBackgroundPositionX; propId2 = CSSPropertyBackgroundPositionY; } else if (propId == CSSPropertyWebkitMaskPosition) { propId1 = CSSPropertyWebkitMaskPositionX; propId2 = CSSPropertyWebkitMaskPositionY; } else if (propId == CSSPropertyBackgroundRepeat) { propId1 = CSSPropertyBackgroundRepeatX; propId2 = CSSPropertyBackgroundRepeatY; } else if (propId == CSSPropertyWebkitMaskRepeat) { propId1 = CSSPropertyWebkitMaskRepeatX; propId2 = CSSPropertyWebkitMaskRepeatY; } while ((val = m_valueList->current())) { RefPtr<CSSValue> currValue; RefPtr<CSSValue> currValue2; if (allowComma) { if (val->unit != CSSParserValue::Operator || val->iValue != ',') return false; m_valueList->next(); allowComma = false; } else { allowComma = true; switch (propId) { case CSSPropertyBackgroundColor: currValue = parseBackgroundColor(); if (currValue) m_valueList->next(); break; case CSSPropertyBackgroundAttachment: case CSSPropertyWebkitMaskAttachment: if (val->id == CSSValueScroll || val->id == CSSValueFixed || val->id == CSSValueLocal) { currValue = primitiveValueCache()->createIdentifierValue(val->id); m_valueList->next(); } break; case CSSPropertyBackgroundImage: case CSSPropertyWebkitMaskImage: if (parseFillImage(currValue)) m_valueList->next(); break; case CSSPropertyWebkitBackgroundClip: case CSSPropertyWebkitBackgroundOrigin: case CSSPropertyWebkitMaskClip: case CSSPropertyWebkitMaskOrigin: // The first three values here are deprecated and do not apply to the version of the property that has // the -webkit- prefix removed. if (val->id == CSSValueBorder || val->id == CSSValuePadding || val->id == CSSValueContent || val->id == CSSValueBorderBox || val->id == CSSValuePaddingBox || val->id == CSSValueContentBox || ((propId == CSSPropertyWebkitBackgroundClip || propId == CSSPropertyWebkitMaskClip) && (val->id == CSSValueText || val->id == CSSValueWebkitText))) { currValue = primitiveValueCache()->createIdentifierValue(val->id); m_valueList->next(); } break; case CSSPropertyBackgroundClip: if (parseBackgroundClip(val, currValue, primitiveValueCache())) m_valueList->next(); break; case CSSPropertyBackgroundOrigin: if (val->id == CSSValueBorderBox || val->id == CSSValuePaddingBox || val->id == CSSValueContentBox) { currValue = primitiveValueCache()->createIdentifierValue(val->id); m_valueList->next(); } break; case CSSPropertyBackgroundPosition: case CSSPropertyWebkitMaskPosition: parseFillPosition(m_valueList, currValue, currValue2); // parseFillPosition advances the m_valueList pointer break; case CSSPropertyBackgroundPositionX: case CSSPropertyWebkitMaskPositionX: { currValue = parseFillPositionX(m_valueList); if (currValue) m_valueList->next(); break; } case CSSPropertyBackgroundPositionY: case CSSPropertyWebkitMaskPositionY: { currValue = parseFillPositionY(m_valueList); if (currValue) m_valueList->next(); break; } case CSSPropertyWebkitBackgroundComposite: case CSSPropertyWebkitMaskComposite: if ((val->id >= CSSValueClear && val->id <= CSSValuePlusLighter) || val->id == CSSValueHighlight) { currValue = primitiveValueCache()->createIdentifierValue(val->id); m_valueList->next(); } break; case CSSPropertyBackgroundRepeat: case CSSPropertyWebkitMaskRepeat: parseFillRepeat(currValue, currValue2); // parseFillRepeat advances the m_valueList pointer break; case CSSPropertyBackgroundSize: case CSSPropertyWebkitBackgroundSize: case CSSPropertyWebkitMaskSize: { currValue = parseFillSize(propId, allowComma); if (currValue) m_valueList->next(); break; } } if (!currValue) return false; if (value && !values) { values = CSSValueList::createCommaSeparated(); values->append(value.release()); } if (value2 && !values2) { values2 = CSSValueList::createCommaSeparated(); values2->append(value2.release()); } if (values) values->append(currValue.release()); else value = currValue.release(); if (currValue2) { if (values2) values2->append(currValue2.release()); else value2 = currValue2.release(); } } // When parsing any fill shorthand property, we let it handle building up the lists for all // properties. if (inShorthand()) break; } if (values && values->length()) { retValue1 = values.release(); if (values2 && values2->length()) retValue2 = values2.release(); return true; } if (value) { retValue1 = value.release(); retValue2 = value2.release(); return true; } return false; } PassRefPtr<CSSValue> CSSParser::parseAnimationDelay() { CSSParserValue* value = m_valueList->current(); if (validUnit(value, FTime, m_strict)) return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationDirection() { CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueNormal || value->id == CSSValueAlternate) return primitiveValueCache()->createIdentifierValue(value->id); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationDuration() { CSSParserValue* value = m_valueList->current(); if (validUnit(value, FTime | FNonNeg, m_strict)) return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationFillMode() { CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueNone || value->id == CSSValueForwards || value->id == CSSValueBackwards || value->id == CSSValueBoth) return primitiveValueCache()->createIdentifierValue(value->id); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationIterationCount() { CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueInfinite) return primitiveValueCache()->createIdentifierValue(value->id); if (validUnit(value, FInteger | FNonNeg, m_strict)) return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationName() { CSSParserValue* value = m_valueList->current(); if (value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT) { if (value->id == CSSValueNone || (value->unit == CSSPrimitiveValue::CSS_STRING && equalIgnoringCase(value->string, "none"))) { return primitiveValueCache()->createIdentifierValue(CSSValueNone); } else { return primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING); } } return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationPlayState() { CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueRunning || value->id == CSSValuePaused) return primitiveValueCache()->createIdentifierValue(value->id); return 0; } PassRefPtr<CSSValue> CSSParser::parseAnimationProperty() { CSSParserValue* value = m_valueList->current(); if (value->unit != CSSPrimitiveValue::CSS_IDENT) return 0; int result = cssPropertyID(value->string); if (result) return primitiveValueCache()->createIdentifierValue(result); if (equalIgnoringCase(value->string, "all")) return primitiveValueCache()->createIdentifierValue(CSSValueAll); if (equalIgnoringCase(value->string, "none")) return primitiveValueCache()->createIdentifierValue(CSSValueNone); return 0; } bool CSSParser::parseTransformOriginShorthand(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3) { parseFillPosition(m_valueList, value1, value2); // now get z if (m_valueList->current()) { if (validUnit(m_valueList->current(), FLength, m_strict)) { value3 = primitiveValueCache()->createValue(m_valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)m_valueList->current()->unit); m_valueList->next(); return true; } return false; } return true; } bool CSSParser::parseCubicBezierTimingFunctionValue(CSSParserValueList*& args, double& result) { CSSParserValue* v = args->current(); if (!validUnit(v, FNumber, m_strict)) return false; result = v->fValue; if (result < 0 || result > 1.0) return false; v = args->next(); if (!v) // The last number in the function has no comma after it, so we're done. return true; if (v->unit != CSSParserValue::Operator && v->iValue != ',') return false; v = args->next(); return true; } PassRefPtr<CSSValue> CSSParser::parseAnimationTimingFunction() { CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueEase || value->id == CSSValueLinear || value->id == CSSValueEaseIn || value->id == CSSValueEaseOut || value->id == CSSValueEaseInOut || value->id == CSSValueStepStart || value->id == CSSValueStepEnd) return primitiveValueCache()->createIdentifierValue(value->id); // We must be a function. if (value->unit != CSSParserValue::Function) return 0; CSSParserValueList* args = value->function->args.get(); if (equalIgnoringCase(value->function->name, "steps(")) { // For steps, 1 or 2 params must be specified (comma-separated) if (!args || (args->size() != 1 && args->size() != 3)) return 0; // There are two values. int numSteps; bool stepAtStart = false; CSSParserValue* v = args->current(); if (!validUnit(v, FInteger, m_strict)) return 0; numSteps = (int) min(v->fValue, (double)INT_MAX); if (numSteps < 1) return 0; v = args->next(); if (v) { // There is a comma so we need to parse the second value if (v->unit != CSSParserValue::Operator && v->iValue != ',') return 0; v = args->next(); if (v->id != CSSValueStart && v->id != CSSValueEnd) return 0; stepAtStart = v->id == CSSValueStart; } return CSSStepsTimingFunctionValue::create(numSteps, stepAtStart); } if (equalIgnoringCase(value->function->name, "cubic-bezier(")) { // For cubic bezier, 4 values must be specified. if (!args || args->size() != 7) return 0; // There are two points specified. The values must be between 0 and 1. double x1, y1, x2, y2; if (!parseCubicBezierTimingFunctionValue(args, x1)) return 0; if (!parseCubicBezierTimingFunctionValue(args, y1)) return 0; if (!parseCubicBezierTimingFunctionValue(args, x2)) return 0; if (!parseCubicBezierTimingFunctionValue(args, y2)) return 0; return CSSCubicBezierTimingFunctionValue::create(x1, y1, x2, y2); } return 0; } bool CSSParser::parseAnimationProperty(int propId, RefPtr<CSSValue>& result) { RefPtr<CSSValueList> values; CSSParserValue* val; RefPtr<CSSValue> value; bool allowComma = false; result = 0; while ((val = m_valueList->current())) { RefPtr<CSSValue> currValue; if (allowComma) { if (val->unit != CSSParserValue::Operator || val->iValue != ',') return false; m_valueList->next(); allowComma = false; } else { switch (propId) { case CSSPropertyWebkitAnimationDelay: case CSSPropertyWebkitTransitionDelay: currValue = parseAnimationDelay(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationDirection: currValue = parseAnimationDirection(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationDuration: case CSSPropertyWebkitTransitionDuration: currValue = parseAnimationDuration(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationFillMode: currValue = parseAnimationFillMode(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationIterationCount: currValue = parseAnimationIterationCount(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationName: currValue = parseAnimationName(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationPlayState: currValue = parseAnimationPlayState(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitTransitionProperty: currValue = parseAnimationProperty(); if (currValue) m_valueList->next(); break; case CSSPropertyWebkitAnimationTimingFunction: case CSSPropertyWebkitTransitionTimingFunction: currValue = parseAnimationTimingFunction(); if (currValue) m_valueList->next(); break; } if (!currValue) return false; if (value && !values) { values = CSSValueList::createCommaSeparated(); values->append(value.release()); } if (values) values->append(currValue.release()); else value = currValue.release(); allowComma = true; } // When parsing the 'transition' shorthand property, we let it handle building up the lists for all // properties. if (inShorthand()) break; } if (values && values->length()) { result = values.release(); return true; } if (value) { result = value.release(); return true; } return false; } #if ENABLE(DASHBOARD_SUPPORT) #define DASHBOARD_REGION_NUM_PARAMETERS 6 #define DASHBOARD_REGION_SHORT_NUM_PARAMETERS 2 static CSSParserValue* skipCommaInDashboardRegion(CSSParserValueList *args) { if (args->size() == (DASHBOARD_REGION_NUM_PARAMETERS*2-1) || args->size() == (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1)) { CSSParserValue* current = args->current(); if (current->unit == CSSParserValue::Operator && current->iValue == ',') return args->next(); } return args->current(); } bool CSSParser::parseDashboardRegions(int propId, bool important) { bool valid = true; CSSParserValue* value = m_valueList->current(); if (value->id == CSSValueNone) { if (m_valueList->next()) return false; addProperty(propId, primitiveValueCache()->createIdentifierValue(value->id), important); return valid; } RefPtr<DashboardRegion> firstRegion = DashboardRegion::create(); DashboardRegion* region = 0; while (value) { if (region == 0) { region = firstRegion.get(); } else { RefPtr<DashboardRegion> nextRegion = DashboardRegion::create(); region->m_next = nextRegion; region = nextRegion.get(); } if (value->unit != CSSParserValue::Function) { valid = false; break; } // Commas count as values, so allow: // dashboard-region(label, type, t, r, b, l) or dashboard-region(label type t r b l) // dashboard-region(label, type, t, r, b, l) or dashboard-region(label type t r b l) // also allow // dashboard-region(label, type) or dashboard-region(label type) // dashboard-region(label, type) or dashboard-region(label type) CSSParserValueList* args = value->function->args.get(); if (!equalIgnoringCase(value->function->name, "dashboard-region(") || !args) { valid = false; break; } int numArgs = args->size(); if ((numArgs != DASHBOARD_REGION_NUM_PARAMETERS && numArgs != (DASHBOARD_REGION_NUM_PARAMETERS*2-1)) && (numArgs != DASHBOARD_REGION_SHORT_NUM_PARAMETERS && numArgs != (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1))) { valid = false; break; } // First arg is a label. CSSParserValue* arg = args->current(); if (arg->unit != CSSPrimitiveValue::CSS_IDENT) { valid = false; break; } region->m_label = arg->string; // Second arg is a type. arg = args->next(); arg = skipCommaInDashboardRegion(args); if (arg->unit != CSSPrimitiveValue::CSS_IDENT) { valid = false; break; } if (equalIgnoringCase(arg->string, "circle")) region->m_isCircle = true; else if (equalIgnoringCase(arg->string, "rectangle")) region->m_isRectangle = true; else { valid = false; break; } region->m_geometryType = arg->string; if (numArgs == DASHBOARD_REGION_SHORT_NUM_PARAMETERS || numArgs == (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1)) { // This originally used CSSValueInvalid by accident. It might be more logical to use something else. RefPtr<CSSPrimitiveValue> amount = primitiveValueCache()->createIdentifierValue(CSSValueInvalid); region->setTop(amount); region->setRight(amount); region->setBottom(amount); region->setLeft(amount); } else { // Next four arguments must be offset numbers int i; for (i = 0; i < 4; i++) { arg = args->next(); arg = skipCommaInDashboardRegion(args); valid = arg->id == CSSValueAuto || validUnit(arg, FLength, m_strict); if (!valid) break; RefPtr<CSSPrimitiveValue> amount = arg->id == CSSValueAuto ? primitiveValueCache()->createIdentifierValue(CSSValueAuto) : primitiveValueCache()->createValue(arg->fValue, (CSSPrimitiveValue::UnitTypes) arg->unit); if (i == 0) region->setTop(amount); else if (i == 1) region->setRight(amount); else if (i == 2) region->setBottom(amount); else region->setLeft(amount); } } if (args->next()) return false; value = m_valueList->next(); } if (valid) addProperty(propId, primitiveValueCache()->createValue(firstRegion.release()), important); return valid; } #endif /* ENABLE(DASHBOARD_SUPPORT) */ PassRefPtr<CSSValue> CSSParser::parseCounterContent(CSSParserValueList* args, bool counters) { unsigned numArgs = args->size(); if (counters && numArgs != 3 && numArgs != 5) return 0; if (!counters && numArgs != 1 && numArgs != 3) return 0; CSSParserValue* i = args->current(); if (i->unit != CSSPrimitiveValue::CSS_IDENT) return 0; RefPtr<CSSPrimitiveValue> identifier = primitiveValueCache()->createValue(i->string, CSSPrimitiveValue::CSS_STRING); RefPtr<CSSPrimitiveValue> separator; if (!counters) separator = primitiveValueCache()->createValue(String(), CSSPrimitiveValue::CSS_STRING); else { i = args->next(); if (i->unit != CSSParserValue::Operator || i->iValue != ',') return 0; i = args->next(); if (i->unit != CSSPrimitiveValue::CSS_STRING) return 0; separator = primitiveValueCache()->createValue(i->string, (CSSPrimitiveValue::UnitTypes) i->unit); } RefPtr<CSSPrimitiveValue> listStyle; i = args->next(); if (!i) // Make the list style default decimal listStyle = primitiveValueCache()->createValue(CSSValueDecimal - CSSValueDisc, CSSPrimitiveValue::CSS_NUMBER); else { if (i->unit != CSSParserValue::Operator || i->iValue != ',') return 0; i = args->next(); if (i->unit != CSSPrimitiveValue::CSS_IDENT) return 0; short ls = 0; if (i->id == CSSValueNone) ls = CSSValueKatakanaIroha - CSSValueDisc + 1; else if (i->id >= CSSValueDisc && i->id <= CSSValueKatakanaIroha) ls = i->id - CSSValueDisc; else return 0; listStyle = primitiveValueCache()->createValue(ls, (CSSPrimitiveValue::UnitTypes) i->unit); } return primitiveValueCache()->createValue(Counter::create(identifier.release(), listStyle.release(), separator.release())); } bool CSSParser::parseShape(int propId, bool important) { CSSParserValue* value = m_valueList->current(); CSSParserValueList* args = value->function->args.get(); if (!equalIgnoringCase(value->function->name, "rect(") || !args) return false; // rect(t, r, b, l) || rect(t r b l) if (args->size() != 4 && args->size() != 7) return false; RefPtr<Rect> rect = Rect::create(); bool valid = true; int i = 0; CSSParserValue* a = args->current(); while (a) { valid = a->id == CSSValueAuto || validUnit(a, FLength, m_strict); if (!valid) break; RefPtr<CSSPrimitiveValue> length = a->id == CSSValueAuto ? primitiveValueCache()->createIdentifierValue(CSSValueAuto) : primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit); if (i == 0) rect->setTop(length); else if (i == 1) rect->setRight(length); else if (i == 2) rect->setBottom(length); else rect->setLeft(length); a = args->next(); if (a && args->size() == 7) { if (a->unit == CSSParserValue::Operator && a->iValue == ',') { a = args->next(); } else { valid = false; break; } } i++; } if (valid) { addProperty(propId, primitiveValueCache()->createValue(rect.release()), important); m_valueList->next(); return true; } return false; } // [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]? 'font-family' bool CSSParser::parseFont(bool important) { bool valid = true; CSSParserValue *value = m_valueList->current(); RefPtr<FontValue> font = FontValue::create(); // optional font-style, font-variant and font-weight while (value) { int id = value->id; if (id) { if (id == CSSValueNormal) { // do nothing, it's the inital value for all three } else if (id == CSSValueItalic || id == CSSValueOblique) { if (font->style) return false; font->style = primitiveValueCache()->createIdentifierValue(id); } else if (id == CSSValueSmallCaps) { if (font->variant) return false; font->variant = primitiveValueCache()->createIdentifierValue(id); } else if (id >= CSSValueBold && id <= CSSValueLighter) { if (font->weight) return false; font->weight = primitiveValueCache()->createIdentifierValue(id); } else { valid = false; } } else if (!font->weight && validUnit(value, FInteger | FNonNeg, true)) { int weight = (int)value->fValue; int val = 0; if (weight == 100) val = CSSValue100; else if (weight == 200) val = CSSValue200; else if (weight == 300) val = CSSValue300; else if (weight == 400) val = CSSValue400; else if (weight == 500) val = CSSValue500; else if (weight == 600) val = CSSValue600; else if (weight == 700) val = CSSValue700; else if (weight == 800) val = CSSValue800; else if (weight == 900) val = CSSValue900; if (val) font->weight = primitiveValueCache()->createIdentifierValue(val); else valid = false; } else { valid = false; } if (!valid) break; value = m_valueList->next(); } if (!value) return false; // set undefined values to default if (!font->style) font->style = primitiveValueCache()->createIdentifierValue(CSSValueNormal); if (!font->variant) font->variant = primitiveValueCache()->createIdentifierValue(CSSValueNormal); if (!font->weight) font->weight = primitiveValueCache()->createIdentifierValue(CSSValueNormal); // now a font size _must_ come // <absolute-size> | <relative-size> | <length> | <percentage> | inherit if (value->id >= CSSValueXxSmall && value->id <= CSSValueLarger) font->size = primitiveValueCache()->createIdentifierValue(value->id); else if (validUnit(value, FLength | FPercent | FNonNeg, m_strict)) font->size = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit); value = m_valueList->next(); if (!font->size || !value) return false; if (value->unit == CSSParserValue::Operator && value->iValue == '/') { // line-height value = m_valueList->next(); if (!value) return false; if (value->id == CSSValueNormal) { // default value, nothing to do } else if (validUnit(value, FNumber | FLength | FPercent | FNonNeg, m_strict)) font->lineHeight = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit); else return false; value = m_valueList->next(); if (!value) return false; } if (!font->lineHeight) font->lineHeight = primitiveValueCache()->createIdentifierValue(CSSValueNormal); // font family must come now font->family = parseFontFamily(); if (m_valueList->current() || !font->family) return false; addProperty(CSSPropertyFont, font.release(), important); return true; } PassRefPtr<CSSValueList> CSSParser::parseFontFamily() { RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated(); CSSParserValue* value = m_valueList->current(); FontFamilyValue* currFamily = 0; while (value) { CSSParserValue* nextValue = m_valueList->next(); bool nextValBreaksFont = !nextValue || (nextValue->unit == CSSParserValue::Operator && nextValue->iValue == ','); bool nextValIsFontName = nextValue && ((nextValue->id >= CSSValueSerif && nextValue->id <= CSSValueWebkitBody) || (nextValue->unit == CSSPrimitiveValue::CSS_STRING || nextValue->unit == CSSPrimitiveValue::CSS_IDENT)); if (value->id >= CSSValueSerif && value->id <= CSSValueWebkitBody) { if (currFamily) currFamily->appendSpaceSeparated(value->string.characters, value->string.length); else if (nextValBreaksFont || !nextValIsFontName) list->append(primitiveValueCache()->createIdentifierValue(value->id)); else { RefPtr<FontFamilyValue> newFamily = FontFamilyValue::create(value->string); currFamily = newFamily.get(); list->append(newFamily.release()); } } else if (value->unit == CSSPrimitiveValue::CSS_STRING) { // Strings never share in a family name. currFamily = 0; list->append(FontFamilyValue::create(value->string)); } else if (value->unit == CSSPrimitiveValue::CSS_IDENT) { if (currFamily) currFamily->appendSpaceSeparated(value->string.characters, value->string.length); else if (nextValBreaksFont || !nextValIsFontName) list->append(FontFamilyValue::create(value->string)); else { RefPtr<FontFamilyValue> newFamily = FontFamilyValue::create(value->string); currFamily = newFamily.get(); list->append(newFamily.release()); } } else { break; } if (!nextValue) break; if (nextValBreaksFont) { value = m_valueList->next(); currFamily = 0; } else if (nextValIsFontName) value = nextValue; else break; } if (!list->length()) list = 0; return list.release(); } bool CSSParser::parseFontStyle(bool important) { RefPtr<CSSValueList> values; if (m_valueList->size() > 1) values = CSSValueList::createCommaSeparated(); CSSParserValue* val; bool expectComma = false; while ((val = m_valueList->current())) { RefPtr<CSSPrimitiveValue> parsedValue; if (!expectComma) { expectComma = true; if (val->id == CSSValueNormal || val->id == CSSValueItalic || val->id == CSSValueOblique) parsedValue = primitiveValueCache()->createIdentifierValue(val->id); else if (val->id == CSSValueAll && !values) { // 'all' is only allowed in @font-face and with no other values. Make a value list to // indicate that we are in the @font-face case. values = CSSValueList::createCommaSeparated(); parsedValue = primitiveValueCache()->createIdentifierValue(val->id); } } else if (val->unit == CSSParserValue::Operator && val->iValue == ',') { expectComma = false; m_valueList->next(); continue; } if (!parsedValue) return false; m_valueList->next(); if (values) values->append(parsedValue.release()); else { addProperty(CSSPropertyFontStyle, parsedValue.release(), important); return true; } } if (values && values->length()) { m_hasFontFaceOnlyValues = true; addProperty(CSSPropertyFontStyle, values.release(), important); return true; } return false; } bool CSSParser::parseFontVariant(bool important) { RefPtr<CSSValueList> values; if (m_valueList->size() > 1) values = CSSValueList::createCommaSeparated(); CSSParserValue* val; bool expectComma = false; while ((val = m_valueList->current())) { RefPtr<CSSPrimitiveValue> parsedValue; if (!expectComma) { expectComma = true; if (val->id == CSSValueNormal || val->id == CSSValueSmallCaps) parsedValue = primitiveValueCache()->createIdentifierValue(val->id); else if (val->id == CSSValueAll && !values) { // 'all' is only allowed in @font-face and with no other values. Make a value list to // indicate that we are in the @font-face case. values = CSSValueList::createCommaSeparated(); parsedValue = primitiveValueCache()->createIdentifierValue(val->id); } } else if (val->unit == CSSParserValue::Operator && val->iValue == ',') { expectComma = false; m_valueList->next(); continue; } if (!parsedValue) return false; m_valueList->next(); if (values) values->append(parsedValue.release()); else { addProperty(CSSPropertyFontVariant, parsedValue.release(), important); return true; } } if (values && values->length()) { m_hasFontFaceOnlyValues = true; addProperty(CSSPropertyFontVariant, values.release(), important); return true; } return false; } bool CSSParser::parseFontWeight(bool important) { RefPtr<CSSValueList> values; if (m_valueList->size() > 1) values = CSSValueList::createCommaSeparated(); CSSParserValue* val; bool expectComma = false; while ((val = m_valueList->current())) { RefPtr<CSSPrimitiveValue> parsedValue; if (!expectComma) { expectComma = true; if (val->unit == CSSPrimitiveValue::CSS_IDENT) { if (val->id >= CSSValueNormal && val->id <= CSSValue900) parsedValue = primitiveValueCache()->createIdentifierValue(val->id); else if (val->id == CSSValueAll && !values) { // 'all' is only allowed in @font-face and with no other values. Make a value list to // indicate that we are in the @font-face case. values = CSSValueList::createCommaSeparated(); parsedValue = primitiveValueCache()->createIdentifierValue(val->id); } } else if (validUnit(val, FInteger | FNonNeg, false)) { int weight = static_cast<int>(val->fValue); if (!(weight % 100) && weight >= 100 && weight <= 900) parsedValue = primitiveValueCache()->createIdentifierValue(CSSValue100 + weight / 100 - 1); } } else if (val->unit == CSSParserValue::Operator && val->iValue == ',') { expectComma = false; m_valueList->next(); continue; } if (!parsedValue) return false; m_valueList->next(); if (values) values->append(parsedValue.release()); else { addProperty(CSSPropertyFontWeight, parsedValue.release(), important); return true; } } if (values && values->length()) { m_hasFontFaceOnlyValues = true; addProperty(CSSPropertyFontWeight, values.release(), important); return true; } return false; } static bool isValidFormatFunction(CSSParserValue* val) { CSSParserValueList* args = val->function->args.get(); return equalIgnoringCase(val->function->name, "format(") && (args->current()->unit == CSSPrimitiveValue::CSS_STRING || args->current()->unit == CSSPrimitiveValue::CSS_IDENT); } bool CSSParser::parseFontFaceSrc() { RefPtr<CSSValueList> values(CSSValueList::createCommaSeparated()); CSSParserValue* val; bool expectComma = false; bool allowFormat = false; bool failed = false; RefPtr<CSSFontFaceSrcValue> uriValue; while ((val = m_valueList->current())) { RefPtr<CSSFontFaceSrcValue> parsedValue; if (val->unit == CSSPrimitiveValue::CSS_URI && !expectComma && m_styleSheet) { // FIXME: The completeURL call should be done when using the CSSFontFaceSrcValue, // not when creating it. parsedValue = CSSFontFaceSrcValue::create(m_styleSheet->completeURL(val->string)); uriValue = parsedValue; allowFormat = true; expectComma = true; } else if (val->unit == CSSParserValue::Function) { // There are two allowed functions: local() and format(). CSSParserValueList* args = val->function->args.get(); if (args && args->size() == 1) { if (equalIgnoringCase(val->function->name, "local(") && !expectComma && (args->current()->unit == CSSPrimitiveValue::CSS_STRING || args->current()->unit == CSSPrimitiveValue::CSS_IDENT)) { expectComma = true; allowFormat = false; CSSParserValue* a = args->current(); uriValue.clear(); parsedValue = CSSFontFaceSrcValue::createLocal(a->string); } else if (allowFormat && uriValue && isValidFormatFunction(val)) { expectComma = true; allowFormat = false; uriValue->setFormat(args->current()->string); uriValue.clear(); m_valueList->next(); continue; } } } else if (val->unit == CSSParserValue::Operator && val->iValue == ',' && expectComma) { expectComma = false; allowFormat = false; uriValue.clear(); m_valueList->next(); continue; } if (parsedValue) values->append(parsedValue.release()); else { failed = true; break; } m_valueList->next(); } if (values->length() && !failed) { addProperty(CSSPropertySrc, values.release(), m_important); m_valueList->next(); return true; } return false; } bool CSSParser::parseFontFaceUnicodeRange() { RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated(); bool failed = false; bool operatorExpected = false; for (; m_valueList->current(); m_valueList->next(), operatorExpected = !operatorExpected) { if (operatorExpected) { if (m_valueList->current()->unit == CSSParserValue::Operator && m_valueList->current()->iValue == ',') continue; failed = true; break; } if (m_valueList->current()->unit != CSSPrimitiveValue::CSS_UNICODE_RANGE) { failed = true; break; } String rangeString = m_valueList->current()->string; UChar32 from = 0; UChar32 to = 0; unsigned length = rangeString.length(); if (length < 3) { failed = true; break; } unsigned i = 2; while (i < length) { UChar c = rangeString[i]; if (c == '-' || c == '?') break; from *= 16; if (c >= '0' && c <= '9') from += c - '0'; else if (c >= 'A' && c <= 'F') from += 10 + c - 'A'; else if (c >= 'a' && c <= 'f') from += 10 + c - 'a'; else { failed = true; break; } i++; } if (failed) break; if (i == length) to = from; else if (rangeString[i] == '?') { unsigned span = 1; while (i < length && rangeString[i] == '?') { span *= 16; from *= 16; i++; } if (i < length) failed = true; to = from + span - 1; } else { if (length < i + 2) { failed = true; break; } i++; while (i < length) { UChar c = rangeString[i]; to *= 16; if (c >= '0' && c <= '9') to += c - '0'; else if (c >= 'A' && c <= 'F') to += 10 + c - 'A'; else if (c >= 'a' && c <= 'f') to += 10 + c - 'a'; else { failed = true; break; } i++; } if (failed) break; } if (from <= to) values->append(CSSUnicodeRangeValue::create(from, to)); } if (failed || !values->length()) return false; addProperty(CSSPropertyUnicodeRange, values.release(), m_important); return true; } // Returns the number of characters which form a valid double // and are terminated by the given terminator character static int checkForValidDouble(const UChar* string, const UChar* end, const char terminator) { int length = end - string; if (length < 1) return 0; bool decimalMarkSeen = false; int processedLength = 0; for (int i = 0; i < length; ++i) { if (string[i] == terminator) { processedLength = i; break; } if (!isASCIIDigit(string[i])) { if (!decimalMarkSeen && string[i] == '.') decimalMarkSeen = true; else return 0; } } if (decimalMarkSeen && processedLength == 1) return 0; return processedLength; } // Returns the number of characters consumed for parsing a valid double // terminated by the given terminator character static int parseDouble(const UChar* string, const UChar* end, const char terminator, double& value) { int length = checkForValidDouble(string, end, terminator); if (!length) return 0; int position = 0; double localValue = 0; // The consumed characters here are guaranteed to be // ASCII digits with or without a decimal mark for (; position < length; ++position) { if (string[position] == '.') break; localValue = localValue * 10 + string[position] - '0'; } if (++position == length) { value = localValue; return length; } double fraction = 0; double scale = 1; while (position < length && scale < MAX_SCALE) { fraction = fraction * 10 + string[position++] - '0'; scale *= 10; } value = localValue + fraction / scale; return length; } static bool parseColorIntOrPercentage(const UChar*& string, const UChar* end, const char terminator, CSSPrimitiveValue::UnitTypes& expect, int& value) { const UChar* current = string; double localValue = 0; bool negative = false; while (current != end && isHTMLSpace(*current)) current++; if (current != end && *current == '-') { negative = true; current++; } if (current == end || !isASCIIDigit(*current)) return false; while (current != end && isASCIIDigit(*current)) { double newValue = localValue * 10 + *current++ - '0'; if (newValue >= 255) { // Clamp values at 255. localValue = 255; while (current != end && isASCIIDigit(*current)) ++current; break; } localValue = newValue; } if (current == end) return false; if (expect == CSSPrimitiveValue::CSS_NUMBER && (*current == '.' || *current == '%')) return false; if (*current == '.') { // We already parsed the integral part, try to parse // the fraction part of the percentage value. double percentage = 0; int numCharactersParsed = parseDouble(current, end, '%', percentage); if (!numCharactersParsed) return false; current += numCharactersParsed; if (*current != '%') return false; localValue += percentage; } if (expect == CSSPrimitiveValue::CSS_PERCENTAGE && *current != '%') return false; if (*current == '%') { expect = CSSPrimitiveValue::CSS_PERCENTAGE; localValue = localValue / 100.0 * 256.0; // Clamp values at 255 for percentages over 100% if (localValue > 255) localValue = 255; current++; } else expect = CSSPrimitiveValue::CSS_NUMBER; while (current != end && isHTMLSpace(*current)) current++; if (current == end || *current++ != terminator) return false; // Clamp negative values at zero. value = negative ? 0 : static_cast<int>(localValue); string = current; return true; } static inline bool isTenthAlpha(const UChar* string, const int length) { // "0.X" if (length == 3 && string[0] == '0' && string[1] == '.' && isASCIIDigit(string[2])) return true; // ".X" if (length == 2 && string[0] == '.' && isASCIIDigit(string[1])) return true; return false; } static inline bool parseAlphaValue(const UChar*& string, const UChar* end, const char terminator, int& value) { while (string != end && isHTMLSpace(*string)) string++; bool negative = false; if (string != end && *string == '-') { negative = true; string++; } value = 0; int length = end - string; if (length < 2) return false; if (string[length - 1] != terminator) return false; if (string[0] != '0' && string[0] != '1' && string[0] != '.') { if (checkForValidDouble(string, end, terminator)) { value = negative ? 0 : 255; string = end; return true; } return false; } if (length == 2 && string[0] != '.') { value = !negative && string[0] == '1' ? 255 : 0; string = end; return true; } if (isTenthAlpha(string, length - 1)) { static const int tenthAlphaValues[] = { 0, 25, 51, 76, 102, 127, 153, 179, 204, 230 }; value = negative ? 0 : tenthAlphaValues[string[length - 2] - '0']; string = end; return true; } double alpha = 0; if (!parseDouble(string, end, terminator, alpha)) return false; value = negative ? 0 : static_cast<int>(alpha * nextafter(256.0, 0.0)); string = end; return true; } static inline bool mightBeRGBA(const UChar* characters, unsigned length) { if (length < 5) return false; return characters[4] == '(' && (characters[0] | 0x20) == 'r' && (characters[1] | 0x20) == 'g' && (characters[2] | 0x20) == 'b' && (characters[3] | 0x20) == 'a'; } static inline bool mightBeRGB(const UChar* characters, unsigned length) { if (length < 4) return false; return characters[3] == '(' && (characters[0] | 0x20) == 'r' && (characters[1] | 0x20) == 'g' && (characters[2] | 0x20) == 'b'; } bool CSSParser::parseColor(const String &name, RGBA32& rgb, bool strict) { const UChar* characters = name.characters(); unsigned length = name.length(); CSSPrimitiveValue::UnitTypes expect = CSSPrimitiveValue::CSS_UNKNOWN; if (!strict && length >= 3) { if (name[0] == '#') { if (Color::parseHexColor(characters + 1, length - 1, rgb)) return true; } else { if (Color::parseHexColor(characters, length, rgb)) return true; } } // Try rgba() syntax. if (mightBeRGBA(characters, length)) { const UChar* current = characters + 5; const UChar* end = characters + length; int red; int green; int blue; int alpha; if (!parseColorIntOrPercentage(current, end, ',', expect, red)) return false; if (!parseColorIntOrPercentage(current, end, ',', expect, green)) return false; if (!parseColorIntOrPercentage(current, end, ',', expect, blue)) return false; if (!parseAlphaValue(current, end, ')', alpha)) return false; if (current != end) return false; rgb = makeRGBA(red, green, blue, alpha); return true; } // Try rgb() syntax. if (mightBeRGB(characters, length)) { const UChar* current = characters + 4; const UChar* end = characters + length; int red; int green; int blue; if (!parseColorIntOrPercentage(current, end, ',', expect, red)) return false; if (!parseColorIntOrPercentage(current, end, ',', expect, green)) return false; if (!parseColorIntOrPercentage(current, end, ')', expect, blue)) return false; if (current != end) return false; rgb = makeRGB(red, green, blue); return true; } // Try named colors. Color tc; tc.setNamedColor(name); if (tc.isValid()) { rgb = tc.rgb(); return true; } return false; } static inline int colorIntFromValue(CSSParserValue* v) { if (v->fValue <= 0.0) return 0; if (v->unit == CSSPrimitiveValue::CSS_PERCENTAGE) { if (v->fValue >= 100.0) return 255; return static_cast<int>(v->fValue * 256.0 / 100.0); } if (v->fValue >= 255.0) return 255; return static_cast<int>(v->fValue); } bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, bool parseAlpha) { CSSParserValueList* args = value->function->args.get(); CSSParserValue* v = args->current(); Units unitType = FUnknown; // Get the first value and its type if (validUnit(v, FInteger, true)) unitType = FInteger; else if (validUnit(v, FPercent, true)) unitType = FPercent; else return false; colorArray[0] = colorIntFromValue(v); for (int i = 1; i < 3; i++) { v = args->next(); if (v->unit != CSSParserValue::Operator && v->iValue != ',') return false; v = args->next(); if (!validUnit(v, unitType, true)) return false; colorArray[i] = colorIntFromValue(v); } if (parseAlpha) { v = args->next(); if (v->unit != CSSParserValue::Operator && v->iValue != ',') return false; v = args->next(); if (!validUnit(v, FNumber, true)) return false; // Convert the floating pointer number of alpha to an integer in the range [0, 256), // with an equal distribution across all 256 values. colorArray[3] = static_cast<int>(max(0.0, min(1.0, v->fValue)) * nextafter(256.0, 0.0)); } return true; } // The CSS3 specification defines the format of a HSL color as // hsl(<number>, <percent>, <percent>) // and with alpha, the format is // hsla(<number>, <percent>, <percent>, <number>) // The first value, HUE, is in an angle with a value between 0 and 360 bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bool parseAlpha) { CSSParserValueList* args = value->function->args.get(); CSSParserValue* v = args->current(); // Get the first value if (!validUnit(v, FNumber, true)) return false; // normalize the Hue value and change it to be between 0 and 1.0 colorArray[0] = (((static_cast<int>(v->fValue) % 360) + 360) % 360) / 360.0; for (int i = 1; i < 3; i++) { v = args->next(); if (v->unit != CSSParserValue::Operator && v->iValue != ',') return false; v = args->next(); if (!validUnit(v, FPercent, true)) return false; colorArray[i] = max(0.0, min(100.0, v->fValue)) / 100.0; // needs to be value between 0 and 1.0 } if (parseAlpha) { v = args->next(); if (v->unit != CSSParserValue::Operator && v->iValue != ',') return false; v = args->next(); if (!validUnit(v, FNumber, true)) return false; colorArray[3] = max(0.0, min(1.0, v->fValue)); } return true; } PassRefPtr<CSSPrimitiveValue> CSSParser::parseColor(CSSParserValue* value) { RGBA32 c = Color::transparent; if (!parseColorFromValue(value ? value : m_valueList->current(), c)) return 0; return primitiveValueCache()->createColorValue(c); } bool CSSParser::parseColorFromValue(CSSParserValue* value, RGBA32& c) { if (!m_strict && value->unit == CSSPrimitiveValue::CSS_NUMBER && value->fValue >= 0. && value->fValue < 1000000.) { String str = String::format("%06d", (int)(value->fValue+.5)); if (!CSSParser::parseColor(str, c, m_strict)) return false; } else if (value->unit == CSSPrimitiveValue::CSS_PARSER_HEXCOLOR || value->unit == CSSPrimitiveValue::CSS_IDENT || (!m_strict && value->unit == CSSPrimitiveValue::CSS_DIMENSION)) { if (!CSSParser::parseColor(value->string, c, m_strict && value->unit == CSSPrimitiveValue::CSS_IDENT)) return false; } else if (value->unit == CSSParserValue::Function && value->function->args != 0 && value->function->args->size() == 5 /* rgb + two commas */ && equalIgnoringCase(value->function->name, "rgb(")) { int colorValues[3]; if (!parseColorParameters(value, colorValues, false)) return false; c = makeRGB(colorValues[0], colorValues[1], colorValues[2]); } else { if (value->unit == CSSParserValue::Function && value->function->args != 0 && value->function->args->size() == 7 /* rgba + three commas */ && equalIgnoringCase(value->function->name, "rgba(")) { int colorValues[4]; if (!parseColorParameters(value, colorValues, true)) return false; c = makeRGBA(colorValues[0], colorValues[1], colorValues[2], colorValues[3]); } else if (value->unit == CSSParserValue::Function && value->function->args != 0 && value->function->args->size() == 5 /* hsl + two commas */ && equalIgnoringCase(value->function->name, "hsl(")) { double colorValues[3]; if (!parseHSLParameters(value, colorValues, false)) return false; c = makeRGBAFromHSLA(colorValues[0], colorValues[1], colorValues[2], 1.0); } else if (value->unit == CSSParserValue::Function && value->function->args != 0 && value->function->args->size() == 7 /* hsla + three commas */ && equalIgnoringCase(value->function->name, "hsla(")) { double colorValues[4]; if (!parseHSLParameters(value, colorValues, true)) return false; c = makeRGBAFromHSLA(colorValues[0], colorValues[1], colorValues[2], colorValues[3]); } else return false; } return true; } // This class tracks parsing state for shadow values. If it goes out of scope (e.g., due to an early return) // without the allowBreak bit being set, then it will clean up all of the objects and destroy them. struct ShadowParseContext { ShadowParseContext(CSSPropertyID prop, CSSPrimitiveValueCache* primitiveValueCache) : property(prop) , m_primitiveValueCache(primitiveValueCache) , allowX(true) , allowY(false) , allowBlur(false) , allowSpread(false) , allowColor(true) , allowStyle(prop == CSSPropertyWebkitBoxShadow || prop == CSSPropertyBoxShadow) , allowBreak(true) { } bool allowLength() { return allowX || allowY || allowBlur || allowSpread; } void commitValue() { // Handle the ,, case gracefully by doing nothing. if (x || y || blur || spread || color || style) { if (!values) values = CSSValueList::createCommaSeparated(); // Construct the current shadow value and add it to the list. values->append(ShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release())); } // Now reset for the next shadow value. x = 0; y = 0; blur = 0; spread = 0; style = 0; color = 0; allowX = true; allowColor = true; allowBreak = true; allowY = false; allowBlur = false; allowSpread = false; allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow; } void commitLength(CSSParserValue* v) { RefPtr<CSSPrimitiveValue> val = m_primitiveValueCache->createValue(v->fValue, (CSSPrimitiveValue::UnitTypes)v->unit); if (allowX) { x = val.release(); allowX = false; allowY = true; allowColor = false; allowStyle = false; allowBreak = false; } else if (allowY) { y = val.release(); allowY = false; allowBlur = true; allowColor = true; allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow; allowBreak = true; } else if (allowBlur) { blur = val.release(); allowBlur = false; allowSpread = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow; } else if (allowSpread) { spread = val.release(); allowSpread = false; } } void commitColor(PassRefPtr<CSSPrimitiveValue> val) { color = val; allowColor = false; if (allowX) { allowStyle = false; allowBreak = false; } else { allowBlur = false; allowSpread = false; allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow; } } void commitStyle(CSSParserValue* v) { style = m_primitiveValueCache->createIdentifierValue(v->id); allowStyle = false; if (allowX) allowBreak = false; else { allowBlur = false; allowSpread = false; allowColor = false; } } CSSPropertyID property; CSSPrimitiveValueCache* m_primitiveValueCache; RefPtr<CSSValueList> values; RefPtr<CSSPrimitiveValue> x; RefPtr<CSSPrimitiveValue> y; RefPtr<CSSPrimitiveValue> blur; RefPtr<CSSPrimitiveValue> spread; RefPtr<CSSPrimitiveValue> style; RefPtr<CSSPrimitiveValue> color; bool allowX; bool allowY; bool allowBlur; bool allowSpread; bool allowColor; bool allowStyle; // inset or not. bool allowBreak; }; bool CSSParser::parseShadow(int propId, bool important) { ShadowParseContext context(static_cast<CSSPropertyID>(propId), primitiveValueCache()); CSSParserValue* val; while ((val = m_valueList->current())) { // Check for a comma break first. if (val->unit == CSSParserValue::Operator) { if (val->iValue != ',' || !context.allowBreak) // Other operators aren't legal or we aren't done with the current shadow // value. Treat as invalid. return false; #if ENABLE(SVG) // -webkit-svg-shadow does not support multiple values. if (static_cast<CSSPropertyID>(propId) == CSSPropertyWebkitSvgShadow) return false; #endif // The value is good. Commit it. context.commitValue(); } else if (validUnit(val, FLength, true)) { // We required a length and didn't get one. Invalid. if (!context.allowLength()) return false; // A length is allowed here. Construct the value and add it. context.commitLength(val); } else if (val->id == CSSValueInset) { if (!context.allowStyle) return false; context.commitStyle(val); } else { // The only other type of value that's ok is a color value. RefPtr<CSSPrimitiveValue> parsedColor; bool isColor = ((val->id >= CSSValueAqua && val->id <= CSSValueWindowtext) || val->id == CSSValueMenu || (val->id >= CSSValueWebkitFocusRingColor && val->id <= CSSValueWebkitText && !m_strict)); if (isColor) { if (!context.allowColor) return false; parsedColor = primitiveValueCache()->createIdentifierValue(val->id); } if (!parsedColor) // It's not built-in. Try to parse it as a color. parsedColor = parseColor(val); if (!parsedColor || !context.allowColor) return false; // This value is not a color or length and is invalid or // it is a color, but a color isn't allowed at this point. context.commitColor(parsedColor.release()); } m_valueList->next(); } if (context.allowBreak) { context.commitValue(); if (context.values->length()) { addProperty(propId, context.values.release(), important); m_valueList->next(); return true; } } return false; } bool CSSParser::parseReflect(int propId, bool important) { // box-reflect: <direction> <offset> <mask> // Direction comes first. CSSParserValue* val = m_valueList->current(); CSSReflectionDirection direction; switch (val->id) { case CSSValueAbove: direction = ReflectionAbove; break; case CSSValueBelow: direction = ReflectionBelow; break; case CSSValueLeft: direction = ReflectionLeft; break; case CSSValueRight: direction = ReflectionRight; break; default: return false; } // The offset comes next. val = m_valueList->next(); RefPtr<CSSPrimitiveValue> offset; if (!val) offset = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_PX); else { if (!validUnit(val, FLength | FPercent, m_strict)) return false; offset = primitiveValueCache()->createValue(val->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(val->unit)); } // Now for the mask. RefPtr<CSSValue> mask; val = m_valueList->next(); if (val) { if (!parseBorderImage(propId, important, mask)) return false; } RefPtr<CSSReflectValue> reflectValue = CSSReflectValue::create(direction, offset.release(), mask.release()); addProperty(propId, reflectValue.release(), important); m_valueList->next(); return true; } struct BorderImageParseContext { BorderImageParseContext(CSSPrimitiveValueCache* primitiveValueCache) : m_primitiveValueCache(primitiveValueCache) , m_allowBreak(false) , m_allowNumber(false) , m_allowSlash(false) , m_allowWidth(false) , m_allowRule(false) , m_borderTop(0) , m_borderRight(0) , m_borderBottom(0) , m_borderLeft(0) , m_horizontalRule(0) , m_verticalRule(0) {} bool allowBreak() const { return m_allowBreak; } bool allowNumber() const { return m_allowNumber; } bool allowSlash() const { return m_allowSlash; } bool allowWidth() const { return m_allowWidth; } bool allowRule() const { return m_allowRule; } void commitImage(PassRefPtr<CSSValue> image) { m_image = image; m_allowNumber = true; } void commitNumber(CSSParserValue* v) { PassRefPtr<CSSPrimitiveValue> val = m_primitiveValueCache->createValue(v->fValue, (CSSPrimitiveValue::UnitTypes)v->unit); if (!m_top) m_top = val; else if (!m_right) m_right = val; else if (!m_bottom) m_bottom = val; else { ASSERT(!m_left); m_left = val; } m_allowBreak = m_allowSlash = m_allowRule = true; m_allowNumber = !m_left; } void commitSlash() { m_allowBreak = m_allowSlash = m_allowNumber = false; m_allowWidth = true; } void commitWidth(CSSParserValue* val) { if (!m_borderTop) m_borderTop = val; else if (!m_borderRight) m_borderRight = val; else if (!m_borderBottom) m_borderBottom = val; else { ASSERT(!m_borderLeft); m_borderLeft = val; } m_allowBreak = m_allowRule = true; m_allowWidth = !m_borderLeft; } void commitRule(int keyword) { if (!m_horizontalRule) m_horizontalRule = keyword; else if (!m_verticalRule) m_verticalRule = keyword; m_allowRule = !m_verticalRule; } PassRefPtr<CSSValue> commitBorderImage(CSSParser* p, bool important) { // We need to clone and repeat values for any omissions. if (!m_right) { m_right = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType()); m_bottom = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType()); m_left = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType()); } if (!m_bottom) { m_bottom = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType()); m_left = m_primitiveValueCache->createValue(m_right->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_right->primitiveType()); } if (!m_left) m_left = m_primitiveValueCache->createValue(m_right->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_right->primitiveType()); // Now build a rect value to hold all four of our primitive values. RefPtr<Rect> rect = Rect::create(); rect->setTop(m_top); rect->setRight(m_right); rect->setBottom(m_bottom); rect->setLeft(m_left); // Fill in STRETCH as the default if it wasn't specified. if (!m_horizontalRule) m_horizontalRule = CSSValueStretch; // The vertical rule should match the horizontal rule if unspecified. if (!m_verticalRule) m_verticalRule = m_horizontalRule; // Now we have to deal with the border widths. The best way to deal with these is to actually put these values into a value // list and then make our parsing machinery do the parsing. if (m_borderTop) { CSSParserValueList newList; newList.addValue(*m_borderTop); if (m_borderRight) newList.addValue(*m_borderRight); if (m_borderBottom) newList.addValue(*m_borderBottom); if (m_borderLeft) newList.addValue(*m_borderLeft); CSSParserValueList* oldList = p->m_valueList; p->m_valueList = &newList; p->parseValue(CSSPropertyBorderWidth, important); p->m_valueList = oldList; } // Make our new border image value now. return CSSBorderImageValue::create(m_image, rect.release(), m_horizontalRule, m_verticalRule); } CSSPrimitiveValueCache* m_primitiveValueCache; bool m_allowBreak; bool m_allowNumber; bool m_allowSlash; bool m_allowWidth; bool m_allowRule; RefPtr<CSSValue> m_image; RefPtr<CSSPrimitiveValue> m_top; RefPtr<CSSPrimitiveValue> m_right; RefPtr<CSSPrimitiveValue> m_bottom; RefPtr<CSSPrimitiveValue> m_left; CSSParserValue* m_borderTop; CSSParserValue* m_borderRight; CSSParserValue* m_borderBottom; CSSParserValue* m_borderLeft; int m_horizontalRule; int m_verticalRule; }; bool CSSParser::parseBorderImage(int propId, bool important, RefPtr<CSSValue>& result) { // Look for an image initially. If the first value is not a URI, then we're done. BorderImageParseContext context(primitiveValueCache()); CSSParserValue* val = m_valueList->current(); if (val->unit == CSSPrimitiveValue::CSS_URI && m_styleSheet) { // FIXME: The completeURL call should be done when using the CSSImageValue, // not when creating it. context.commitImage(CSSImageValue::create(m_styleSheet->completeURL(val->string))); } else if (isGeneratedImageValue(val)) { RefPtr<CSSValue> value; if (parseGeneratedImage(value)) context.commitImage(value); else return false; } else return false; while ((val = m_valueList->next())) { if (context.allowNumber() && validUnit(val, FInteger | FNonNeg | FPercent, true)) { context.commitNumber(val); } else if (propId == CSSPropertyWebkitBorderImage && context.allowSlash() && val->unit == CSSParserValue::Operator && val->iValue == '/') { context.commitSlash(); } else if (context.allowWidth() && (val->id == CSSValueThin || val->id == CSSValueMedium || val->id == CSSValueThick || validUnit(val, FLength, m_strict))) { context.commitWidth(val); } else if (context.allowRule() && (val->id == CSSValueStretch || val->id == CSSValueRound || val->id == CSSValueRepeat)) { context.commitRule(val->id); } else { // Something invalid was encountered. return false; } } if (context.allowNumber() && propId != CSSPropertyWebkitBorderImage) { // Allow the slices to be omitted for images that don't fit to a border. We just set the slices to be 0. context.m_top = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_NUMBER); context.m_allowBreak = true; } if (context.allowBreak()) { // Need to fully commit as a single value. result = context.commitBorderImage(this, important); return true; } return false; } static void completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4]) { if (radii[3]) return; if (!radii[2]) { if (!radii[1]) radii[1] = radii[0]; radii[2] = radii[0]; } radii[3] = radii[1]; } bool CSSParser::parseBorderRadius(int propId, bool important) { unsigned num = m_valueList->size(); if (num > 9) return false; ShorthandScope scope(this, propId); RefPtr<CSSPrimitiveValue> radii[2][4]; unsigned indexAfterSlash = 0; for (unsigned i = 0; i < num; ++i) { CSSParserValue* value = m_valueList->valueAt(i); if (value->unit == CSSParserValue::Operator) { if (value->iValue != '/') return false; if (!i || indexAfterSlash || i + 1 == num || num > i + 5) return false; indexAfterSlash = i + 1; completeBorderRadii(radii[0]); continue; } if (i - indexAfterSlash >= 4) return false; if (!validUnit(value, FLength | FPercent, m_strict)) return false; RefPtr<CSSPrimitiveValue> radius = primitiveValueCache()->createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit)); if (!indexAfterSlash) { radii[0][i] = radius; // Legacy syntax: -webkit-border-radius: l1 l2; is equivalent to border-radius: l1 / l2; if (num == 2 && propId == CSSPropertyWebkitBorderRadius) { indexAfterSlash = 1; completeBorderRadii(radii[0]); } } else radii[1][i - indexAfterSlash] = radius.release(); } if (!indexAfterSlash) { completeBorderRadii(radii[0]); for (unsigned i = 0; i < 4; ++i) radii[1][i] = radii[0][i]; } else completeBorderRadii(radii[1]); m_implicitShorthand = true; addProperty(CSSPropertyBorderTopLeftRadius, primitiveValueCache()->createValue(Pair::create(radii[0][0].release(), radii[1][0].release())), important); addProperty(CSSPropertyBorderTopRightRadius, primitiveValueCache()->createValue(Pair::create(radii[0][1].release(), radii[1][1].release())), important); addProperty(CSSPropertyBorderBottomRightRadius, primitiveValueCache()->createValue(Pair::create(radii[0][2].release(), radii[1][2].release())), important); addProperty(CSSPropertyBorderBottomLeftRadius, primitiveValueCache()->createValue(Pair::create(radii[0][3].release(), radii[1][3].release())), important); m_implicitShorthand = false; return true; } bool CSSParser::parseCounter(int propId, int defaultValue, bool important) { enum { ID, VAL } state = ID; RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated(); RefPtr<CSSPrimitiveValue> counterName; while (true) { CSSParserValue* val = m_valueList->current(); switch (state) { case ID: if (val && val->unit == CSSPrimitiveValue::CSS_IDENT) { counterName = primitiveValueCache()->createValue(val->string, CSSPrimitiveValue::CSS_STRING); state = VAL; m_valueList->next(); continue; } break; case VAL: { int i = defaultValue; if (val && val->unit == CSSPrimitiveValue::CSS_NUMBER) { i = clampToInteger(val->fValue); m_valueList->next(); } list->append(primitiveValueCache()->createValue(Pair::create(counterName.release(), primitiveValueCache()->createValue(i, CSSPrimitiveValue::CSS_NUMBER)))); state = ID; continue; } } break; } if (list->length() > 0) { addProperty(propId, list.release(), important); return true; } return false; } // This should go away once we drop support for -webkit-gradient static PassRefPtr<CSSPrimitiveValue> parseDeprecatedGradientPoint(CSSParserValue* a, bool horizontal, CSSPrimitiveValueCache* primitiveValueCache) { RefPtr<CSSPrimitiveValue> result; if (a->unit == CSSPrimitiveValue::CSS_IDENT) { if ((equalIgnoringCase(a->string, "left") && horizontal) || (equalIgnoringCase(a->string, "top") && !horizontal)) result = primitiveValueCache->createValue(0., CSSPrimitiveValue::CSS_PERCENTAGE); else if ((equalIgnoringCase(a->string, "right") && horizontal) || (equalIgnoringCase(a->string, "bottom") && !horizontal)) result = primitiveValueCache->createValue(100., CSSPrimitiveValue::CSS_PERCENTAGE); else if (equalIgnoringCase(a->string, "center")) result = primitiveValueCache->createValue(50., CSSPrimitiveValue::CSS_PERCENTAGE); } else if (a->unit == CSSPrimitiveValue::CSS_NUMBER || a->unit == CSSPrimitiveValue::CSS_PERCENTAGE) result = primitiveValueCache->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit); return result; } static bool parseDeprecatedGradientColorStop(CSSParser* p, CSSParserValue* a, CSSGradientColorStop& stop) { if (a->unit != CSSParserValue::Function) return false; if (!equalIgnoringCase(a->function->name, "from(") && !equalIgnoringCase(a->function->name, "to(") && !equalIgnoringCase(a->function->name, "color-stop(")) return false; CSSParserValueList* args = a->function->args.get(); if (!args) return false; if (equalIgnoringCase(a->function->name, "from(") || equalIgnoringCase(a->function->name, "to(")) { // The "from" and "to" stops expect 1 argument. if (args->size() != 1) return false; if (equalIgnoringCase(a->function->name, "from(")) stop.m_position = p->primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_NUMBER); else stop.m_position = p->primitiveValueCache()->createValue(1, CSSPrimitiveValue::CSS_NUMBER); int id = args->current()->id; if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu) stop.m_color = p->primitiveValueCache()->createIdentifierValue(id); else stop.m_color = p->parseColor(args->current()); if (!stop.m_color) return false; } // The "color-stop" function expects 3 arguments. if (equalIgnoringCase(a->function->name, "color-stop(")) { if (args->size() != 3) return false; CSSParserValue* stopArg = args->current(); if (stopArg->unit == CSSPrimitiveValue::CSS_PERCENTAGE) stop.m_position = p->primitiveValueCache()->createValue(stopArg->fValue / 100, CSSPrimitiveValue::CSS_NUMBER); else if (stopArg->unit == CSSPrimitiveValue::CSS_NUMBER) stop.m_position = p->primitiveValueCache()->createValue(stopArg->fValue, CSSPrimitiveValue::CSS_NUMBER); else return false; stopArg = args->next(); if (stopArg->unit != CSSParserValue::Operator || stopArg->iValue != ',') return false; stopArg = args->next(); int id = stopArg->id; if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu) stop.m_color = p->primitiveValueCache()->createIdentifierValue(id); else stop.m_color = p->parseColor(stopArg); if (!stop.m_color) return false; } return true; } bool CSSParser::parseDeprecatedGradient(RefPtr<CSSValue>& gradient) { // Walk the arguments. CSSParserValueList* args = m_valueList->current()->function->args.get(); if (!args || args->size() == 0) return false; // The first argument is the gradient type. It is an identifier. CSSGradientType gradientType; CSSParserValue* a = args->current(); if (!a || a->unit != CSSPrimitiveValue::CSS_IDENT) return false; if (equalIgnoringCase(a->string, "linear")) gradientType = CSSLinearGradient; else if (equalIgnoringCase(a->string, "radial")) gradientType = CSSRadialGradient; else return false; RefPtr<CSSGradientValue> result; switch (gradientType) { case CSSLinearGradient: result = CSSLinearGradientValue::create(NonRepeating, true); break; case CSSRadialGradient: result = CSSRadialGradientValue::create(NonRepeating, true); break; } // Comma. a = args->next(); if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',') return false; // Next comes the starting point for the gradient as an x y pair. There is no // comma between the x and the y values. // First X. It can be left, right, number or percent. a = args->next(); if (!a) return false; RefPtr<CSSPrimitiveValue> point = parseDeprecatedGradientPoint(a, true, primitiveValueCache()); if (!point) return false; result->setFirstX(point.release()); // First Y. It can be top, bottom, number or percent. a = args->next(); if (!a) return false; point = parseDeprecatedGradientPoint(a, false, primitiveValueCache()); if (!point) return false; result->setFirstY(point.release()); // Comma after the first point. a = args->next(); if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',') return false; // For radial gradients only, we now expect a numeric radius. if (gradientType == CSSRadialGradient) { a = args->next(); if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER) return false; static_cast<CSSRadialGradientValue*>(result.get())->setFirstRadius(primitiveValueCache()->createValue(a->fValue, CSSPrimitiveValue::CSS_NUMBER)); // Comma after the first radius. a = args->next(); if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',') return false; } // Next is the ending point for the gradient as an x, y pair. // Second X. It can be left, right, number or percent. a = args->next(); if (!a) return false; point = parseDeprecatedGradientPoint(a, true, primitiveValueCache()); if (!point) return false; result->setSecondX(point.release()); // Second Y. It can be top, bottom, number or percent. a = args->next(); if (!a) return false; point = parseDeprecatedGradientPoint(a, false, primitiveValueCache()); if (!point) return false; result->setSecondY(point.release()); // For radial gradients only, we now expect the second radius. if (gradientType == CSSRadialGradient) { // Comma after the second point. a = args->next(); if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',') return false; a = args->next(); if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER) return false; static_cast<CSSRadialGradientValue*>(result.get())->setSecondRadius(primitiveValueCache()->createValue(a->fValue, CSSPrimitiveValue::CSS_NUMBER)); } // We now will accept any number of stops (0 or more). a = args->next(); while (a) { // Look for the comma before the next stop. if (a->unit != CSSParserValue::Operator || a->iValue != ',') return false; // Now examine the stop itself. a = args->next(); if (!a) return false; // The function name needs to be one of "from", "to", or "color-stop." CSSGradientColorStop stop; if (!parseDeprecatedGradientColorStop(this, a, stop)) return false; result->addStop(stop); // Advance a = args->next(); } gradient = result.release(); return true; } static PassRefPtr<CSSPrimitiveValue> valueFromSideKeyword(CSSParserValue* a, bool& isHorizontal, CSSPrimitiveValueCache* primitiveValueCache) { if (a->unit != CSSPrimitiveValue::CSS_IDENT) return 0; switch (a->id) { case CSSValueLeft: case CSSValueRight: isHorizontal = true; break; case CSSValueTop: case CSSValueBottom: isHorizontal = false; break; default: return 0; } return primitiveValueCache->createIdentifierValue(a->id); } static PassRefPtr<CSSPrimitiveValue> parseGradientColorOrKeyword(CSSParser* p, CSSParserValue* value) { int id = value->id; if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu) return p->primitiveValueCache()->createIdentifierValue(id); return p->parseColor(value); } bool CSSParser::parseLinearGradient(RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating) { RefPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating); // Walk the arguments. CSSParserValueList* args = m_valueList->current()->function->args.get(); if (!args || !args->size()) return false; CSSParserValue* a = args->current(); if (!a) return false; bool expectComma = false; // Look for angle. if (validUnit(a, FAngle, true)) { result->setAngle(primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit)); a = args->next(); expectComma = true; } else { // Look one or two optional keywords that indicate a side or corner. RefPtr<CSSPrimitiveValue> startX, startY; RefPtr<CSSPrimitiveValue> location; bool isHorizontal = false; if ((location = valueFromSideKeyword(a, isHorizontal, primitiveValueCache()))) { if (isHorizontal) startX = location; else startY = location; a = args->next(); if (a) { if ((location = valueFromSideKeyword(a, isHorizontal, primitiveValueCache()))) { if (isHorizontal) { if (startX) return false; startX = location; } else { if (startY) return false; startY = location; } a = args->next(); } } expectComma = true; } if (!startX && !startY) startY = primitiveValueCache()->createIdentifierValue(CSSValueTop); result->setFirstX(startX.release()); result->setFirstY(startY.release()); } if (!parseGradientColorStops(args, result.get(), expectComma)) return false; Vector<CSSGradientColorStop>& stops = result->stops(); if (stops.isEmpty()) return false; gradient = result.release(); return true; } bool CSSParser::parseRadialGradient(RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating) { RefPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating); // Walk the arguments. CSSParserValueList* args = m_valueList->current()->function->args.get(); if (!args || !args->size()) return false; CSSParserValue* a = args->current(); if (!a) return false; bool expectComma = false; // Optional background-position RefPtr<CSSValue> centerX; RefPtr<CSSValue> centerY; // parseFillPosition advances the args next pointer. parseFillPosition(args, centerX, centerY); a = args->current(); if (!a) return false; if (centerX || centerY) { // Comma if (a->unit != CSSParserValue::Operator || a->iValue != ',') return false; a = args->next(); if (!a) return false; } ASSERT(!centerX || centerX->isPrimitiveValue()); ASSERT(!centerY || centerY->isPrimitiveValue()); result->setFirstX(static_cast<CSSPrimitiveValue*>(centerX.get())); result->setSecondX(static_cast<CSSPrimitiveValue*>(centerX.get())); // CSS3 radial gradients always share the same start and end point. result->setFirstY(static_cast<CSSPrimitiveValue*>(centerY.get())); result->setSecondY(static_cast<CSSPrimitiveValue*>(centerY.get())); RefPtr<CSSPrimitiveValue> shapeValue; RefPtr<CSSPrimitiveValue> sizeValue; // Optional shape and/or size in any order. for (int i = 0; i < 2; ++i) { if (a->unit != CSSPrimitiveValue::CSS_IDENT) break; bool foundValue = false; switch (a->id) { case CSSValueCircle: case CSSValueEllipse: shapeValue = primitiveValueCache()->createIdentifierValue(a->id); foundValue = true; break; case CSSValueClosestSide: case CSSValueClosestCorner: case CSSValueFarthestSide: case CSSValueFarthestCorner: case CSSValueContain: case CSSValueCover: sizeValue = primitiveValueCache()->createIdentifierValue(a->id); foundValue = true; break; } if (foundValue) { a = args->next(); if (!a) return false; expectComma = true; } } result->setShape(shapeValue); result->setSizingBehavior(sizeValue); // Or, two lengths or percentages RefPtr<CSSPrimitiveValue> horizontalSize; RefPtr<CSSPrimitiveValue> verticalSize; if (!shapeValue && !sizeValue) { if (validUnit(a, FLength | FPercent, m_strict)) { horizontalSize = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit); a = args->next(); if (!a) return false; expectComma = true; } if (validUnit(a, FLength | FPercent, m_strict)) { verticalSize = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit); a = args->next(); if (!a) return false; expectComma = true; } } // Must have neither or both. if (!horizontalSize != !verticalSize) return false; result->setEndHorizontalSize(horizontalSize); result->setEndVerticalSize(verticalSize); if (!parseGradientColorStops(args, result.get(), expectComma)) return false; gradient = result.release(); return true; } bool CSSParser::parseGradientColorStops(CSSParserValueList* valueList, CSSGradientValue* gradient, bool expectComma) { CSSParserValue* a = valueList->current(); // Now look for color stops. while (a) { // Look for the comma before the next stop. if (expectComma) { if (a->unit != CSSParserValue::Operator || a->iValue != ',') return false; a = valueList->next(); if (!a) return false; } // <color-stop> = <color> [ <percentage> | <length> ]? CSSGradientColorStop stop; stop.m_color = parseGradientColorOrKeyword(this, a); if (!stop.m_color) return false; a = valueList->next(); if (a) { if (validUnit(a, FLength | FPercent, m_strict)) { stop.m_position = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit); a = valueList->next(); } } gradient->addStop(stop); expectComma = true; } // Must have 2 or more stops to be valid. return gradient->stops().size() > 1; } bool CSSParser::isGeneratedImageValue(CSSParserValue* val) const { if (val->unit != CSSParserValue::Function) return false; return equalIgnoringCase(val->function->name, "-webkit-gradient(") || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(") || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(") || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(") || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(") || equalIgnoringCase(val->function->name, "-webkit-canvas("); } bool CSSParser::parseGeneratedImage(RefPtr<CSSValue>& value) { CSSParserValue* val = m_valueList->current(); if (val->unit != CSSParserValue::Function) return false; if (equalIgnoringCase(val->function->name, "-webkit-gradient(")) return parseDeprecatedGradient(value); if (equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")) return parseLinearGradient(value, NonRepeating); if (equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")) return parseLinearGradient(value, Repeating); if (equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")) return parseRadialGradient(value, NonRepeating); if (equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")) return parseRadialGradient(value, Repeating); if (equalIgnoringCase(val->function->name, "-webkit-canvas(")) return parseCanvas(value); return false; } bool CSSParser::parseCanvas(RefPtr<CSSValue>& canvas) { RefPtr<CSSCanvasValue> result = CSSCanvasValue::create(); // Walk the arguments. CSSParserValueList* args = m_valueList->current()->function->args.get(); if (!args || args->size() != 1) return false; // The first argument is the canvas name. It is an identifier. CSSParserValue* a = args->current(); if (!a || a->unit != CSSPrimitiveValue::CSS_IDENT) return false; result->setName(a->string); canvas = result; return true; } class TransformOperationInfo { public: TransformOperationInfo(const CSSParserString& name) : m_type(WebKitCSSTransformValue::UnknownTransformOperation) , m_argCount(1) , m_allowSingleArgument(false) , m_unit(CSSParser::FUnknown) { if (equalIgnoringCase(name, "scale(") || equalIgnoringCase(name, "scalex(") || equalIgnoringCase(name, "scaley(") || equalIgnoringCase(name, "scalez(")) { m_unit = CSSParser::FNumber; if (equalIgnoringCase(name, "scale(")) m_type = WebKitCSSTransformValue::ScaleTransformOperation; else if (equalIgnoringCase(name, "scalex(")) m_type = WebKitCSSTransformValue::ScaleXTransformOperation; else if (equalIgnoringCase(name, "scaley(")) m_type = WebKitCSSTransformValue::ScaleYTransformOperation; else m_type = WebKitCSSTransformValue::ScaleZTransformOperation; } else if (equalIgnoringCase(name, "scale3d(")) { m_type = WebKitCSSTransformValue::Scale3DTransformOperation; m_argCount = 5; m_unit = CSSParser::FNumber; } else if (equalIgnoringCase(name, "rotate(")) { m_type = WebKitCSSTransformValue::RotateTransformOperation; m_unit = CSSParser::FAngle; } else if (equalIgnoringCase(name, "rotatex(") || equalIgnoringCase(name, "rotatey(") || equalIgnoringCase(name, "rotatez(")) { m_unit = CSSParser::FAngle; if (equalIgnoringCase(name, "rotatex(")) m_type = WebKitCSSTransformValue::RotateXTransformOperation; else if (equalIgnoringCase(name, "rotatey(")) m_type = WebKitCSSTransformValue::RotateYTransformOperation; else m_type = WebKitCSSTransformValue::RotateZTransformOperation; } else if (equalIgnoringCase(name, "rotate3d(")) { m_type = WebKitCSSTransformValue::Rotate3DTransformOperation; m_argCount = 7; m_unit = CSSParser::FNumber; } else if (equalIgnoringCase(name, "skew(") || equalIgnoringCase(name, "skewx(") || equalIgnoringCase(name, "skewy(")) { m_unit = CSSParser::FAngle; if (equalIgnoringCase(name, "skew(")) m_type = WebKitCSSTransformValue::SkewTransformOperation; else if (equalIgnoringCase(name, "skewx(")) m_type = WebKitCSSTransformValue::SkewXTransformOperation; else m_type = WebKitCSSTransformValue::SkewYTransformOperation; } else if (equalIgnoringCase(name, "translate(") || equalIgnoringCase(name, "translatex(") || equalIgnoringCase(name, "translatey(") || equalIgnoringCase(name, "translatez(")) { m_unit = CSSParser::FLength | CSSParser::FPercent; if (equalIgnoringCase(name, "translate(")) m_type = WebKitCSSTransformValue::TranslateTransformOperation; else if (equalIgnoringCase(name, "translatex(")) m_type = WebKitCSSTransformValue::TranslateXTransformOperation; else if (equalIgnoringCase(name, "translatey(")) m_type = WebKitCSSTransformValue::TranslateYTransformOperation; else m_type = WebKitCSSTransformValue::TranslateZTransformOperation; } else if (equalIgnoringCase(name, "translate3d(")) { m_type = WebKitCSSTransformValue::Translate3DTransformOperation; m_argCount = 5; m_unit = CSSParser::FLength | CSSParser::FPercent; } else if (equalIgnoringCase(name, "matrix(")) { m_type = WebKitCSSTransformValue::MatrixTransformOperation; m_argCount = 11; m_unit = CSSParser::FNumber; } else if (equalIgnoringCase(name, "matrix3d(")) { m_type = WebKitCSSTransformValue::Matrix3DTransformOperation; m_argCount = 31; m_unit = CSSParser::FNumber; } else if (equalIgnoringCase(name, "perspective(")) { m_type = WebKitCSSTransformValue::PerspectiveTransformOperation; m_unit = CSSParser::FNumber; } if (equalIgnoringCase(name, "scale(") || equalIgnoringCase(name, "skew(") || equalIgnoringCase(name, "translate(")) { m_allowSingleArgument = true; m_argCount = 3; } } WebKitCSSTransformValue::TransformOperationType type() const { return m_type; } unsigned argCount() const { return m_argCount; } CSSParser::Units unit() const { return m_unit; } bool unknown() const { return m_type == WebKitCSSTransformValue::UnknownTransformOperation; } bool hasCorrectArgCount(unsigned argCount) { return m_argCount == argCount || (m_allowSingleArgument && argCount == 1); } private: WebKitCSSTransformValue::TransformOperationType m_type; unsigned m_argCount; bool m_allowSingleArgument; CSSParser::Units m_unit; }; PassRefPtr<CSSValueList> CSSParser::parseTransform() { if (!m_valueList) return 0; // The transform is a list of functional primitives that specify transform operations. // We collect a list of WebKitCSSTransformValues, where each value specifies a single operation. RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated(); for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) { if (value->unit != CSSParserValue::Function || !value->function) return 0; // Every primitive requires at least one argument. CSSParserValueList* args = value->function->args.get(); if (!args) return 0; // See if the specified primitive is one we understand. TransformOperationInfo info(value->function->name); if (info.unknown()) return 0; if (!info.hasCorrectArgCount(args->size())) return 0; // Create the new WebKitCSSTransformValue for this operation and add it to our list. RefPtr<WebKitCSSTransformValue> transformValue = WebKitCSSTransformValue::create(info.type()); list->append(transformValue); // Snag our values. CSSParserValue* a = args->current(); unsigned argNumber = 0; while (a) { CSSParser::Units unit = info.unit(); if (info.type() == WebKitCSSTransformValue::Rotate3DTransformOperation && argNumber == 3) { // 4th param of rotate3d() is an angle rather than a bare number, validate it as such if (!validUnit(a, FAngle, true)) return 0; } else if (info.type() == WebKitCSSTransformValue::Translate3DTransformOperation && argNumber == 2) { // 3rd param of translate3d() cannot be a percentage if (!validUnit(a, FLength, true)) return 0; } else if (info.type() == WebKitCSSTransformValue::TranslateZTransformOperation && argNumber == 0) { // 1st param of translateZ() cannot be a percentage if (!validUnit(a, FLength, true)) return 0; } else if (info.type() == WebKitCSSTransformValue::PerspectiveTransformOperation && argNumber == 0) { // 1st param of perspective() must be a non-negative number (deprecated) or length. if (!validUnit(a, FNumber | FLength | FNonNeg, true)) return 0; } else if (!validUnit(a, unit, true)) return 0; // Add the value to the current transform operation. transformValue->append(primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit)); a = args->next(); if (!a) break; if (a->unit != CSSParserValue::Operator || a->iValue != ',') return 0; a = args->next(); argNumber++; } } return list.release(); } bool CSSParser::parseTransformOrigin(int propId, int& propId1, int& propId2, int& propId3, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3) { propId1 = propId; propId2 = propId; propId3 = propId; if (propId == CSSPropertyWebkitTransformOrigin) { propId1 = CSSPropertyWebkitTransformOriginX; propId2 = CSSPropertyWebkitTransformOriginY; propId3 = CSSPropertyWebkitTransformOriginZ; } switch (propId) { case CSSPropertyWebkitTransformOrigin: if (!parseTransformOriginShorthand(value, value2, value3)) return false; // parseTransformOriginShorthand advances the m_valueList pointer break; case CSSPropertyWebkitTransformOriginX: { value = parseFillPositionX(m_valueList); if (value) m_valueList->next(); break; } case CSSPropertyWebkitTransformOriginY: { value = parseFillPositionY(m_valueList); if (value) m_valueList->next(); break; } case CSSPropertyWebkitTransformOriginZ: { if (validUnit(m_valueList->current(), FLength, m_strict)) value = primitiveValueCache()->createValue(m_valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)m_valueList->current()->unit); if (value) m_valueList->next(); break; } } return value; } bool CSSParser::parsePerspectiveOrigin(int propId, int& propId1, int& propId2, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2) { propId1 = propId; propId2 = propId; if (propId == CSSPropertyWebkitPerspectiveOrigin) { propId1 = CSSPropertyWebkitPerspectiveOriginX; propId2 = CSSPropertyWebkitPerspectiveOriginY; } switch (propId) { case CSSPropertyWebkitPerspectiveOrigin: parseFillPosition(m_valueList, value, value2); break; case CSSPropertyWebkitPerspectiveOriginX: { value = parseFillPositionX(m_valueList); if (value) m_valueList->next(); break; } case CSSPropertyWebkitPerspectiveOriginY: { value = parseFillPositionY(m_valueList); if (value) m_valueList->next(); break; } } return value; } bool CSSParser::parseTextEmphasisStyle(bool important) { unsigned valueListSize = m_valueList->size(); RefPtr<CSSPrimitiveValue> fill; RefPtr<CSSPrimitiveValue> shape; for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) { if (value->unit == CSSPrimitiveValue::CSS_STRING) { if (fill || shape || (valueListSize != 1 && !inShorthand())) return false; addProperty(CSSPropertyWebkitTextEmphasisStyle, primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING), important); m_valueList->next(); return true; } if (value->id == CSSValueNone) { if (fill || shape || (valueListSize != 1 && !inShorthand())) return false; addProperty(CSSPropertyWebkitTextEmphasisStyle, primitiveValueCache()->createIdentifierValue(CSSValueNone), important); m_valueList->next(); return true; } if (value->id == CSSValueOpen || value->id == CSSValueFilled) { if (fill) return false; fill = primitiveValueCache()->createIdentifierValue(value->id); } else if (value->id == CSSValueDot || value->id == CSSValueCircle || value->id == CSSValueDoubleCircle || value->id == CSSValueTriangle || value->id == CSSValueSesame) { if (shape) return false; shape = primitiveValueCache()->createIdentifierValue(value->id); } else if (!inShorthand()) return false; else break; } if (fill && shape) { RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated(); parsedValues->append(fill.release()); parsedValues->append(shape.release()); addProperty(CSSPropertyWebkitTextEmphasisStyle, parsedValues.release(), important); return true; } if (fill) { addProperty(CSSPropertyWebkitTextEmphasisStyle, fill.release(), important); return true; } if (shape) { addProperty(CSSPropertyWebkitTextEmphasisStyle, shape.release(), important); return true; } return false; } bool CSSParser::parseLineBoxContain(bool important) { LineBoxContain lineBoxContain = LineBoxContainNone; for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) { if (value->id == CSSValueBlock) { if (lineBoxContain & LineBoxContainBlock) return false; lineBoxContain |= LineBoxContainBlock; } else if (value->id == CSSValueInline) { if (lineBoxContain & LineBoxContainInline) return false; lineBoxContain |= LineBoxContainInline; } else if (value->id == CSSValueFont) { if (lineBoxContain & LineBoxContainFont) return false; lineBoxContain |= LineBoxContainFont; } else if (value->id == CSSValueGlyphs) { if (lineBoxContain & LineBoxContainGlyphs) return false; lineBoxContain |= LineBoxContainGlyphs; } else if (value->id == CSSValueReplaced) { if (lineBoxContain & LineBoxContainReplaced) return false; lineBoxContain |= LineBoxContainReplaced; } else if (value->id == CSSValueInlineBox) { if (lineBoxContain & LineBoxContainInlineBox) return false; lineBoxContain |= LineBoxContainInlineBox; } else return false; } if (!lineBoxContain) return false; addProperty(CSSPropertyWebkitLineBoxContain, CSSLineBoxContainValue::create(lineBoxContain), important); return true; } static inline int yyerror(const char*) { return 1; } #define END_TOKEN 0 #include "CSSGrammar.h" int CSSParser::lex(void* yylvalWithoutType) { YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType); int length; lex(); UChar* t = text(&length); switch (token()) { case WHITESPACE: case SGML_CD: case INCLUDES: case DASHMATCH: break; case URI: case STRING: case IDENT: case NTH: case HEX: case IDSEL: case DIMEN: case UNICODERANGE: case FUNCTION: case ANYFUNCTION: case NOTFUNCTION: case CALCFUNCTION: case MINFUNCTION: case MAXFUNCTION: yylval->string.characters = t; yylval->string.length = length; break; case IMPORT_SYM: case PAGE_SYM: case MEDIA_SYM: case FONT_FACE_SYM: case CHARSET_SYM: case NAMESPACE_SYM: case WEBKIT_KEYFRAMES_SYM: case IMPORTANT_SYM: break; case QEMS: length--; case GRADS: case TURNS: length--; case DEGS: case RADS: case KHERTZ: case REMS: length--; case MSECS: case HERTZ: case EMS: case EXS: case PXS: case CMS: case MMS: case INS: case PTS: case PCS: length--; case SECS: case PERCENTAGE: length--; case FLOATTOKEN: case INTEGER: yylval->number = charactersToDouble(t, length); break; default: break; } return token(); } void CSSParser::recheckAtKeyword(const UChar* str, int len) { String ruleName(str, len); if (equalIgnoringCase(ruleName, "@import")) yyTok = IMPORT_SYM; else if (equalIgnoringCase(ruleName, "@page")) yyTok = PAGE_SYM; else if (equalIgnoringCase(ruleName, "@media")) yyTok = MEDIA_SYM; else if (equalIgnoringCase(ruleName, "@font-face")) yyTok = FONT_FACE_SYM; else if (equalIgnoringCase(ruleName, "@charset")) yyTok = CHARSET_SYM; else if (equalIgnoringCase(ruleName, "@namespace")) yyTok = NAMESPACE_SYM; else if (equalIgnoringCase(ruleName, "@-webkit-keyframes")) yyTok = WEBKIT_KEYFRAMES_SYM; else if (equalIgnoringCase(ruleName, "@-webkit-mediaquery")) yyTok = WEBKIT_MEDIAQUERY_SYM; } UChar* CSSParser::text(int *length) { UChar* start = yytext; int l = yyleng; switch (yyTok) { case STRING: l--; /* nobreak */ case HEX: case IDSEL: start++; l--; break; case URI: // "url("{w}{string}{w}")" // "url("{w}{url}{w}")" // strip "url(" and ")" start += 4; l -= 5; // strip {w} while (l && isHTMLSpace(*start)) { ++start; --l; } while (l && isHTMLSpace(start[l - 1])) --l; if (l && (*start == '"' || *start == '\'')) { ASSERT(l >= 2 && start[l - 1] == *start); ++start; l -= 2; } break; default: break; } // process escapes UChar* out = start; UChar* escape = 0; bool sawEscape = false; for (int i = 0; i < l; i++) { UChar* current = start + i; if (escape == current - 1) { if (isASCIIHexDigit(*current)) continue; if (yyTok == STRING && (*current == '\n' || *current == '\r' || *current == '\f')) { // ### handle \r\n case if (*current != '\r') escape = 0; continue; } // in all other cases copy the char to output // ### *out++ = *current; escape = 0; continue; } if (escape == current - 2 && yyTok == STRING && *(current-1) == '\r' && *current == '\n') { escape = 0; continue; } if (escape > current - 7 && isASCIIHexDigit(*current)) continue; if (escape) { // add escaped char unsigned uc = 0; escape++; while (escape < current) { uc *= 16; uc += toASCIIHexValue(*escape); escape++; } // can't handle chars outside ucs2 if (uc > 0xffff) uc = 0xfffd; *out++ = uc; escape = 0; if (isHTMLSpace(*current)) continue; } if (!escape && *current == '\\') { escape = current; sawEscape = true; continue; } *out++ = *current; } if (escape) { // add escaped char unsigned uc = 0; escape++; while (escape < start+l) { uc *= 16; uc += toASCIIHexValue(*escape); escape++; } // can't handle chars outside ucs2 if (uc > 0xffff) uc = 0xfffd; *out++ = uc; } *length = out - start; // If we have an unrecognized @-keyword, and if we handled any escapes at all, then // we should attempt to adjust yyTok to the correct type. if (yyTok == ATKEYWORD && sawEscape) recheckAtKeyword(start, *length); return start; } void CSSParser::countLines() { for (UChar* current = yytext; current < yytext + yyleng; ++current) { if (*current == '\n') ++m_lineNumber; } } CSSParserSelector* CSSParser::createFloatingSelector() { CSSParserSelector* selector = new CSSParserSelector; m_floatingSelectors.add(selector); return selector; } PassOwnPtr<CSSParserSelector> CSSParser::sinkFloatingSelector(CSSParserSelector* selector) { if (selector) { ASSERT(m_floatingSelectors.contains(selector)); m_floatingSelectors.remove(selector); } return adoptPtr(selector); } Vector<OwnPtr<CSSParserSelector> >* CSSParser::createFloatingSelectorVector() { Vector<OwnPtr<CSSParserSelector> >* selectorVector = new Vector<OwnPtr<CSSParserSelector> >; m_floatingSelectorVectors.add(selectorVector); return selectorVector; } PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > CSSParser::sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectorVector) { if (selectorVector) { ASSERT(m_floatingSelectorVectors.contains(selectorVector)); m_floatingSelectorVectors.remove(selectorVector); } return adoptPtr(selectorVector); } CSSParserValueList* CSSParser::createFloatingValueList() { CSSParserValueList* list = new CSSParserValueList; m_floatingValueLists.add(list); return list; } CSSParserValueList* CSSParser::sinkFloatingValueList(CSSParserValueList* list) { if (list) { ASSERT(m_floatingValueLists.contains(list)); m_floatingValueLists.remove(list); } return list; } CSSParserFunction* CSSParser::createFloatingFunction() { CSSParserFunction* function = new CSSParserFunction; m_floatingFunctions.add(function); return function; } CSSParserFunction* CSSParser::sinkFloatingFunction(CSSParserFunction* function) { if (function) { ASSERT(m_floatingFunctions.contains(function)); m_floatingFunctions.remove(function); } return function; } CSSParserValue& CSSParser::sinkFloatingValue(CSSParserValue& value) { if (value.unit == CSSParserValue::Function) { ASSERT(m_floatingFunctions.contains(value.function)); m_floatingFunctions.remove(value.function); } return value; } MediaQueryExp* CSSParser::createFloatingMediaQueryExp(const AtomicString& mediaFeature, CSSParserValueList* values) { m_floatingMediaQueryExp = MediaQueryExp::create(mediaFeature, values); return m_floatingMediaQueryExp.get(); } PassOwnPtr<MediaQueryExp> CSSParser::sinkFloatingMediaQueryExp(MediaQueryExp* expression) { ASSERT_UNUSED(expression, expression == m_floatingMediaQueryExp); return m_floatingMediaQueryExp.release(); } Vector<OwnPtr<MediaQueryExp> >* CSSParser::createFloatingMediaQueryExpList() { m_floatingMediaQueryExpList = adoptPtr(new Vector<OwnPtr<MediaQueryExp> >); return m_floatingMediaQueryExpList.get(); } PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > CSSParser::sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp> >* list) { ASSERT_UNUSED(list, list == m_floatingMediaQueryExpList); return m_floatingMediaQueryExpList.release(); } MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const String& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions) { m_floatingMediaQuery = adoptPtr(new MediaQuery(restrictor, mediaType, expressions)); return m_floatingMediaQuery.get(); } MediaQuery* CSSParser::createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions) { return createFloatingMediaQuery(MediaQuery::None, "all", expressions); } PassOwnPtr<MediaQuery> CSSParser::sinkFloatingMediaQuery(MediaQuery* query) { ASSERT_UNUSED(query, query == m_floatingMediaQuery); return m_floatingMediaQuery.release(); } MediaList* CSSParser::createMediaList() { RefPtr<MediaList> list = MediaList::create(); MediaList* result = list.get(); m_parsedStyleObjects.append(list.release()); return result; } CSSRule* CSSParser::createCharsetRule(const CSSParserString& charset) { if (!m_styleSheet) return 0; RefPtr<CSSCharsetRule> rule = CSSCharsetRule::create(m_styleSheet, charset); CSSCharsetRule* result = rule.get(); m_parsedStyleObjects.append(rule.release()); return result; } CSSRule* CSSParser::createImportRule(const CSSParserString& url, MediaList* media) { if (!media || !m_styleSheet || !m_allowImportRules) return 0; RefPtr<CSSImportRule> rule = CSSImportRule::create(m_styleSheet, url, media); CSSImportRule* result = rule.get(); m_parsedStyleObjects.append(rule.release()); return result; } CSSRule* CSSParser::createMediaRule(MediaList* media, CSSRuleList* rules) { if (!media || !rules || !m_styleSheet) return 0; m_allowImportRules = m_allowNamespaceDeclarations = false; RefPtr<CSSMediaRule> rule = CSSMediaRule::create(m_styleSheet, media, rules); CSSMediaRule* result = rule.get(); m_parsedStyleObjects.append(rule.release()); return result; } CSSRuleList* CSSParser::createRuleList() { RefPtr<CSSRuleList> list = CSSRuleList::create(); CSSRuleList* listPtr = list.get(); m_parsedRuleLists.append(list.release()); return listPtr; } WebKitCSSKeyframesRule* CSSParser::createKeyframesRule() { m_allowImportRules = m_allowNamespaceDeclarations = false; RefPtr<WebKitCSSKeyframesRule> rule = WebKitCSSKeyframesRule::create(m_styleSheet); WebKitCSSKeyframesRule* rulePtr = rule.get(); m_parsedStyleObjects.append(rule.release()); return rulePtr; } CSSRule* CSSParser::createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors) { CSSStyleRule* result = 0; markRuleBodyEnd(); if (selectors) { m_allowImportRules = m_allowNamespaceDeclarations = false; RefPtr<CSSStyleRule> rule = CSSStyleRule::create(m_styleSheet, m_lastSelectorLineNumber); rule->adoptSelectorVector(*selectors); if (m_hasFontFaceOnlyValues) deleteFontFaceOnlyValues(); rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties)); result = rule.get(); m_parsedStyleObjects.append(rule.release()); if (m_ruleRangeMap) { ASSERT(m_currentRuleData); m_currentRuleData->styleSourceData->styleBodyRange = m_ruleBodyRange; m_currentRuleData->selectorListRange = m_selectorListRange; m_ruleRangeMap->set(result, m_currentRuleData.release()); m_currentRuleData = CSSRuleSourceData::create(); m_currentRuleData->styleSourceData = CSSStyleSourceData::create(); m_inStyleRuleOrDeclaration = false; } } resetSelectorListMarks(); resetRuleBodyMarks(); clearProperties(); return result; } CSSRule* CSSParser::createFontFaceRule() { m_allowImportRules = m_allowNamespaceDeclarations = false; for (unsigned i = 0; i < m_numParsedProperties; ++i) { CSSProperty* property = m_parsedProperties[i]; int id = property->id(); if ((id == CSSPropertyFontWeight || id == CSSPropertyFontStyle || id == CSSPropertyFontVariant) && property->value()->isPrimitiveValue()) { RefPtr<CSSValue> value = property->m_value.release(); property->m_value = CSSValueList::createCommaSeparated(); static_cast<CSSValueList*>(property->value())->append(value.release()); } else if (id == CSSPropertyFontFamily && (!property->value()->isValueList() || static_cast<CSSValueList*>(property->value())->length() != 1)) { // Unlike font-family property, font-family descriptor in @font-face rule // has to be a value list with exactly one family name. It cannot have a // have 'initial' value and cannot 'inherit' from parent. // See http://dev.w3.org/csswg/css3-fonts/#font-family-desc clearProperties(); return 0; } } RefPtr<CSSFontFaceRule> rule = CSSFontFaceRule::create(m_styleSheet); rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties)); clearProperties(); CSSFontFaceRule* result = rule.get(); m_parsedStyleObjects.append(rule.release()); return result; } void CSSParser::addNamespace(const AtomicString& prefix, const AtomicString& uri) { if (!m_styleSheet || !m_allowNamespaceDeclarations) return; m_allowImportRules = false; m_styleSheet->addNamespace(this, prefix, uri); } void CSSParser::updateSpecifiersWithElementName(const AtomicString& namespacePrefix, const AtomicString& elementName, CSSParserSelector* specifiers) { AtomicString determinedNamespace = namespacePrefix != nullAtom && m_styleSheet ? m_styleSheet->determineNamespace(namespacePrefix) : m_defaultNamespace; QualifiedName tag = QualifiedName(namespacePrefix, elementName, determinedNamespace); if (!specifiers->isUnknownPseudoElement()) { specifiers->setTag(tag); return; } specifiers->setRelation(CSSSelector::ShadowDescendant); if (CSSParserSelector* history = specifiers->tagHistory()) { history->setTag(tag); return; } // No need to create an extra element name selector if we are matching any element // in any namespace. if (elementName == starAtom && m_defaultNamespace == starAtom) return; CSSParserSelector* elementNameSelector = new CSSParserSelector; elementNameSelector->setTag(tag); specifiers->setTagHistory(elementNameSelector); } CSSRule* CSSParser::createPageRule(PassOwnPtr<CSSParserSelector> pageSelector) { // FIXME: Margin at-rules are ignored. m_allowImportRules = m_allowNamespaceDeclarations = false; CSSPageRule* pageRule = 0; if (pageSelector) { RefPtr<CSSPageRule> rule = CSSPageRule::create(m_styleSheet, m_lastSelectorLineNumber); Vector<OwnPtr<CSSParserSelector> > selectorVector; selectorVector.append(pageSelector); rule->adoptSelectorVector(selectorVector); rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties)); pageRule = rule.get(); m_parsedStyleObjects.append(rule.release()); } clearProperties(); return pageRule; } CSSRule* CSSParser::createMarginAtRule(CSSSelector::MarginBoxType /* marginBox */) { // FIXME: Implement margin at-rule here, using: // - marginBox: margin box // - m_parsedProperties: properties at [m_numParsedPropertiesBeforeMarginBox, m_numParsedProperties) are for this at-rule. // Don't forget to also update the action for page symbol in CSSGrammar.y such that margin at-rule data is cleared if page_selector is invalid. endDeclarationsForMarginBox(); return 0; // until this method is implemented. } void CSSParser::startDeclarationsForMarginBox() { m_numParsedPropertiesBeforeMarginBox = m_numParsedProperties; } void CSSParser::endDeclarationsForMarginBox() { ASSERT(m_numParsedPropertiesBeforeMarginBox != INVALID_NUM_PARSED_PROPERTIES); rollbackLastProperties(m_numParsedProperties - m_numParsedPropertiesBeforeMarginBox); m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES; } void CSSParser::deleteFontFaceOnlyValues() { ASSERT(m_hasFontFaceOnlyValues); int deletedProperties = 0; for (unsigned i = 0; i < m_numParsedProperties; ++i) { CSSProperty* property = m_parsedProperties[i]; int id = property->id(); if ((id == CSSPropertyFontWeight || id == CSSPropertyFontStyle || id == CSSPropertyFontVariant) && property->value()->isValueList()) { delete property; deletedProperties++; } else if (deletedProperties) m_parsedProperties[i - deletedProperties] = m_parsedProperties[i]; } m_numParsedProperties -= deletedProperties; } WebKitCSSKeyframeRule* CSSParser::createKeyframeRule(CSSParserValueList* keys) { // Create a key string from the passed keys String keyString; for (unsigned i = 0; i < keys->size(); ++i) { float key = (float) keys->valueAt(i)->fValue; if (i != 0) keyString += ","; keyString += String::number(key); keyString += "%"; } RefPtr<WebKitCSSKeyframeRule> keyframe = WebKitCSSKeyframeRule::create(m_styleSheet); keyframe->setKeyText(keyString); keyframe->setDeclaration(CSSMutableStyleDeclaration::create(0, m_parsedProperties, m_numParsedProperties)); clearProperties(); WebKitCSSKeyframeRule* keyframePtr = keyframe.get(); m_parsedStyleObjects.append(keyframe.release()); return keyframePtr; } void CSSParser::invalidBlockHit() { if (m_styleSheet && !m_hadSyntacticallyValidCSSRule) m_styleSheet->setHasSyntacticallyValidCSSHeader(false); } void CSSParser::updateLastSelectorLineAndPosition() { m_lastSelectorLineNumber = m_lineNumber; markRuleBodyStart(); } void CSSParser::markSelectorListStart() { m_selectorListRange.start = yytext - m_data; } void CSSParser::markSelectorListEnd() { if (!m_currentRuleData) return; UChar* listEnd = yytext; while (listEnd > m_data + 1) { if (isHTMLSpace(*(listEnd - 1))) --listEnd; else break; } m_selectorListRange.end = listEnd - m_data; } void CSSParser::markRuleBodyStart() { unsigned offset = yytext - m_data; if (*yytext == '{') ++offset; // Skip the rule body opening brace. if (offset > m_ruleBodyRange.start) m_ruleBodyRange.start = offset; m_inStyleRuleOrDeclaration = true; } void CSSParser::markRuleBodyEnd() { unsigned offset = yytext - m_data; if (offset > m_ruleBodyRange.end) m_ruleBodyRange.end = offset; } void CSSParser::markPropertyStart() { if (!m_inStyleRuleOrDeclaration) return; m_propertyRange.start = yytext - m_data; } void CSSParser::markPropertyEnd(bool isImportantFound, bool isPropertyParsed) { if (!m_inStyleRuleOrDeclaration) return; unsigned offset = yytext - m_data; if (*yytext == ';') // Include semicolon into the property text. ++offset; m_propertyRange.end = offset; if (m_propertyRange.start != UINT_MAX && m_currentRuleData) { // This stuff is only executed when the style data retrieval is requested by client. const unsigned start = m_propertyRange.start; const unsigned end = m_propertyRange.end; ASSERT(start < end); String propertyString = String(m_data + start, end - start).stripWhiteSpace(); if (propertyString.endsWith(";", true)) propertyString = propertyString.left(propertyString.length() - 1); Vector<String> propertyComponents; size_t colonIndex = propertyString.find(":"); ASSERT(colonIndex != notFound); String name = propertyString.left(colonIndex).stripWhiteSpace(); String value = propertyString.substring(colonIndex + 1, propertyString.length()).stripWhiteSpace(); // The property range is relative to the declaration start offset. m_currentRuleData->styleSourceData->propertyData.append( CSSPropertySourceData(name, value, isImportantFound, isPropertyParsed, SourceRange(start - m_ruleBodyRange.start, end - m_ruleBodyRange.start))); } resetPropertyMarks(); } static int cssPropertyID(const UChar* propertyName, unsigned length) { if (!length) return 0; if (length > maxCSSPropertyNameLength) return 0; char buffer[maxCSSPropertyNameLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character for (unsigned i = 0; i != length; ++i) { UChar c = propertyName[i]; if (c == 0 || c >= 0x7F) return 0; // illegal character buffer[i] = toASCIILower(c); } buffer[length] = '\0'; const char* name = buffer; if (buffer[0] == '-') { // If the prefix is -apple- or -khtml-, change it to -webkit-. // This makes the string one character longer. if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) { memmove(buffer + 7, buffer + 6, length + 1 - 6); memcpy(buffer, "-webkit", 7); ++length; } if (hasPrefix(buffer, length, "-webkit")) { if (!strcmp(buffer, "-webkit-box-sizing")) { // -webkit-box-sizing worked in Safari 4 and earlier. const char* const boxSizing = "box-sizing"; name = boxSizing; length = strlen(boxSizing); } else if (!strcmp(buffer, "-webkit-opacity")) { // Honor -webkit-opacity as a synonym for opacity. // This was the only syntax that worked in Safari 1.1, and may be in use on some websites and widgets. const char* const opacity = "opacity"; name = opacity; length = strlen(opacity); #if PLATFORM(IOS) } else if (!strcmp(buffer, "-webkit-hyphenate-locale")) { // Worked in iOS 4.2. const char* const webkitLocale = "-webkit-locale"; name = webkitLocale; length = strlen(webkitLocale); #endif } else if (hasPrefix(buffer + 7, length - 7, "-border-")) { // -webkit-border-*-*-radius worked in Safari 4 and earlier. -webkit-border-radius syntax // differs from border-radius, so it is remains as a distinct property. if (!strcmp(buffer + 15, "top-left-radius") || !strcmp(buffer + 15, "top-right-radius") || !strcmp(buffer + 15, "bottom-right-radius") || !strcmp(buffer + 15, "bottom-left-radius")) { name = buffer + 8; length -= 8; } } } } const Property* hashTableEntry = findProperty(name, length); return hashTableEntry ? hashTableEntry->id : 0; } int cssPropertyID(const String& string) { return cssPropertyID(string.characters(), string.length()); } int cssPropertyID(const CSSParserString& string) { return cssPropertyID(string.characters, string.length); } int cssValueKeywordID(const CSSParserString& string) { unsigned length = string.length; if (!length) return 0; if (length > maxCSSValueKeywordLength) return 0; char buffer[maxCSSValueKeywordLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character for (unsigned i = 0; i != length; ++i) { UChar c = string.characters[i]; if (c == 0 || c >= 0x7F) return 0; // illegal character buffer[i] = WTF::toASCIILower(c); } buffer[length] = '\0'; if (buffer[0] == '-') { // If the prefix is -apple- or -khtml-, change it to -webkit-. // This makes the string one character longer. if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) { memmove(buffer + 7, buffer + 6, length + 1 - 6); memcpy(buffer, "-webkit", 7); ++length; } } const Value* hashTableEntry = findValue(buffer, length); return hashTableEntry ? hashTableEntry->id : 0; } // "ident" from the CSS tokenizer, minus backslash-escape sequences static bool isCSSTokenizerIdentifier(const String& string) { const UChar* p = string.characters(); const UChar* end = p + string.length(); // -? if (p != end && p[0] == '-') ++p; // {nmstart} if (p == end || !(p[0] == '_' || p[0] >= 128 || isASCIIAlpha(p[0]))) return false; ++p; // {nmchar}* for (; p != end; ++p) { if (!(p[0] == '_' || p[0] == '-' || p[0] >= 128 || isASCIIAlphanumeric(p[0]))) return false; } return true; } // "url" from the CSS tokenizer, minus backslash-escape sequences static bool isCSSTokenizerURL(const String& string) { const UChar* p = string.characters(); const UChar* end = p + string.length(); for (; p != end; ++p) { UChar c = p[0]; switch (c) { case '!': case '#': case '$': case '%': case '&': break; default: if (c < '*') return false; if (c <= '~') break; if (c < 128) return false; } } return true; } // We use single quotes for now because markup.cpp uses double quotes. String quoteCSSString(const String& string) { // For efficiency, we first pre-calculate the length of the quoted string, then we build the actual one. // Please see below for the actual logic. unsigned quotedStringSize = 2; // Two quotes surrounding the entire string. bool afterEscape = false; for (unsigned i = 0; i < string.length(); ++i) { UChar ch = string[i]; if (ch == '\\' || ch == '\'') { quotedStringSize += 2; afterEscape = false; } else if (ch < 0x20 || ch == 0x7F) { quotedStringSize += 2 + (ch >= 0x10); afterEscape = true; } else { quotedStringSize += 1 + (afterEscape && (isASCIIHexDigit(ch) || ch == ' ')); afterEscape = false; } } StringBuffer buffer(quotedStringSize); unsigned index = 0; buffer[index++] = '\''; afterEscape = false; for (unsigned i = 0; i < string.length(); ++i) { UChar ch = string[i]; if (ch == '\\' || ch == '\'') { buffer[index++] = '\\'; buffer[index++] = ch; afterEscape = false; } else if (ch < 0x20 || ch == 0x7F) { // Control characters. buffer[index++] = '\\'; placeByteAsHexCompressIfPossible(ch, buffer, index, Lowercase); afterEscape = true; } else { // Space character may be required to separate backslash-escape sequence and normal characters. if (afterEscape && (isASCIIHexDigit(ch) || ch == ' ')) buffer[index++] = ' '; buffer[index++] = ch; afterEscape = false; } } buffer[index++] = '\''; ASSERT(quotedStringSize == index); return String::adopt(buffer); } String quoteCSSStringIfNeeded(const String& string) { return isCSSTokenizerIdentifier(string) ? string : quoteCSSString(string); } String quoteCSSURLIfNeeded(const String& string) { return isCSSTokenizerURL(string) ? string : quoteCSSString(string); } bool isValidNthToken(const CSSParserString& token) { // The tokenizer checks for the construct of an+b. // nth can also accept "odd" or "even" but should not accept any other token. return equalIgnoringCase(token, "odd") || equalIgnoringCase(token, "even"); } #define YY_DECL int CSSParser::lex() #define yyconst const typedef int yy_state_type; typedef unsigned YY_CHAR; // The following line makes sure we treat non-Latin-1 Unicode characters correctly. #define YY_SC_TO_UI(c) (c > 0xff ? 0xff : c) #define YY_DO_BEFORE_ACTION \ yytext = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ yy_hold_char = *yy_cp; \ *yy_cp = 0; \ yy_c_buf_p = yy_cp; #define YY_BREAK break; #define ECHO #define YY_RULE_SETUP #define INITIAL 0 #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) #define yyterminate() yyTok = END_TOKEN; return yyTok #define YY_FATAL_ERROR(a) // The following line is needed to build the tokenizer with a condition stack. // The macro is used in the tokenizer grammar with lines containing // BEGIN(mediaqueries) and BEGIN(initial). yy_start acts as index to // tokenizer transition table, and 'mediaqueries' and 'initial' are // offset multipliers that specify which transitions are active // in the tokenizer during in each condition (tokenizer state). #define BEGIN yy_start = 1 + 2 * #include "tokenizer.cpp" }
apache-2.0
gorcz/Raigad
raigad/src/main/java/com/netflix/raigad/configuration/MemoryConfigSource.java
1133
/** * Copyright 2014 Netflix, Inc. * * 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 com.netflix.raigad.configuration; import com.google.common.collect.Maps; import java.util.Map; public final class MemoryConfigSource extends AbstractConfigSource { private final Map<String, String> data = Maps.newConcurrentMap(); @Override public int size() { return data.size(); } @Override public String get(final String key) { return data.get(key); } @Override public void set(final String key, final String value) { data.put(key, value); } }
apache-2.0
setjet/spark
core/src/test/scala/org/apache/spark/storage/ShuffleBlockFetcherIteratorSuite.scala
16486
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.storage import java.io.{File, InputStream, IOException} import java.util.concurrent.Semaphore import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import org.mockito.Matchers.{any, eq => meq} import org.mockito.Mockito._ import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import org.scalatest.PrivateMethodTester import org.apache.spark.{SparkFunSuite, TaskContext} import org.apache.spark.network._ import org.apache.spark.network.buffer.{FileSegmentManagedBuffer, ManagedBuffer} import org.apache.spark.network.shuffle.BlockFetchingListener import org.apache.spark.network.util.LimitedInputStream import org.apache.spark.shuffle.FetchFailedException class ShuffleBlockFetcherIteratorSuite extends SparkFunSuite with PrivateMethodTester { // Some of the tests are quite tricky because we are testing the cleanup behavior // in the presence of faults. /** Creates a mock [[BlockTransferService]] that returns data from the given map. */ private def createMockTransfer(data: Map[BlockId, ManagedBuffer]): BlockTransferService = { val transfer = mock(classOf[BlockTransferService]) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val blocks = invocation.getArguments()(3).asInstanceOf[Array[String]] val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] for (blockId <- blocks) { if (data.contains(BlockId(blockId))) { listener.onBlockFetchSuccess(blockId, data(BlockId(blockId))) } else { listener.onBlockFetchFailure(blockId, new BlockNotFoundException(blockId)) } } } }) transfer } // Create a mock managed buffer for testing def createMockManagedBuffer(): ManagedBuffer = { val mockManagedBuffer = mock(classOf[ManagedBuffer]) val in = mock(classOf[InputStream]) when(in.read(any())).thenReturn(1) when(in.read(any(), any(), any())).thenReturn(1) when(mockManagedBuffer.createInputStream()).thenReturn(in) mockManagedBuffer } test("successful 3 local reads + 2 remote reads") { val blockManager = mock(classOf[BlockManager]) val localBmId = BlockManagerId("test-client", "test-client", 1) doReturn(localBmId).when(blockManager).blockManagerId // Make sure blockManager.getBlockData would return the blocks val localBlocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 0, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 1, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 2, 0) -> createMockManagedBuffer()) localBlocks.foreach { case (blockId, buf) => doReturn(buf).when(blockManager).getBlockData(meq(blockId)) } // Make sure remote blocks would return val remoteBmId = BlockManagerId("test-client-1", "test-client-1", 2) val remoteBlocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 3, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 4, 0) -> createMockManagedBuffer()) val transfer = createMockTransfer(remoteBlocks) val blocksByAddress = Seq[(BlockManagerId, Seq[(BlockId, Long)])]( (localBmId, localBlocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq), (remoteBmId, remoteBlocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq) ) val iterator = new ShuffleBlockFetcherIterator( TaskContext.empty(), transfer, blockManager, blocksByAddress, (_, in) => in, 48 * 1024 * 1024, Int.MaxValue, true) // 3 local blocks fetched in initialization verify(blockManager, times(3)).getBlockData(any()) for (i <- 0 until 5) { assert(iterator.hasNext, s"iterator should have 5 elements but actually has $i elements") val (blockId, inputStream) = iterator.next() // Make sure we release buffers when a wrapped input stream is closed. val mockBuf = localBlocks.getOrElse(blockId, remoteBlocks(blockId)) // Note: ShuffleBlockFetcherIterator wraps input streams in a BufferReleasingInputStream val wrappedInputStream = inputStream.asInstanceOf[BufferReleasingInputStream] verify(mockBuf, times(0)).release() val delegateAccess = PrivateMethod[InputStream]('delegate) verify(wrappedInputStream.invokePrivate(delegateAccess()), times(0)).close() wrappedInputStream.close() verify(mockBuf, times(1)).release() verify(wrappedInputStream.invokePrivate(delegateAccess()), times(1)).close() wrappedInputStream.close() // close should be idempotent verify(mockBuf, times(1)).release() verify(wrappedInputStream.invokePrivate(delegateAccess()), times(1)).close() } // 3 local blocks, and 2 remote blocks // (but from the same block manager so one call to fetchBlocks) verify(blockManager, times(3)).getBlockData(any()) verify(transfer, times(1)).fetchBlocks(any(), any(), any(), any(), any()) } test("release current unexhausted buffer in case the task completes early") { val blockManager = mock(classOf[BlockManager]) val localBmId = BlockManagerId("test-client", "test-client", 1) doReturn(localBmId).when(blockManager).blockManagerId // Make sure remote blocks would return val remoteBmId = BlockManagerId("test-client-1", "test-client-1", 2) val blocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 0, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 1, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 2, 0) -> createMockManagedBuffer()) // Semaphore to coordinate event sequence in two different threads. val sem = new Semaphore(0) val transfer = mock(classOf[BlockTransferService]) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] Future { // Return the first two blocks, and wait till task completion before returning the 3rd one listener.onBlockFetchSuccess( ShuffleBlockId(0, 0, 0).toString, blocks(ShuffleBlockId(0, 0, 0))) listener.onBlockFetchSuccess( ShuffleBlockId(0, 1, 0).toString, blocks(ShuffleBlockId(0, 1, 0))) sem.acquire() listener.onBlockFetchSuccess( ShuffleBlockId(0, 2, 0).toString, blocks(ShuffleBlockId(0, 2, 0))) } } }) val blocksByAddress = Seq[(BlockManagerId, Seq[(BlockId, Long)])]( (remoteBmId, blocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq)) val taskContext = TaskContext.empty() val iterator = new ShuffleBlockFetcherIterator( taskContext, transfer, blockManager, blocksByAddress, (_, in) => in, 48 * 1024 * 1024, Int.MaxValue, true) verify(blocks(ShuffleBlockId(0, 0, 0)), times(0)).release() iterator.next()._2.close() // close() first block's input stream verify(blocks(ShuffleBlockId(0, 0, 0)), times(1)).release() // Get the 2nd block but do not exhaust the iterator val subIter = iterator.next()._2 // Complete the task; then the 2nd block buffer should be exhausted verify(blocks(ShuffleBlockId(0, 1, 0)), times(0)).release() taskContext.markTaskCompleted(None) verify(blocks(ShuffleBlockId(0, 1, 0)), times(1)).release() // The 3rd block should not be retained because the iterator is already in zombie state sem.release() verify(blocks(ShuffleBlockId(0, 2, 0)), times(0)).retain() verify(blocks(ShuffleBlockId(0, 2, 0)), times(0)).release() } test("fail all blocks if any of the remote request fails") { val blockManager = mock(classOf[BlockManager]) val localBmId = BlockManagerId("test-client", "test-client", 1) doReturn(localBmId).when(blockManager).blockManagerId // Make sure remote blocks would return val remoteBmId = BlockManagerId("test-client-1", "test-client-1", 2) val blocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 0, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 1, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 2, 0) -> createMockManagedBuffer() ) // Semaphore to coordinate event sequence in two different threads. val sem = new Semaphore(0) val transfer = mock(classOf[BlockTransferService]) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] Future { // Return the first block, and then fail. listener.onBlockFetchSuccess( ShuffleBlockId(0, 0, 0).toString, blocks(ShuffleBlockId(0, 0, 0))) listener.onBlockFetchFailure( ShuffleBlockId(0, 1, 0).toString, new BlockNotFoundException("blah")) listener.onBlockFetchFailure( ShuffleBlockId(0, 2, 0).toString, new BlockNotFoundException("blah")) sem.release() } } }) val blocksByAddress = Seq[(BlockManagerId, Seq[(BlockId, Long)])]( (remoteBmId, blocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq)) val taskContext = TaskContext.empty() val iterator = new ShuffleBlockFetcherIterator( taskContext, transfer, blockManager, blocksByAddress, (_, in) => in, 48 * 1024 * 1024, Int.MaxValue, true) // Continue only after the mock calls onBlockFetchFailure sem.acquire() // The first block should be returned without an exception, and the last two should throw // FetchFailedExceptions (due to failure) iterator.next() intercept[FetchFailedException] { iterator.next() } intercept[FetchFailedException] { iterator.next() } } test("retry corrupt blocks") { val blockManager = mock(classOf[BlockManager]) val localBmId = BlockManagerId("test-client", "test-client", 1) doReturn(localBmId).when(blockManager).blockManagerId // Make sure remote blocks would return val remoteBmId = BlockManagerId("test-client-1", "test-client-1", 2) val blocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 0, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 1, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 2, 0) -> createMockManagedBuffer() ) // Semaphore to coordinate event sequence in two different threads. val sem = new Semaphore(0) val corruptStream = mock(classOf[InputStream]) when(corruptStream.read(any(), any(), any())).thenThrow(new IOException("corrupt")) val corruptBuffer = mock(classOf[ManagedBuffer]) when(corruptBuffer.createInputStream()).thenReturn(corruptStream) val corruptLocalBuffer = new FileSegmentManagedBuffer(null, new File("a"), 0, 100) val transfer = mock(classOf[BlockTransferService]) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] Future { // Return the first block, and then fail. listener.onBlockFetchSuccess( ShuffleBlockId(0, 0, 0).toString, blocks(ShuffleBlockId(0, 0, 0))) listener.onBlockFetchSuccess( ShuffleBlockId(0, 1, 0).toString, corruptBuffer) listener.onBlockFetchSuccess( ShuffleBlockId(0, 2, 0).toString, corruptLocalBuffer) sem.release() } } }) val blocksByAddress = Seq[(BlockManagerId, Seq[(BlockId, Long)])]( (remoteBmId, blocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq)) val taskContext = TaskContext.empty() val iterator = new ShuffleBlockFetcherIterator( taskContext, transfer, blockManager, blocksByAddress, (_, in) => new LimitedInputStream(in, 100), 48 * 1024 * 1024, Int.MaxValue, true) // Continue only after the mock calls onBlockFetchFailure sem.acquire() // The first block should be returned without an exception val (id1, _) = iterator.next() assert(id1 === ShuffleBlockId(0, 0, 0)) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] Future { // Return the first block, and then fail. listener.onBlockFetchSuccess( ShuffleBlockId(0, 1, 0).toString, corruptBuffer) sem.release() } } }) // The next block is corrupt local block (the second one is corrupt and retried) intercept[FetchFailedException] { iterator.next() } sem.acquire() intercept[FetchFailedException] { iterator.next() } } test("retry corrupt blocks (disabled)") { val blockManager = mock(classOf[BlockManager]) val localBmId = BlockManagerId("test-client", "test-client", 1) doReturn(localBmId).when(blockManager).blockManagerId // Make sure remote blocks would return val remoteBmId = BlockManagerId("test-client-1", "test-client-1", 2) val blocks = Map[BlockId, ManagedBuffer]( ShuffleBlockId(0, 0, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 1, 0) -> createMockManagedBuffer(), ShuffleBlockId(0, 2, 0) -> createMockManagedBuffer() ) // Semaphore to coordinate event sequence in two different threads. val sem = new Semaphore(0) val corruptStream = mock(classOf[InputStream]) when(corruptStream.read(any(), any(), any())).thenThrow(new IOException("corrupt")) val corruptBuffer = mock(classOf[ManagedBuffer]) when(corruptBuffer.createInputStream()).thenReturn(corruptStream) val transfer = mock(classOf[BlockTransferService]) when(transfer.fetchBlocks(any(), any(), any(), any(), any())).thenAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = { val listener = invocation.getArguments()(4).asInstanceOf[BlockFetchingListener] Future { // Return the first block, and then fail. listener.onBlockFetchSuccess( ShuffleBlockId(0, 0, 0).toString, blocks(ShuffleBlockId(0, 0, 0))) listener.onBlockFetchSuccess( ShuffleBlockId(0, 1, 0).toString, corruptBuffer) listener.onBlockFetchSuccess( ShuffleBlockId(0, 2, 0).toString, corruptBuffer) sem.release() } } }) val blocksByAddress = Seq[(BlockManagerId, Seq[(BlockId, Long)])]( (remoteBmId, blocks.keys.map(blockId => (blockId, 1.asInstanceOf[Long])).toSeq)) val taskContext = TaskContext.empty() val iterator = new ShuffleBlockFetcherIterator( taskContext, transfer, blockManager, blocksByAddress, (_, in) => new LimitedInputStream(in, 100), 48 * 1024 * 1024, Int.MaxValue, false) // Continue only after the mock calls onBlockFetchFailure sem.acquire() // The first block should be returned without an exception val (id1, _) = iterator.next() assert(id1 === ShuffleBlockId(0, 0, 0)) val (id2, _) = iterator.next() assert(id2 === ShuffleBlockId(0, 1, 0)) val (id3, _) = iterator.next() assert(id3 === ShuffleBlockId(0, 2, 0)) } }
apache-2.0
veritas-shine/minix3-rpi
external/bsd/libc++/dist/libcxx/test/containers/unord/unord.multimap/unord.multimap.cnstr/size_hash.pass.cpp
2997
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_map> // template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, // class Alloc = allocator<pair<const Key, T>>> // class unordered_multimap // unordered_multimap(size_type n, const hasher& hf); #include <unordered_map> #include <cassert> #include "../../../NotConstructible.h" #include "../../../test_compare.h" #include "../../../test_hash.h" #include "../../../test_allocator.h" #include "../../../min_allocator.h" int main() { { typedef std::unordered_multimap<NotConstructible, NotConstructible, test_hash<std::hash<NotConstructible> >, test_compare<std::equal_to<NotConstructible> >, test_allocator<std::pair<const NotConstructible, NotConstructible> > > C; C c(7, test_hash<std::hash<NotConstructible> >(8) ); assert(c.bucket_count() == 7); assert(c.hash_function() == test_hash<std::hash<NotConstructible> >(8)); assert(c.key_eq() == test_compare<std::equal_to<NotConstructible> >()); assert(c.get_allocator() == (test_allocator<std::pair<const NotConstructible, NotConstructible> >())); assert(c.size() == 0); assert(c.empty()); assert(std::distance(c.begin(), c.end()) == 0); assert(c.load_factor() == 0); assert(c.max_load_factor() == 1); } #if __cplusplus >= 201103L { typedef std::unordered_multimap<NotConstructible, NotConstructible, test_hash<std::hash<NotConstructible> >, test_compare<std::equal_to<NotConstructible> >, min_allocator<std::pair<const NotConstructible, NotConstructible> > > C; C c(7, test_hash<std::hash<NotConstructible> >(8) ); assert(c.bucket_count() == 7); assert(c.hash_function() == test_hash<std::hash<NotConstructible> >(8)); assert(c.key_eq() == test_compare<std::equal_to<NotConstructible> >()); assert(c.get_allocator() == (min_allocator<std::pair<const NotConstructible, NotConstructible> >())); assert(c.size() == 0); assert(c.empty()); assert(std::distance(c.begin(), c.end()) == 0); assert(c.load_factor() == 0); assert(c.max_load_factor() == 1); } #endif }
apache-2.0
GabrielBrascher/cloudstack
test/integration/component/test_allocation_states.py
11273
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase from marvin.lib.utils import cleanup_resources from marvin.lib.base import (Host, Pod, Zone, Cluster, StoragePool) from marvin.lib.common import get_zone, get_template from marvin.codes import FAILED class Services: """Test Resource Limits Services """ def __init__(self): self.services = { "domain": { "name": "Domain", }, "account": { "email": "test@test.com", "firstname": "Test", "lastname": "User", "username": "test", # Random characters are appended for unique # username "password": "password", }, "service_offering": { "name": "Tiny Instance", "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz "memory": 128, # In MBs }, "disk_offering": { "displaytext": "Small", "name": "Small", "disksize": 1 }, "volume": { "diskname": "TestDiskServ", }, "server": { "displayname": "TestVM", "username": "root", "password": "password", "ssh_port": 22, "hypervisor": 'XenServer', "privateport": 22, "publicport": 22, "protocol": 'TCP', }, "template": { "displaytext": "Cent OS Template", "name": "Cent OS Template", "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', "templatefilter": 'self', }, "ostype": 'CentOS 5.3 (64-bit)', # Cent OS 5.3 (64 bit) "sleep": 60, "timeout": 10, } class TestAllocationState(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestAllocationState, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services # Get Zone, Domain and templates cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.hypervisor = cls.testClient.getHypervisorInfo() cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) if cls.template == FAILED: assert False, "get_template() failed to return template with description %s" % cls.services["ostype"] cls.services['mode'] = cls.zone.networktype cls._cleanup = [] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created instance, volumes and snapshots cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_01_zones(self): """Check the status of zones""" # Validate the following # 1. List zones # 2. Check allocation state is "enabled" or not zones = Zone.list( self.apiclient, id=self.zone.id, listall=True ) self.assertEqual( isinstance(zones, list), True, "Check if listZones returns a valid response" ) for zone in zones: self.assertEqual( zone.allocationstate, 'Enabled', "Zone allocation state should be enabled" ) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_02_pods(self): """Check the status of pods""" # Validate the following # 1. List pods # 2. Check allocation state is "enabled" or not pods = Pod.list( self.apiclient, zoneid=self.zone.id, listall=True ) self.assertEqual( isinstance(pods, list), True, "Check if listPods returns a valid response" ) for pod in pods: self.assertEqual( pod.allocationstate, 'Enabled', "Pods allocation state should be enabled" ) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_03_clusters(self): """Check the status of clusters""" # Validate the following # 1. List clusters # 2. Check allocation state is "enabled" or not clusters = Cluster.list( self.apiclient, zoneid=self.zone.id, listall=True ) self.assertEqual( isinstance(clusters, list), True, "Check if listClusters returns a valid response" ) for cluster in clusters: self.assertEqual( cluster.allocationstate, 'Enabled', "Clusters allocation state should be enabled" ) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_04_hosts(self): """Check the status of hosts""" # Validate the following # 1. List hosts with type=Routing # 2. Check state is "Up" or not hosts = Host.list( self.apiclient, zoneid=self.zone.id, type='Routing', listall=True ) self.assertEqual( isinstance(hosts, list), True, "Check if listHosts returns a valid response" ) for host in hosts: self.assertEqual( host.state, 'Up', "Host should be in Up state and running" ) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_05_storage_pools(self): """Check the status of Storage pools""" # Validate the following # 1. List storage pools for the zone # 2. Check state is "enabled" or not storage_pools = StoragePool.list( self.apiclient, zoneid=self.zone.id, listall=True ) self.assertEqual( isinstance(storage_pools, list), True, "Check if listStoragePools returns a valid response" ) for storage_pool in storage_pools: self.assertEqual( storage_pool.state, 'Up', "storage pool should be in Up state and running" ) return @attr(tags=["advanced", "advancedns", "simulator"], required_hardware="false") def test_06_secondary_storage(self): """Check the status of secondary storage""" # Validate the following # 1. List secondary storage # 2. Check state is "Up" or not if self.hypervisor.lower() == 'simulator': self.skipTest("Hypervisor is simulator skipping") sec_storages = Host.list( self.apiclient, zoneid=self.zone.id, type='SecondaryStorageVM', listall=True ) if sec_storages is None: self.skipTest("SSVM is not provisioned yet, skipping") self.assertEqual( isinstance(sec_storages, list), True, "Check if listHosts returns a valid response" ) for sec_storage in sec_storages: self.assertEqual( sec_storage.state, 'Up', "Secondary storage should be in Up state" ) return
apache-2.0
sanitysoon/nbase-arc
confmaster/src/main/java/com/navercorp/nbasearc/confmaster/server/lock/HierarchicalLockPGS.java
4133
/* * Copyright 2015 Naver Corp. * * 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 com.navercorp.nbasearc.confmaster.server.lock; import static com.navercorp.nbasearc.confmaster.Constant.*; import java.util.ArrayList; import java.util.List; import com.navercorp.nbasearc.confmaster.Constant; import com.navercorp.nbasearc.confmaster.ThreadLocalVariableHolder; import com.navercorp.nbasearc.confmaster.logger.Logger; import com.navercorp.nbasearc.confmaster.server.cluster.PartitionGroupServer; import com.navercorp.nbasearc.confmaster.server.cluster.PathUtil; public class HierarchicalLockPGS extends HierarchicalLock { private HierarchicalLockPG pgLock; private String clusterName; private String pgID = null; private String pgsID; public HierarchicalLockPGS() { } public HierarchicalLockPGS(HierarchicalLockHelper hlh, LockType lockType, String clusterName, HierarchicalLockPG pgLock, String pgID, String pgsID) { super(hlh, lockType); this.clusterName = clusterName; this.pgLock = pgLock; this.pgID = pgID; this.pgsID = pgsID; if (!pgLock.isLocked() && pgID == null) { PartitionGroupServer pgs = getHlh().getContainer().getPgs(clusterName, pgsID); if (pgs == null) { String message = EXCEPTIONMSG_PARTITION_GROUP_SERVER_DOES_NOT_EXIST + PartitionGroupServer.fullName(clusterName, pgsID); Logger.error(message); throw new IllegalArgumentException(message); } pgID = String.valueOf(pgs.getPgId()); pgLock.setPgID(pgID); pgLock._lock(); } _lock(); } public HierarchicalLockPGS pgs(LockType lockType, String pgsID) { return new HierarchicalLockPGS(getHlh(), lockType, clusterName, pgLock, null, pgsID); } public HierarchicalLockPGS pgs(LockType lockType, String pgID, String pgsID) { return new HierarchicalLockPGS(getHlh(), lockType, clusterName, pgLock, pgID, pgsID); } public HierarchicalLockGWList gwList(LockType lockType) { return new HierarchicalLockGWList(getHlh(), lockType, clusterName); } @Override protected void _lock() { List<PartitionGroupServer> pgsList; if (pgsID.equals(Constant.ALL_IN_PG)) { pgsList = getHlh().getContainer().getPgsList(clusterName, pgID); } else if (pgsID.equals(Constant.ALL)) { pgsList = getHlh().getContainer().getPgsList(clusterName); } else { PartitionGroupServer pgs = getHlh().getContainer().getPgs(clusterName, pgsID); if (pgs == null) { throw new IllegalArgumentException( EXCEPTIONMSG_PARTITION_GROUP_DOES_NOT_EXIST + PartitionGroupServer.fullName(clusterName, pgsID)); } pgsList = new ArrayList<PartitionGroupServer>(); pgsList.add(pgs); } for (PartitionGroupServer pgs : pgsList) { ThreadLocalVariableHolder.addPermission(pgs.getPath(), getLockType()); ThreadLocalVariableHolder.addPermission(PathUtil.rsPath(pgs.getName(), pgs.getClusterName()), getLockType()); switch (getLockType()) { case READ: getHlh().acquireLock(pgs.readLock()); break; case WRITE: getHlh().acquireLock(pgs.writeLock()); break; } } } }
apache-2.0
google/knative-gcp
vendor/cloud.google.com/go/pubsub/message.go
3915
// Copyright 2016 Google LLC // // 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 pubsub import ( "time" "github.com/golang/protobuf/ptypes" pb "google.golang.org/genproto/googleapis/pubsub/v1" ) // Message represents a Pub/Sub message. type Message struct { // ID identifies this message. This ID is assigned by the server and is // populated for Messages obtained from a subscription. // // This field is read-only. ID string // Data is the actual data in the message. Data []byte // Attributes represents the key-value pairs the current message is // labelled with. Attributes map[string]string // ackID is the identifier to acknowledge this message. ackID string // PublishTime is the time at which the message was published. This is // populated by the server for Messages obtained from a subscription. // // This field is read-only. PublishTime time.Time // receiveTime is the time the message was received by the client. receiveTime time.Time // DeliveryAttempt is the number of times a message has been delivered. // This is part of the dead lettering feature that forwards messages that // fail to be processed (from nack/ack deadline timeout) to a dead letter topic. // If dead lettering is enabled, this will be set on all attempts, starting // with value 1. Otherwise, the value will be nil. // This field is read-only. DeliveryAttempt *int // size is the approximate size of the message's data and attributes. size int calledDone bool // The done method of the iterator that created this Message. doneFunc func(string, bool, time.Time) // OrderingKey identifies related messages for which publish order should // be respected. If empty string is used, message will be sent unordered. OrderingKey string } func toMessage(resp *pb.ReceivedMessage) (*Message, error) { if resp.Message == nil { return &Message{ackID: resp.AckId}, nil } pubTime, err := ptypes.Timestamp(resp.Message.PublishTime) if err != nil { return nil, err } var deliveryAttempt *int if resp.DeliveryAttempt > 0 { da := int(resp.DeliveryAttempt) deliveryAttempt = &da } return &Message{ ackID: resp.AckId, Data: resp.Message.Data, Attributes: resp.Message.Attributes, ID: resp.Message.MessageId, PublishTime: pubTime, DeliveryAttempt: deliveryAttempt, OrderingKey: resp.Message.OrderingKey, }, nil } // Ack indicates successful processing of a Message passed to the Subscriber.Receive callback. // It should not be called on any other Message value. // If message acknowledgement fails, the Message will be redelivered. // Client code must call Ack or Nack when finished for each received Message. // Calls to Ack or Nack have no effect after the first call. func (m *Message) Ack() { m.done(true) } // Nack indicates that the client will not or cannot process a Message passed to the Subscriber.Receive callback. // It should not be called on any other Message value. // Nack will result in the Message being redelivered more quickly than if it were allowed to expire. // Client code must call Ack or Nack when finished for each received Message. // Calls to Ack or Nack have no effect after the first call. func (m *Message) Nack() { m.done(false) } func (m *Message) done(ack bool) { if m.calledDone { return } m.calledDone = true m.doneFunc(m.ackID, ack, m.receiveTime) }
apache-2.0
ingokegel/intellij-community
platform/platform-api/src/com/intellij/pom/NavigatableWithText.java
888
/* * Copyright 2000-2010 JetBrains s.r.o. * * 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 com.intellij.pom; import com.intellij.openapi.util.NlsActions; import org.jetbrains.annotations.Nullable; /** * @author yole */ public interface NavigatableWithText extends Navigatable { @NlsActions.ActionText @Nullable String getNavigateActionText(boolean focusEditor); }
apache-2.0
huntxu/neutron
neutron/db/migration/alembic_migrations/versions/mitaka/expand/32e5974ada25_add_neutron_resources_table.py
1390
# # 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. # from alembic import op import sqlalchemy as sa """Add standard attribute table Revision ID: 32e5974ada25 Revises: 13cfb89f881a Create Date: 2015-09-10 00:22:47.618593 """ # revision identifiers, used by Alembic. revision = '32e5974ada25' down_revision = '13cfb89f881a' TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups', 'floatingips', 'routers', 'securitygrouprules') def upgrade(): op.create_table( 'standardattributes', sa.Column('id', sa.BigInteger(), autoincrement=True), sa.Column('resource_type', sa.String(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) for table in TABLES: op.add_column(table, sa.Column('standard_attr_id', sa.BigInteger(), nullable=True))
apache-2.0
quinton-hoole/kubernetes
staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go
5618
/* Copyright 2019 The Kubernetes 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 webhook import ( "k8s.io/api/admissionregistration/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // WebhookAccessor provides a common interface to both mutating and validating webhook types. type WebhookAccessor interface { // GetUID gets a string that uniquely identifies the webhook. GetUID() string // GetName gets the webhook Name field. Note that the name is scoped to the webhook // configuration and does not provide a globally unique identity, if a unique identity is // needed, use GetUID. GetName() string // GetClientConfig gets the webhook ClientConfig field. GetClientConfig() v1beta1.WebhookClientConfig // GetRules gets the webhook Rules field. GetRules() []v1beta1.RuleWithOperations // GetFailurePolicy gets the webhook FailurePolicy field. GetFailurePolicy() *v1beta1.FailurePolicyType // GetMatchPolicy gets the webhook MatchPolicy field. GetMatchPolicy() *v1beta1.MatchPolicyType // GetNamespaceSelector gets the webhook NamespaceSelector field. GetNamespaceSelector() *metav1.LabelSelector // GetObjectSelector gets the webhook ObjectSelector field. GetObjectSelector() *metav1.LabelSelector // GetSideEffects gets the webhook SideEffects field. GetSideEffects() *v1beta1.SideEffectClass // GetTimeoutSeconds gets the webhook TimeoutSeconds field. GetTimeoutSeconds() *int32 // GetAdmissionReviewVersions gets the webhook AdmissionReviewVersions field. GetAdmissionReviewVersions() []string // GetMutatingWebhook if the accessor contains a MutatingWebhook, returns it and true, else returns false. GetMutatingWebhook() (*v1beta1.MutatingWebhook, bool) // GetValidatingWebhook if the accessor contains a ValidatingWebhook, returns it and true, else returns false. GetValidatingWebhook() (*v1beta1.ValidatingWebhook, bool) } // NewMutatingWebhookAccessor creates an accessor for a MutatingWebhook. func NewMutatingWebhookAccessor(uid string, h *v1beta1.MutatingWebhook) WebhookAccessor { return mutatingWebhookAccessor{uid: uid, MutatingWebhook: h} } type mutatingWebhookAccessor struct { *v1beta1.MutatingWebhook uid string } func (m mutatingWebhookAccessor) GetUID() string { return m.uid } func (m mutatingWebhookAccessor) GetName() string { return m.Name } func (m mutatingWebhookAccessor) GetClientConfig() v1beta1.WebhookClientConfig { return m.ClientConfig } func (m mutatingWebhookAccessor) GetRules() []v1beta1.RuleWithOperations { return m.Rules } func (m mutatingWebhookAccessor) GetFailurePolicy() *v1beta1.FailurePolicyType { return m.FailurePolicy } func (m mutatingWebhookAccessor) GetMatchPolicy() *v1beta1.MatchPolicyType { return m.MatchPolicy } func (m mutatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector { return m.NamespaceSelector } func (m mutatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector { return m.ObjectSelector } func (m mutatingWebhookAccessor) GetSideEffects() *v1beta1.SideEffectClass { return m.SideEffects } func (m mutatingWebhookAccessor) GetTimeoutSeconds() *int32 { return m.TimeoutSeconds } func (m mutatingWebhookAccessor) GetAdmissionReviewVersions() []string { return m.AdmissionReviewVersions } func (m mutatingWebhookAccessor) GetMutatingWebhook() (*v1beta1.MutatingWebhook, bool) { return m.MutatingWebhook, true } func (m mutatingWebhookAccessor) GetValidatingWebhook() (*v1beta1.ValidatingWebhook, bool) { return nil, false } // NewValidatingWebhookAccessor creates an accessor for a ValidatingWebhook. func NewValidatingWebhookAccessor(uid string, h *v1beta1.ValidatingWebhook) WebhookAccessor { return validatingWebhookAccessor{uid: uid, ValidatingWebhook: h} } type validatingWebhookAccessor struct { *v1beta1.ValidatingWebhook uid string } func (v validatingWebhookAccessor) GetUID() string { return v.uid } func (v validatingWebhookAccessor) GetName() string { return v.Name } func (v validatingWebhookAccessor) GetClientConfig() v1beta1.WebhookClientConfig { return v.ClientConfig } func (v validatingWebhookAccessor) GetRules() []v1beta1.RuleWithOperations { return v.Rules } func (v validatingWebhookAccessor) GetFailurePolicy() *v1beta1.FailurePolicyType { return v.FailurePolicy } func (v validatingWebhookAccessor) GetMatchPolicy() *v1beta1.MatchPolicyType { return v.MatchPolicy } func (v validatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector { return v.NamespaceSelector } func (v validatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector { return v.ObjectSelector } func (v validatingWebhookAccessor) GetSideEffects() *v1beta1.SideEffectClass { return v.SideEffects } func (v validatingWebhookAccessor) GetTimeoutSeconds() *int32 { return v.TimeoutSeconds } func (v validatingWebhookAccessor) GetAdmissionReviewVersions() []string { return v.AdmissionReviewVersions } func (v validatingWebhookAccessor) GetMutatingWebhook() (*v1beta1.MutatingWebhook, bool) { return nil, false } func (v validatingWebhookAccessor) GetValidatingWebhook() (*v1beta1.ValidatingWebhook, bool) { return v.ValidatingWebhook, true }
apache-2.0
wwezhuimeng/twitter-server
doc/src/sphinx/conf.py
1764
# -*- coding: utf-8 -*- # # Documentation config # import sys, os sys.path.append(os.path.abspath('exts')) sys.path.append(os.path.abspath('utils')) import sbt_versions # highlight_language = 'scala' highlight_language = 'text' # this way we don't get ugly syntax coloring extensions = ['sphinx.ext.extlinks', 'includecode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' exclude_patterns = [] sys.path.append(os.path.abspath('_themes')) html_theme_path = ['_themes'] html_theme = 'flask' html_short_title = 'TwitterServer' html_sidebars = { 'index': ['sidebarintro.html', 'searchbox.html'], '**': ['sidebarintro.html', 'localtoc.html', 'relations.html', 'searchbox.html'] } html_theme_options = { 'index_logo': None } # These don't seem to work? html_use_smartypants = True html_show_sphinx = False project = u'TwitterServer' copyright = u'2013 Twitter, Inc' version = '' release = '' htmlhelp_basename = "twitter-server" release = sbt_versions.find_release(os.path.abspath('../../../project/Build.scala')) version = sbt_versions.release_to_version(release) # e.g. :issue:`36` :ticket:`8` extlinks = { 'issue': ('https://github.com/twitter/twitter-server/issues/%s', 'issue #') } rst_epilog = ''' .. include:: /links.txt ''' pygments_style = 'flask_theme_support.FlaskyStyle' # fall back if theme is not there try: __import__('flask_theme_support') except ImportError, e: print '-' * 74 print 'Warning: Flask themes unavailable. Building with default theme' print 'If you want the Flask themes, run this command and build again:' print print ' git submodule update --init' print '-' * 74 pygments_style = 'tango' html_theme = 'default' html_theme_options = {}
apache-2.0
etirelli/droolsjbpm-tools
drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/flow/bpmn2/editor/BPMNModelEditor.java
13273
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * 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 org.drools.eclipse.flow.bpmn2.editor; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.drools.eclipse.DroolsEclipsePlugin; import org.drools.eclipse.WorkItemDefinitions; import org.drools.eclipse.flow.common.editor.GenericModelEditor; import org.drools.eclipse.flow.ruleflow.core.RuleFlowProcessWrapper; import org.drools.eclipse.flow.ruleflow.core.RuleFlowWrapperBuilder; import org.drools.eclipse.flow.ruleflow.core.StartNodeWrapper; import org.drools.eclipse.flow.ruleflow.core.WorkItemWrapper; import org.drools.eclipse.flow.ruleflow.editor.RuleFlowPaletteFactory; import org.drools.eclipse.flow.ruleflow.editor.editpart.RuleFlowEditPartFactory; import org.drools.eclipse.util.ProjectClassLoader; import org.jbpm.process.core.WorkDefinition; import org.jbpm.process.core.WorkDefinitionExtension; import org.drools.core.xml.SemanticModules; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPartFactory; import org.eclipse.gef.palette.CombinedTemplateCreationEntry; import org.eclipse.gef.palette.PaletteDrawer; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.requests.SimpleFactory; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.jbpm.bpmn2.xml.BPMNDISemanticModule; import org.jbpm.bpmn2.xml.BPMNExtensionsSemanticModule; import org.jbpm.bpmn2.xml.BPMNSemanticModule; import org.jbpm.bpmn2.xml.XmlBPMNProcessDumper; import org.jbpm.compiler.xml.XmlProcessReader; import org.jbpm.ruleflow.core.RuleFlowProcess; import org.jbpm.workflow.core.node.CompositeNode; import org.jbpm.workflow.core.node.EndNode; import org.jbpm.workflow.core.node.EventNode; import org.jbpm.workflow.core.node.FaultNode; import org.jbpm.workflow.core.node.Join; import org.jbpm.workflow.core.node.Split; import org.jbpm.workflow.core.node.StartNode; import org.jbpm.workflow.core.node.TimerNode; import org.kie.api.definition.process.Node; import org.kie.api.definition.process.Process; /** * Graphical editor for a RuleFlow. */ public class BPMNModelEditor extends GenericModelEditor { protected EditPartFactory createEditPartFactory() { RuleFlowEditPartFactory factory = new RuleFlowEditPartFactory(); factory.setProject(getJavaProject()); return factory; } protected PaletteRoot createPalette() { return RuleFlowPaletteFactory.createPalette(); } protected Object createModel() { RuleFlowProcessWrapper result = new RuleFlowProcessWrapper(); StartNodeWrapper start = new StartNodeWrapper(); start.setConstraint(new Rectangle(100, 100, -1, -1)); result.addElement(start); start.setParent(result); IFile file = ((IFileEditorInput)getEditorInput()).getFile(); String name = file.getName(); result.setName(name.substring(0, name.length() - 5)); result.setId("com.sample.process"); return result; } public RuleFlowProcessWrapper getRuleFlowModel() { return (RuleFlowProcessWrapper) getModel(); } protected void setInput(IEditorInput input) { super.setInput(input); if (input instanceof IFileEditorInput) { refreshPalette(((IFileEditorInput) input).getFile()); } } private void refreshPalette(IFile file) { IJavaProject javaProject = getJavaProject(); if (javaProject != null) { try { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); ClassLoader newLoader = ProjectClassLoader.getProjectClassLoader(javaProject); try { Thread.currentThread().setContextClassLoader(newLoader); if (getPaletteRoot().getChildren().size() > 2) { PaletteDrawer drawer = (PaletteDrawer) getPaletteRoot().getChildren().get(2); List<CombinedTemplateCreationEntry> entries = new ArrayList<CombinedTemplateCreationEntry>(); try { for (final WorkDefinition workDefinition: WorkItemDefinitions.getWorkDefinitions(file).values()) { final String label; String description = workDefinition.getName(); String icon = null; if (workDefinition instanceof WorkDefinitionExtension) { WorkDefinitionExtension extension = (WorkDefinitionExtension) workDefinition; label = extension.getDisplayName(); description = extension.getExplanationText(); icon = extension.getIcon(); } else { label = workDefinition.getName(); } URL iconUrl = null; if (icon != null) { iconUrl = newLoader.getResource(icon); } if (iconUrl == null) { iconUrl = DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/action.gif"); } CombinedTemplateCreationEntry combined = new CombinedTemplateCreationEntry( label, description, WorkItemWrapper.class, new SimpleFactory(WorkItemWrapper.class) { public Object getNewObject() { WorkItemWrapper workItemWrapper = (WorkItemWrapper) super.getNewObject(); workItemWrapper.setName(label); workItemWrapper.setWorkDefinition(workDefinition); return workItemWrapper; } }, ImageDescriptor.createFromURL(iconUrl), ImageDescriptor.createFromURL(iconUrl) ); entries.add(combined); } } catch (Throwable t) { DroolsEclipsePlugin.log(t); MessageDialog.openError( getSite().getShell(), "Parsing work item definitions", t.getMessage()); } drawer.setChildren(entries); } } finally { Thread.currentThread().setContextClassLoader(oldLoader); } } catch (Exception e) { DroolsEclipsePlugin.log(e); } } } protected void writeModel(OutputStream os) throws IOException { writeModel(os, true); } protected void writeModel(OutputStream os, boolean includeGraphics) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8"); try { RuleFlowProcess process = getRuleFlowModel().getRuleFlowProcess(); XmlBPMNProcessDumper dumper = XmlBPMNProcessDumper.INSTANCE; String out = dumper.dump(process, XmlBPMNProcessDumper.META_DATA_USING_DI); writer.write(out); } catch (Throwable t) { DroolsEclipsePlugin.log(t); IStatus status = new Status( IStatus.ERROR, DroolsEclipsePlugin.getUniqueIdentifier(), -1, "Could not save BPMN process, see error log for more details and contact the developers: " + t.getMessage(), t); ErrorDialog.openError( getSite().getShell(), "Process Save Error", "Unable to save process.", status); throw new IOException(t.getMessage()); } writer.close(); } protected void createModel(InputStream is) { try { InputStreamReader isr = new InputStreamReader(is, "UTF-8"); SemanticModules semanticModules = new SemanticModules(); semanticModules.addSemanticModule(new BPMNSemanticModule()); semanticModules.addSemanticModule(new BPMNExtensionsSemanticModule()); semanticModules.addSemanticModule(new BPMNDISemanticModule()); XmlProcessReader xmlReader = new XmlProcessReader(semanticModules, Thread.currentThread().getContextClassLoader()); try { List<Process> processes = xmlReader.read(isr); if (processes == null || processes.size() == 0) { setModel(createModel()); } else { RuleFlowProcess process = (RuleFlowProcess) processes.get(0); if (process == null) { setModel(createModel()); } else { correctEventNodeSize(process.getNodes()); setModel(new RuleFlowWrapperBuilder().getProcessWrapper(process, getJavaProject())); } } } catch (Throwable t) { DroolsEclipsePlugin.log(t); MessageDialog.openError( getSite().getShell(), "Could not read RuleFlow file", "An exception occurred while reading in the RuleFlow XML: " + t.getMessage() + " See the error log for more details."); setModel(createModel()); } if (isr != null){ isr.close(); } } catch (Throwable t) { DroolsEclipsePlugin.log(t); } } private void correctEventNodeSize(Node[] nodes) { for (Node node: nodes) { if (node instanceof StartNode || node instanceof EndNode || node instanceof EventNode || node instanceof FaultNode || node instanceof TimerNode) { Integer width = (Integer) node.getMetaData().get("width"); if (width == null) { width = 48; } Integer height = (Integer) node.getMetaData().get("height"); if (height == null) { height = 48; } if (width != 48 || height != 48) { node.getMetaData().put("width", 48); node.getMetaData().put("height", 48); Integer x = (Integer) node.getMetaData().get("x"); Integer y = (Integer) node.getMetaData().get("y"); x = x - ((48 - width)/2); y = y - ((48 - height)/2); node.getMetaData().put("x", x); node.getMetaData().put("y", y); } } else if (node instanceof Split || node instanceof Join) { Integer width = (Integer) node.getMetaData().get("width"); if (width == null) { width = 49; } Integer height = (Integer) node.getMetaData().get("height"); if (height == null) { height = 49; } if (width != 49 || height != 49) { node.getMetaData().put("width", 49); node.getMetaData().put("height", 49); Integer x = (Integer) node.getMetaData().get("x"); Integer y = (Integer) node.getMetaData().get("y"); x = x - ((49 - width)/2); y = y - ((49 - height)/2); node.getMetaData().put("x", x); node.getMetaData().put("y", y); } } else if (node instanceof CompositeNode) { correctEventNodeSize(((CompositeNode) node).getNodes()); } } } }
apache-2.0
STAH/OpenRiaServices
OpenRiaServices.DomainServices.Tools/Test/ServerClassLib/TestDomainSharedService.cs
565
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenRiaServices.DomainServices.Server; using OpenRiaServices.DomainServices.Hosting; namespace ServerClassLib { /// <summary> /// This DomainService is used to test for the pre-existence of /// a DomainContext in the client. /// </summary> [EnableClientAccess] public class TestDomainSharedService : DomainService { public IEnumerable<TestEntity2> GetTestEntities() { return new TestEntity2[0]; } } }
apache-2.0
ern/elasticsearch
x-pack/plugin/identity-provider/src/internalClusterTest/java/org/elasticsearch/xpack/idp/action/SamlIdentityProviderTests.java
27444
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.idp.action; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.core.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.test.rest.yaml.ObjectPath; import org.elasticsearch.xpack.core.security.action.CreateApiKeyRequestBuilder; import org.elasticsearch.xpack.core.security.action.CreateApiKeyResponse; import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.idp.saml.sp.SamlServiceProviderDocument; import org.elasticsearch.xpack.idp.saml.sp.SamlServiceProviderIndex; import org.elasticsearch.xpack.idp.saml.support.SamlFactory; import org.elasticsearch.xpack.idp.saml.test.IdentityProviderIntegTestCase; import org.opensaml.core.xml.util.XMLObjectSupport; import org.opensaml.saml.common.SAMLObject; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.NameIDPolicy; import org.opensaml.security.SecurityException; import org.opensaml.security.x509.X509Credential; import org.opensaml.xmlsec.crypto.XMLSigningUtil; import org.opensaml.xmlsec.signature.support.SignatureConstants; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.joda.time.DateTime.now; import static org.opensaml.saml.saml2.core.NameIDType.TRANSIENT; @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numClientNodes = 0, numDataNodes = 0) @TestLogging(value = "org.elasticsearch.xpack.idp.action.TransportPutSamlServiceProviderAction:TRACE," + "org.elasticsearch.xpack.idp.saml.sp.SamlServiceProviderIndex:TRACE", reason = "https://github.com/elastic/elasticsearch/issues/54423") public class SamlIdentityProviderTests extends IdentityProviderIntegTestCase { private final SamlFactory samlFactory = new SamlFactory(); public void testIdpInitiatedSso() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // User login a.k.a exchange the user credentials for an API Key final String apiKeyCredentials = getApiKeyFromCredentials(SAMPLE_IDPUSER_NAME, new SecureString(SAMPLE_IDPUSER_PASSWORD.toCharArray())); // Make a request to init an SSO flow with the API Key as secondary authentication Request request = new Request("POST", "/_idp/saml/init"); request.setOptions(RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", basicAuthHeaderValue(CONSOLE_USER_NAME, new SecureString(CONSOLE_USER_PASSWORD.toCharArray()))) .addHeader("es-secondary-authorization", "ApiKey " + apiKeyCredentials) .build()); request.setJsonEntity("{ \"entity_id\": \"" + entityId + "\", \"acs\": \"" + acsUrl + "\" }"); Response initResponse = getRestClient().performRequest(request); ObjectPath objectPath = ObjectPath.createFromResponse(initResponse); assertThat(objectPath.evaluate("post_url").toString(), equalTo(acsUrl)); final String body = objectPath.evaluate("saml_response").toString(); assertThat(body, containsString("Destination=\"" + acsUrl + "\"")); assertThat(body, containsString("<saml2:Audience>" + entityId + "</saml2:Audience>")); assertThat(body, containsString("<saml2:NameID Format=\"" + TRANSIENT + "\">")); Map<String, String> serviceProvider = objectPath.evaluate("service_provider"); assertThat(serviceProvider, hasKey("entity_id")); assertThat(serviceProvider.get("entity_id"), equalTo(entityId)); assertContainsAttributeWithValue(body, "principal", SAMPLE_IDPUSER_NAME); assertContainsAttributeWithValue(body, "roles", "superuser"); } public void testIdPInitiatedSsoFailsForUnknownSP() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // User login a.k.a exchange the user credentials for an API Key final String apiKeyCredentials = getApiKeyFromCredentials(SAMPLE_IDPUSER_NAME, new SecureString(SAMPLE_IDPUSER_PASSWORD.toCharArray())); // Make a request to init an SSO flow with the API Key as secondary authentication Request request = new Request("POST", "/_idp/saml/init"); request.setOptions(RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", basicAuthHeaderValue(CONSOLE_USER_NAME, new SecureString(CONSOLE_USER_PASSWORD.toCharArray()))) .addHeader("es-secondary-authorization", "ApiKey " + apiKeyCredentials) .build()); request.setJsonEntity("{ \"entity_id\": \"" + entityId + randomAlphaOfLength(3) + "\", \"acs\": \"" + acsUrl + "\" }"); ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat(e.getMessage(), containsString("is not known to this Identity Provider")); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); } public void testIdPInitiatedSsoFailsWithoutSecondaryAuthentication() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // Make a request to init an SSO flow with the API Key as secondary authentication Request request = new Request("POST", "/_idp/saml/init"); request.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); request.setJsonEntity("{ \"entity_id\": \"" + entityId + "\", \"acs\": \"" + acsUrl + "\" }"); ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertThat(e.getMessage(), containsString("Request is missing secondary authentication")); } public void testSpInitiatedSso() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // Validate incoming authentication request Request validateRequest = new Request("POST", "/_idp/saml/validate"); validateRequest.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final String nameIdFormat = TRANSIENT; final String relayString = randomBoolean() ? randomAlphaOfLength(8) : null; final boolean forceAuthn = true; final AuthnRequest authnRequest = buildAuthnRequest(entityId, new URL(acsUrl), new URL("https://idp.org/sso/redirect"), nameIdFormat, forceAuthn); final String query = getQueryString(authnRequest, relayString, false, null); validateRequest.setJsonEntity("{\"authn_request_query\":\"" + query + "\"}"); Response validateResponse = getRestClient().performRequest(validateRequest); ObjectPath validateResponseObject = ObjectPath.createFromResponse(validateResponse); Map<String, String> serviceProvider = validateResponseObject.evaluate("service_provider"); assertThat(serviceProvider, hasKey("entity_id")); assertThat(serviceProvider.get("entity_id"), equalTo(entityId)); assertThat(serviceProvider, hasKey("acs")); assertThat(serviceProvider.get("acs"), equalTo(acsUrl)); assertThat(validateResponseObject.evaluate("force_authn"), equalTo(forceAuthn)); Map<String, String> authnState = validateResponseObject.evaluate("authn_state"); assertThat(authnState, hasKey("nameid_format")); assertThat(authnState.get("nameid_format"), equalTo(nameIdFormat)); assertThat(authnState, hasKey("authn_request_id")); final String expectedInResponeTo = authnState.get("authn_request_id"); // User login a.k.a exchange the user credentials for an API Key final String apiKeyCredentials = getApiKeyFromCredentials(SAMPLE_IDPUSER_NAME, new SecureString(SAMPLE_IDPUSER_PASSWORD.toCharArray())); // Make a request to init an SSO flow with the API Key as secondary authentication Request initRequest = new Request("POST", "/_idp/saml/init"); initRequest.setOptions(RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", basicAuthHeaderValue(CONSOLE_USER_NAME, new SecureString(CONSOLE_USER_PASSWORD.toCharArray()))) .addHeader("es-secondary-authorization", "ApiKey " + apiKeyCredentials) .build()); XContentBuilder authnStateBuilder = jsonBuilder(); authnStateBuilder.map(authnState); initRequest.setJsonEntity("{" + ("\"entity_id\":\"" + entityId + "\",") + ("\"acs\":\"" + serviceProvider.get("acs") + "\",") + ("\"authn_state\":" + Strings.toString(authnStateBuilder)) + "}"); Response initResponse = getRestClient().performRequest(initRequest); ObjectPath initResponseObject = ObjectPath.createFromResponse(initResponse); assertThat(initResponseObject.evaluate("post_url").toString(), equalTo(acsUrl)); final String body = initResponseObject.evaluate("saml_response").toString(); assertThat(body, containsString("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>")); assertThat(body, containsString("Destination=\"" + acsUrl + "\"")); assertThat(body, containsString("<saml2:Audience>" + entityId + "</saml2:Audience>")); assertThat(body, containsString("<saml2:NameID Format=\"" + nameIdFormat + "\">")); assertThat(body, containsString("InResponseTo=\"" + expectedInResponeTo + "\"")); Map<String, String> sp = initResponseObject.evaluate("service_provider"); assertThat(sp, hasKey("entity_id")); assertThat(sp.get("entity_id"), equalTo(entityId)); assertContainsAttributeWithValue(body, "principal", SAMPLE_IDPUSER_NAME); assertContainsAttributeWithValue(body, "roles", "superuser"); } public void testSpInitiatedSsoFailsForUserWithNoAccess() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // Validate incoming authentication request Request validateRequest = new Request("POST", "/_idp/saml/validate"); validateRequest.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final String nameIdFormat = TRANSIENT; final String relayString = randomBoolean() ? randomAlphaOfLength(8) : null; final boolean forceAuthn = true; final AuthnRequest authnRequest = buildAuthnRequest(entityId, new URL(acsUrl), new URL("https://idp.org/sso/redirect"), nameIdFormat, forceAuthn); final String query = getQueryString(authnRequest, relayString, false, null); validateRequest.setJsonEntity("{\"authn_request_query\":\"" + query + "\"}"); Response validateResponse = getRestClient().performRequest(validateRequest); ObjectPath validateResponseObject = ObjectPath.createFromResponse(validateResponse); Map<String, String> serviceProvider = validateResponseObject.evaluate("service_provider"); assertThat(serviceProvider, hasKey("entity_id")); assertThat(serviceProvider.get("entity_id"), equalTo(entityId)); assertThat(serviceProvider, hasKey("acs")); assertThat(serviceProvider.get("acs"), equalTo(acsUrl)); assertThat(validateResponseObject.evaluate("force_authn"), equalTo(forceAuthn)); Map<String, String> authnState = validateResponseObject.evaluate("authn_state"); assertThat(authnState, hasKey("nameid_format")); assertThat(authnState.get("nameid_format"), equalTo(nameIdFormat)); assertThat(authnState, hasKey("authn_request_id")); final String expectedInResponeTo = authnState.get("authn_request_id"); // User login a.k.a exchange the user credentials for an API Key - user can authenticate but shouldn't have access this SP final String apiKeyCredentials = getApiKeyFromCredentials(SAMPLE_USER_NAME, new SecureString(SAMPLE_USER_PASSWORD.toCharArray())); // Make a request to init an SSO flow with the API Key as secondary authentication Request initRequest = new Request("POST", "/_idp/saml/init"); initRequest.setOptions(RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", basicAuthHeaderValue(CONSOLE_USER_NAME, new SecureString(CONSOLE_USER_PASSWORD.toCharArray()))) .addHeader("es-secondary-authorization", "ApiKey " + apiKeyCredentials) .build()); XContentBuilder authnStateBuilder = jsonBuilder(); authnStateBuilder.map(authnState); initRequest.setJsonEntity("{ \"entity_id\":\"" + entityId + "\", \"acs\":\"" + acsUrl + "\"," + "\"authn_state\":" + Strings.toString(authnStateBuilder) + "}"); Response initResponse = getRestClient().performRequest(initRequest); ObjectPath initResponseObject = ObjectPath.createFromResponse(initResponse); assertThat(initResponseObject.evaluate("post_url").toString(), equalTo(acsUrl)); final String body = initResponseObject.evaluate("saml_response").toString(); assertThat(body, containsString("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Requester\"/>")); assertThat(body, containsString("InResponseTo=\"" + expectedInResponeTo + "\"")); Map<String, String> sp = initResponseObject.evaluate("service_provider"); assertThat(sp, hasKey("entity_id")); assertThat(sp.get("entity_id"), equalTo(entityId)); assertThat(initResponseObject.evaluate("error"), equalTo("User [" + SAMPLE_USER_NAME + "] is not permitted to access service [" + entityId + "]")); } public void testSpInitiatedSsoFailsForUnknownSp() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // Validate incoming authentication request Request validateRequest = new Request("POST", "/_idp/saml/validate"); validateRequest.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final String nameIdFormat = TRANSIENT; final String relayString = null; final boolean forceAuthn = randomBoolean(); final AuthnRequest authnRequest = buildAuthnRequest(entityId + randomAlphaOfLength(4), new URL(acsUrl), new URL("https://idp.org/sso/redirect"), nameIdFormat, forceAuthn); final String query = getQueryString(authnRequest, relayString, false, null); validateRequest.setJsonEntity("{\"authn_request_query\":\"" + query + "\"}"); ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(validateRequest)); assertThat(e.getMessage(), containsString("is not known to this Identity Provider")); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); } public void testSpInitiatedSsoFailsForMalformedRequest() throws Exception { String acsUrl = "https://" + randomAlphaOfLength(12) + ".elastic-cloud.com/saml/acs"; String entityId = SP_ENTITY_ID; registerServiceProvider(entityId, acsUrl); registerApplicationPrivileges(); ensureGreen(SamlServiceProviderIndex.INDEX_NAME); // Validate incoming authentication request Request validateRequest = new Request("POST", "/_idp/saml/validate"); validateRequest.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final String nameIdFormat = TRANSIENT; final String relayString = null; final boolean forceAuthn = randomBoolean(); final AuthnRequest authnRequest = buildAuthnRequest(entityId + randomAlphaOfLength(4), new URL(acsUrl), new URL("https://idp.org/sso/redirect"), nameIdFormat, forceAuthn); final String query = getQueryString(authnRequest, relayString, false, null); // Skip http parameter name final String queryWithoutParam = query.substring(12); validateRequest.setJsonEntity("{\"authn_request_query\":\"" + queryWithoutParam + "\"}"); ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(validateRequest)); assertThat(e.getMessage(), containsString("does not contain a SAMLRequest parameter")); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); // arbitrarily trim the request final String malformedRequestQuery = query.substring(0, query.length() - randomIntBetween(10, 15)); validateRequest.setJsonEntity("{\"authn_request_query\":\"" + malformedRequestQuery + "\"}"); ResponseException e1 = expectThrows(ResponseException.class, () -> getRestClient().performRequest(validateRequest)); assertThat(e1.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); } private void registerServiceProvider(String entityId, String acsUrl) throws Exception { internalCluster().ensureAtLeastNumDataNodes(1); ensureYellowAndNoInitializingShards(); Map<String, Object> spFields = new HashMap<>(); spFields.put(SamlServiceProviderDocument.Fields.ACS.getPreferredName(), acsUrl); spFields.put(SamlServiceProviderDocument.Fields.ENTITY_ID.getPreferredName(), entityId); spFields.put(SamlServiceProviderDocument.Fields.NAME_ID.getPreferredName(), TRANSIENT); spFields.put(SamlServiceProviderDocument.Fields.NAME.getPreferredName(), "Dummy SP"); spFields.put("attributes", Map.of( "principal", "https://saml.elasticsearch.org/attributes/principal", "roles", "https://saml.elasticsearch.org/attributes/roles" )); spFields.put("privileges", Map.of( "resource", entityId, "roles", Set.of("sso:(\\w+)") )); Request request = new Request("PUT", "/_idp/saml/sp/" + urlEncode(entityId) + "?refresh=" + WriteRequest.RefreshPolicy.IMMEDIATE.getValue()); request.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.map(spFields); request.setJsonEntity(Strings.toString(builder)); Response registerResponse = getRestClient().performRequest(request); assertThat(registerResponse.getStatusLine().getStatusCode(), equalTo(200)); ObjectPath registerResponseObject = ObjectPath.createFromResponse(registerResponse); Map<String, Object> document = registerResponseObject.evaluate("document"); assertThat(document, hasKey("_created")); assertThat(document.get("_created"), equalTo(true)); Map<String, Object> serviceProvider = registerResponseObject.evaluate("service_provider"); assertThat(serviceProvider, hasKey("entity_id")); assertThat(serviceProvider.get("entity_id"), equalTo(entityId)); assertThat(serviceProvider, hasKey("enabled")); assertThat(serviceProvider.get("enabled"), equalTo(true)); } private void registerApplicationPrivileges() throws IOException { registerApplicationPrivileges(Map.of("deployment_admin", Set.of("sso:superuser"), "deployment_viewer", Set.of("sso:viewer"))); } private void registerApplicationPrivileges(Map<String, Set<String>> privileges) throws IOException { Request request = new Request("PUT", "/_security/privilege?refresh=" + WriteRequest.RefreshPolicy.IMMEDIATE.getValue()); request.setOptions(REQUEST_OPTIONS_AS_CONSOLE_USER); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); builder.startObject("elastic-cloud"); // app-name privileges.forEach((privName, actions) -> { try { builder.startObject(privName); builder.field("actions", actions); builder.endObject(); } catch (IOException e) { throw new UncheckedIOException(e); } }); builder.endObject(); // app-name builder.endObject(); // root request.setJsonEntity(Strings.toString(builder)); Response response = getRestClient().performRequest(request); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private String getApiKeyFromCredentials(String username, SecureString password) { Client client = client().filterWithHeader(Collections.singletonMap("Authorization", UsernamePasswordToken.basicAuthHeaderValue(username, password))); final CreateApiKeyResponse response = new CreateApiKeyRequestBuilder(client) .setName("test key") .setExpiration(TimeValue.timeValueHours(TimeUnit.DAYS.toHours(7L))) .get(); assertNotNull(response); return Base64.getEncoder().encodeToString( (response.getId() + ":" + response.getKey().toString()).getBytes(StandardCharsets.UTF_8)); } private AuthnRequest buildAuthnRequest(String entityId, URL acs, URL destination, String nameIdFormat, boolean forceAuthn) { final Issuer issuer = samlFactory.buildObject(Issuer.class, Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(entityId); final NameIDPolicy nameIDPolicy = samlFactory.buildObject(NameIDPolicy.class, NameIDPolicy.DEFAULT_ELEMENT_NAME); nameIDPolicy.setFormat(nameIdFormat); final AuthnRequest authnRequest = samlFactory.buildObject(AuthnRequest.class, AuthnRequest.DEFAULT_ELEMENT_NAME); authnRequest.setID(samlFactory.secureIdentifier()); authnRequest.setIssuer(issuer); authnRequest.setIssueInstant(now()); authnRequest.setAssertionConsumerServiceURL(acs.toString()); authnRequest.setDestination(destination.toString()); authnRequest.setNameIDPolicy(nameIDPolicy); authnRequest.setForceAuthn(forceAuthn); return authnRequest; } private String getQueryString(AuthnRequest authnRequest, String relayState, boolean sign, @Nullable X509Credential credential) { try { final String request = deflateAndBase64Encode(authnRequest); String queryParam = "SAMLRequest=" + urlEncode(request); if (relayState != null) { queryParam += "&RelayState=" + urlEncode(relayState); } if (sign) { final String algo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256; queryParam += "&SigAlg=" + urlEncode(algo); final byte[] sig = sign(queryParam, algo, credential); queryParam += "&Signature=" + urlEncode(base64Encode(sig)); } return queryParam; } catch (Exception e) { throw new ElasticsearchException("Cannot construct SAML redirect", e); } } private String base64Encode(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } private static String urlEncode(String param) throws UnsupportedEncodingException { return URLEncoder.encode(param, StandardCharsets.UTF_8.name()); } private String deflateAndBase64Encode(SAMLObject message) throws Exception { Deflater deflater = new Deflater(Deflater.DEFLATED, true); try (ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater)) { String messageStr = samlFactory.toString(XMLObjectSupport.marshall(message), false); deflaterStream.write(messageStr.getBytes(StandardCharsets.UTF_8)); deflaterStream.finish(); return base64Encode(bytesOut.toByteArray()); } } private byte[] sign(String text, String algo, X509Credential credential) throws SecurityException { return sign(text.getBytes(StandardCharsets.UTF_8), algo, credential); } private byte[] sign(byte[] content, String algo, X509Credential credential) throws SecurityException { return XMLSigningUtil.signWithURI(credential, algo, content); } private void assertContainsAttributeWithValue(String message, String attribute, String value) { assertThat(message, containsString("<saml2:Attribute FriendlyName=\"" + attribute + "\" Name=\"https://saml.elasticsearch" + ".org/attributes/" + attribute + "\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"><saml2:AttributeValue " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xsd:string\">" + value + "</saml2:AttributeValue></saml2" + ":Attribute>")); } }
apache-2.0
shanalikhan1/NopCommerce_POS
Libraries/Nop.Services/Catalog/ICategoryService.cs
5205
using System.Collections.Generic; using Nop.Core; using Nop.Core.Domain.Catalog; namespace Nop.Services.Catalog { /// <summary> /// Category service interface /// </summary> public partial interface ICategoryService { /// <summary> /// Delete category /// </summary> /// <param name="category">Category</param> void DeleteCategory(Category category); /// <summary> /// Gets all categories /// </summary> /// <param name="categoryName">Category name</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Categories</returns> IPagedList<Category> GetAllCategories(string categoryName = "", int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false); /// <summary> /// Gets all categories filtered by parent category identifier /// </summary> /// <param name="parentCategoryId">Parent category identifier</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Category collection</returns> IList<Category> GetAllCategoriesByParentCategoryId(int parentCategoryId, bool showHidden = false); /// <summary> /// Gets all categories displayed on the home page /// </summary> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Categories</returns> IList<Category> GetAllCategoriesDisplayedOnHomePage(bool showHidden = false); /// <summary> /// Gets a category /// </summary> /// <param name="categoryId">Category identifier</param> /// <returns>Category</returns> Category GetCategoryById(int categoryId); /// <summary> /// Inserts category /// </summary> /// <param name="category">Category</param> void InsertCategory(Category category); /// <summary> /// Updates the category /// </summary> /// <param name="category">Category</param> void UpdateCategory(Category category); /// <summary> /// Update HasDiscountsApplied property (used for performance optimization) /// </summary> /// <param name="category">Category</param> void UpdateHasDiscountsApplied(Category category); /// <summary> /// Deletes a product category mapping /// </summary> /// <param name="productCategory">Product category</param> void DeleteProductCategory(ProductCategory productCategory); /// <summary> /// Gets product category mapping collection /// </summary> /// <param name="categoryId">Category identifier</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Product a category mapping collection</returns> IPagedList<ProductCategory> GetProductCategoriesByCategoryId(int categoryId, int pageIndex, int pageSize, bool showHidden = false); /// <summary> /// Gets a product category mapping collection /// </summary> /// <param name="productId">Product identifier</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Product category mapping collection</returns> IList<ProductCategory> GetProductCategoriesByProductId(int productId, bool showHidden = false); /// <summary> /// Gets a product category mapping collection /// </summary> /// <param name="productId">Product identifier</param> /// <param name="storeId">Store identifier (used in multi-store environment). "showHidden" parameter should also be "true"</param> /// <param name="showHidden"> A value indicating whether to show hidden records</param> /// <returns> Product category mapping collection</returns> IList<ProductCategory> GetProductCategoriesByProductId(int productId, int storeId, bool showHidden = false); /// <summary> /// Gets a product category mapping /// </summary> /// <param name="productCategoryId">Product category mapping identifier</param> /// <returns>Product category mapping</returns> ProductCategory GetProductCategoryById(int productCategoryId); /// <summary> /// Inserts a product category mapping /// </summary> /// <param name="productCategory">>Product category mapping</param> void InsertProductCategory(ProductCategory productCategory); /// <summary> /// Updates the product category mapping /// </summary> /// <param name="productCategory">>Product category mapping</param> void UpdateProductCategory(ProductCategory productCategory); } }
apache-2.0