repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
HuygensING/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/dropwizard/contenttypes/SerializerWriterRegistry.java
1216
package nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes; import nl.knaw.huygens.timbuctoo.v5.dropwizard.SupportedExportFormats; import java.util.HashMap; import java.util.Optional; import java.util.Set; import static java.lang.String.format; public class SerializerWriterRegistry implements SupportedExportFormats { private HashMap<String, SerializerWriter> supportedMimeTypes; public SerializerWriterRegistry(SerializerWriter... writers) { supportedMimeTypes = new HashMap<>(); for (SerializerWriter writer : writers) { register(writer); } } @Override public Set<String> getSupportedMimeTypes() { return supportedMimeTypes.keySet(); } private void register(SerializerWriter serializerWriter) { String mimeType = serializerWriter.getMimeType(); SerializerWriter added = supportedMimeTypes.putIfAbsent(mimeType, serializerWriter); if (added != null) { throw new RuntimeException(format("Timbuctoo supports only one serializer writer for '%s'", mimeType)); } } public Optional<SerializerWriter> getBestMatch(String acceptHeader) { return MimeParser.bestMatch(supportedMimeTypes.keySet(), acceptHeader).map(supportedMimeTypes::get); } }
gpl-3.0
arcusys/Valamis
valamis-updaters/src/main/scala/com/arcusys/valamis/updaters/common/BaseDBUpdater.scala
798
package com.arcusys.valamis.updaters.common import com.arcusys.learn.liferay.LiferayClasses.LUpgradeProcess import com.arcusys.learn.liferay.util.DataAccessUtil import com.arcusys.slick.migration.dialect.Dialect import com.arcusys.valamis.persistence.common.{SlickDBInfo, SlickDBInfoLiferayImpl, SlickProfile} /** * Created by pkornilov on 8/30/16. */ abstract class BaseDBUpdater extends LUpgradeProcess with SlickProfile { lazy val dbInfo: SlickDBInfo = new SlickDBInfoLiferayImpl(DataAccessUtil.getDataSource) lazy val db = dbInfo.databaseDef lazy val O = driver.columnOptions implicit lazy val dialect = Dialect(dbInfo.slickDriver) .getOrElse(throw new Exception(s"There is no dialect for driver ${dbInfo.slickDriver}")) override lazy val driver = dbInfo.slickDriver }
gpl-3.0
GotoLink/Battlegear2
src/api/java/org/bukkit/craftbukkit/event/CraftEventFactory.java
693
package org.bukkit.craftbukkit.event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import org.bukkit.event.player.PlayerInteractEvent; public class CraftEventFactory { public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, ItemStack stack){ return callPlayerInteractEvent(player, action, 0, 256, 0, 0, stack); } public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, int x, int y, int z, int face, ItemStack stack){ return new PlayerInteractEvent(); } }
gpl-3.0
javiermatias/jbc-utn-frc
3ro/TSB/final/util/src/tsb/examenFinal/util/Balance.java
1495
package tsb.examenFinal.util; import java.util.Stack; /** * * Verifica el balanceo de caractertes de apertura y cierre * como [] {} <> */ public abstract class Balance { public static boolean isBalanced(final String str, final char c0, final char c1) { boolean toReturn; if (c0 == c1) { toReturn = isSameBalanced(str, c0); } else { toReturn = isNotSameBalanced(str, c0, c1); } return toReturn; } private static boolean isSameBalanced(final String str, final char c0) { char[] array = str.toCharArray(); int count = 0; for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == c0) { count++; } } int proc = (count / 2) * 2; return (count == proc); } private static boolean isNotSameBalanced(final String str, final char c0, final char c1) { char[] array = str.toCharArray(); Stack<String> stack = new Stack<String>(); for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == c0) { stack.add(String.valueOf(c)); } else if (c == c1) { if (stack.isEmpty() == false && stack.peek().charAt(0) == c0) { stack.pop(); } else { stack.push(String.valueOf(c)); } } } return stack.isEmpty(); } }
gpl-3.0
simalytics/askbot-devel
static/default/media/js/post.js
160054
/* Scripts for cnprog.com Project Name: Lanai All Rights Resevred 2008. CNPROG.COM */ var lanai = { /** * Finds any <pre><code></code></pre> tags which aren't registered for * pretty printing, adds the appropriate class name and invokes prettify. */ highlightSyntax: function(){ var styled = false; $("pre code").parent().each(function(){ if (!$(this).hasClass('prettyprint')){ $(this).addClass('prettyprint'); styled = true; } }); if (styled){ prettyPrint(); } } }; //todo: clean-up now there is utils:WaitIcon function appendLoader(element) { loading = gettext('loading...') element.append('<img class="ajax-loader" ' + 'src="' + mediaUrl("media/images/indicator.gif") + '" title="' + loading + '" alt="' + loading + '" />'); } function removeLoader() { $("img.ajax-loader").remove(); } function setSubmitButtonDisabled(form, isDisabled) { form.find('input[type="submit"]').attr("disabled", isDisabled); } function enableSubmitButton(form) { setSubmitButtonDisabled(form, false); } function disableSubmitButton(form) { setSubmitButtonDisabled(form, true); } function setupFormValidation(form, validationRules, validationMessages, onSubmitCallback) { enableSubmitButton(form); form.validate({ debug: true, rules: (validationRules ? validationRules : {}), messages: (validationMessages ? validationMessages : {}), errorElement: "span", errorClass: "form-error", errorPlacement: function(error, element) { var span = element.next().find("span.form-error"); if (span.length === 0) { span = element.parent().find("span.form-error"); if (span.length === 0){ //for resizable textarea var element_id = element.attr('id'); span = $('label[for="' + element_id + '"]'); } } span.replaceWith(error); }, submitHandler: function(form_dom) { disableSubmitButton($(form_dom)); if (onSubmitCallback){ onSubmitCallback(); } else{ form_dom.submit(); } } }); } /** * generic tag cleaning function, settings * are from askbot live settings and askbot.const */ var cleanTag = function(tag_name, settings) { var tag_regex = new RegExp(settings['tag_regex']); if (tag_regex.test(tag_name) === false) { throw settings['messages']['wrong_chars'] } var max_length = settings['max_tag_length']; if (tag_name.length > max_length) { throw interpolate( ngettext( 'must be shorter than %(max_chars)s character', 'must be shorter than %(max_chars)s characters', max_length ), {'max_chars': max_length }, true ); } if (settings['force_lowercase_tags']) { return tag_name.toLowerCase(); } else { return tag_name; } }; var validateTagLength = function(value){ var tags = getUniqueWords(value); var are_tags_ok = true; $.each(tags, function(index, value){ if (value.length > askbot['settings']['maxTagLength']){ are_tags_ok = false; } }); return are_tags_ok; }; var validateTagCount = function(value){ var tags = getUniqueWords(value); return (tags.length <= askbot['settings']['maxTagsPerPost']); }; $.validator.addMethod('limit_tag_count', validateTagCount); $.validator.addMethod('limit_tag_length', validateTagLength); var CPValidator = function() { return { getQuestionFormRules : function() { return { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: 105, limit_tag_count: true, limit_tag_length: true }, text: { minlength: askbot['settings']['minQuestionBodyLength'] }, title: { minlength: askbot['settings']['minTitleLength'] } }; }, getQuestionFormMessages: function(){ return { tags: { required: " " + gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] }, text: { required: " " + gettext('details are required'), minlength: interpolate( ngettext( 'details must have > %s character', 'details must have > %s characters', askbot['settings']['minQuestionBodyLength'] ), [askbot['settings']['minQuestionBodyLength'], ] ) }, title: { required: " " + gettext('enter your question'), minlength: interpolate( ngettext( 'question must have > %s character', 'question must have > %s characters', askbot['settings']['minTitleLength'] ), [askbot['settings']['minTitleLength'], ] ) } }; }, getAnswerFormRules : function(){ return { text: { minlength: askbot['settings']['minAnswerBodyLength'] }, }; }, getAnswerFormMessages: function(){ return { text: { required: " " + gettext('content cannot be empty'), minlength: interpolate( ngettext( 'answer must be > %s character', 'answer must be > %s characters', askbot['settings']['minAnswerBodyLength'] ), [askbot['settings']['minAnswerBodyLength'], ] ) }, } } }; }(); /** * @constructor */ var ThreadUsersDialog = function() { SimpleControl.call(this); this._heading_text = 'Add heading with the setHeadingText()'; }; inherits(ThreadUsersDialog, SimpleControl); ThreadUsersDialog.prototype.setHeadingText = function(text) { this._heading_text = text; }; ThreadUsersDialog.prototype.showUsers = function(html) { this._dialog.setContent(html); this._dialog.show(); }; ThreadUsersDialog.prototype.startShowingUsers = function() { var me = this; var threadId = this._threadId; var url = this._url; $.ajax({ type: 'GET', data: {'thread_id': threadId}, dataType: 'json', url: url, cache: false, success: function(data){ if (data['success'] == true){ me.showUsers(data['html']); } else { showMessage(me.getElement(), data['message'], 'after'); } } }); }; ThreadUsersDialog.prototype.decorate = function(element) { this._element = element; ThreadUsersDialog.superClass_.decorate.call(this, element); this._threadId = element.data('threadId'); this._url = element.data('url'); var dialog = new ModalDialog(); dialog.setRejectButtonText(''); dialog.setAcceptButtonText(gettext('Back to the question')); dialog.setHeadingText(this._heading_text); dialog.setAcceptHandler(function(){ dialog.hide(); }); var dialog_element = dialog.getElement(); $(dialog_element).find('.modal-footer').css('text-align', 'center'); $(document).append(dialog_element); this._dialog = dialog; var me = this; this.setHandler(function(){ me.startShowingUsers(); }); }; /** * @constructor */ var DraftPost = function() { WrappedElement.call(this); }; inherits(DraftPost, WrappedElement); /** * @return {string} */ DraftPost.prototype.getUrl = function() { throw 'Not Implemented'; }; /** * @return {boolean} */ DraftPost.prototype.shouldSave = function() { throw 'Not Implemented'; }; /** * @return {object} data dict */ DraftPost.prototype.getData = function() { throw 'Not Implemented'; }; DraftPost.prototype.backupData = function() { this._old_data = this.getData(); }; DraftPost.prototype.showNotification = function() { var note = $('.editor-status span'); note.hide(); note.html(gettext('draft saved...')); note.fadeIn().delay(3000).fadeOut(); }; DraftPost.prototype.getSaveHandler = function() { var me = this; return function(save_synchronously) { if (me.shouldSave()) { $.ajax({ type: 'POST', cache: false, dataType: 'json', async: save_synchronously ? false : true, url: me.getUrl(), data: me.getData(), success: function(data) { if (data['success'] && !save_synchronously) { me.showNotification(); } me.backupData(); } }); } }; }; DraftPost.prototype.decorate = function(element) { this._element = element; this.assignContentElements(); this.backupData(); setInterval(this.getSaveHandler(), 30000);//auto-save twice a minute var me = this; window.onbeforeunload = function() { var saveHandler = me.getSaveHandler(); saveHandler(true); //var msg = gettext("%s, we've saved your draft, but..."); //return interpolate(msg, [askbot['data']['userName']]); }; }; /** * @contstructor */ var DraftQuestion = function() { DraftPost.call(this); }; inherits(DraftQuestion, DraftPost); DraftQuestion.prototype.getUrl = function() { return askbot['urls']['saveDraftQuestion']; }; DraftQuestion.prototype.shouldSave = function() { var newd = this.getData(); var oldd = this._old_data; return ( newd['title'] !== oldd['title'] || newd['text'] !== oldd['text'] || newd['tagnames'] !== oldd['tagnames'] ); }; DraftQuestion.prototype.getData = function() { return { 'title': this._title_element.val(), 'text': this._text_element.val(), 'tagnames': this._tagnames_element.val() }; }; DraftQuestion.prototype.assignContentElements = function() { this._title_element = $('#id_title'); this._text_element = $('#editor'); this._tagnames_element = $('#id_tags'); }; var DraftAnswer = function() { DraftPost.call(this); }; inherits(DraftAnswer, DraftPost); DraftAnswer.prototype.setThreadId = function(id) { this._threadId = id; }; DraftAnswer.prototype.getUrl = function() { return askbot['urls']['saveDraftAnswer']; }; DraftAnswer.prototype.shouldSave = function() { return this.getData()['text'] !== this._old_data['text']; }; DraftAnswer.prototype.getData = function() { return { 'text': this._textElement.val(), 'thread_id': this._threadId }; }; DraftAnswer.prototype.assignContentElements = function() { this._textElement = $('#editor'); }; /** * @constructor * @extends {SimpleControl} * @param {Comment} comment to upvote */ var CommentVoteButton = function(comment){ SimpleControl.call(this); /** * @param {Comment} */ this._comment = comment; /** * @type {boolean} */ this._voted = false; /** * @type {number} */ this._score = 0; }; inherits(CommentVoteButton, SimpleControl); /** * @param {number} score */ CommentVoteButton.prototype.setScore = function(score){ this._score = score; if (this._element){ this._element.html(score); } }; /** * @param {boolean} voted */ CommentVoteButton.prototype.setVoted = function(voted){ this._voted = voted; if (this._element){ this._element.addClass('upvoted'); } }; CommentVoteButton.prototype.getVoteHandler = function(){ var me = this; var comment = this._comment; return function(){ var voted = me._voted; var post_id = me._comment.getId(); var data = { cancel_vote: voted ? true:false, post_id: post_id }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['upvote_comment'], cache: false, success: function(data){ if (data['success'] == true){ me.setScore(data['score']); me.setVoted(true); } else { showMessage(comment.getElement(), data['message'], 'after'); } } }); }; }; CommentVoteButton.prototype.decorate = function(element){ this._element = element; this.setHandler(this.getVoteHandler()); var element = this._element; var comment = this._comment; /* can't call comment.getElement() here due * an issue in the getElement() of comment * so use an "illegal" access to comment._element here */ comment._element.mouseenter(function(){ //outside height may not be known //var height = comment.getElement().height(); //element.height(height); element.addClass('hover'); }); comment._element.mouseleave(function(){ element.removeClass('hover'); }); }; CommentVoteButton.prototype.createDom = function(){ this._element = this.makeElement('div'); if (this._score > 0){ this._element.html(this._score); } this._element.addClass('upvote'); if (this._voted){ this._element.addClass('upvoted'); } this.decorate(this._element); }; /** * legacy Vote class * handles all sorts of vote-like operations */ var Vote = function(){ // All actions are related to a question var questionId; //question slug to build redirect urls var questionSlug; // The object we operate on actually. It can be a question or an answer. var postId; var questionAuthorId; var currentUserId; var answerContainerIdPrefix = 'post-id-'; var voteContainerId = 'vote-buttons'; var imgIdPrefixAccept = 'answer-img-accept-'; var classPrefixFollow= 'button follow'; var classPrefixFollowed= 'button followed'; var imgIdPrefixQuestionVoteup = 'question-img-upvote-'; var imgIdPrefixQuestionVotedown = 'question-img-downvote-'; var imgIdPrefixAnswerVoteup = 'answer-img-upvote-'; var imgIdPrefixAnswerVotedown = 'answer-img-downvote-'; var divIdFavorite = 'favorite-number'; var commentLinkIdPrefix = 'comment-'; var voteNumberClass = "vote-number"; var offensiveIdPrefixQuestionFlag = 'question-offensive-flag-'; var removeOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-flag-'; var removeAllOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-all-flag-'; var offensiveIdPrefixAnswerFlag = 'answer-offensive-flag-'; var removeOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-flag-'; var removeAllOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-all-flag-'; var offensiveClassFlag = 'offensive-flag'; var questionControlsId = 'question-controls'; var removeAnswerLinkIdPrefix = 'answer-delete-link-'; var questionSubscribeUpdates = 'question-subscribe-updates'; var questionSubscribeSidebar= 'question-subscribe-sidebar'; var acceptAnonymousMessage = gettext('insufficient privilege'); var acceptOwnAnswerMessage = gettext('cannot pick own answer as best'); var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; var favoriteAnonymousMessage = gettext('anonymous users cannot follow questions') + pleaseLogin; var subscribeAnonymousMessage = gettext('anonymous users cannot subscribe to questions') + pleaseLogin; var voteAnonymousMessage = gettext('anonymous users cannot vote') + pleaseLogin; //there were a couple of more messages... var offensiveConfirmation = gettext('please confirm offensive'); var removeOffensiveConfirmation = gettext('please confirm removal of offensive flag'); var offensiveAnonymousMessage = gettext('anonymous users cannot flag offensive posts') + pleaseLogin; var removeConfirmation = gettext('confirm delete'); var removeAnonymousMessage = gettext('anonymous users cannot delete/undelete') + pleaseLogin; var recoveredMessage = gettext('post recovered'); var deletedMessage = gettext('post deleted'); var VoteType = { acceptAnswer : 0, questionUpVote : 1, questionDownVote : 2, favorite : 4, answerUpVote: 5, answerDownVote:6, offensiveQuestion : 7, removeOffensiveQuestion : 7.5, removeAllOffensiveQuestion : 7.6, offensiveAnswer:8, removeOffensiveAnswer:8.5, removeAllOffensiveAnswer:8.6, removeQuestion: 9,//deprecate removeAnswer:10,//deprecate questionSubscribeUpdates:11, questionUnsubscribeUpdates:12 }; var getFavoriteButton = function(){ var favoriteButton = 'div.'+ voteContainerId +' a[class="'+ classPrefixFollow +'"]'; favoriteButton += ', div.'+ voteContainerId +' a[class="'+ classPrefixFollowed +'"]'; return $(favoriteButton); }; var getFavoriteNumber = function(){ var favoriteNumber = '#'+ divIdFavorite ; return $(favoriteNumber); }; var getQuestionVoteUpButton = function(){ var questionVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVoteup +'"]'; return $(questionVoteUpButton); }; var getQuestionVoteDownButton = function(){ var questionVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVotedown +'"]'; return $(questionVoteDownButton); }; var getAnswerVoteUpButtons = function(){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVoteup +'"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButtons = function(){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVotedown +'"]'; return $(answerVoteDownButton); }; var getAnswerVoteUpButton = function(id){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVoteup + id + '"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButton = function(id){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVotedown + id + '"]'; return $(answerVoteDownButton); }; var getOffensiveQuestionFlag = function(){ var offensiveQuestionFlag = '.question-card span[id^="'+ offensiveIdPrefixQuestionFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveQuestionFlag = function(){ var removeOffensiveQuestionFlag = '.question-card span[id^="'+ removeOffensiveIdPrefixQuestionFlag +'"]'; return $(removeOffensiveQuestionFlag); }; var getRemoveAllOffensiveQuestionFlag = function(){ var removeAllOffensiveQuestionFlag = '.question-card span[id^="'+ removeAllOffensiveIdPrefixQuestionFlag +'"]'; return $(removeAllOffensiveQuestionFlag); }; var getOffensiveAnswerFlags = function(){ var offensiveQuestionFlag = 'div.answer span[id^="'+ offensiveIdPrefixAnswerFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveAnswerFlag = function(){ var removeOffensiveAnswerFlag = 'div.answer span[id^="'+ removeOffensiveIdPrefixAnswerFlag +'"]'; return $(removeOffensiveAnswerFlag); }; var getRemoveAllOffensiveAnswerFlag = function(){ var removeAllOffensiveAnswerFlag = 'div.answer span[id^="'+ removeAllOffensiveIdPrefixAnswerFlag +'"]'; return $(removeAllOffensiveAnswerFlag); }; var getquestionSubscribeUpdatesCheckbox = function(){ return $('#' + questionSubscribeUpdates); }; var getquestionSubscribeSidebarCheckbox= function(){ return $('#' + questionSubscribeSidebar); }; var getremoveAnswersLinks = function(){ var removeAnswerLinks = 'div.answer-controls a[id^="'+ removeAnswerLinkIdPrefix +'"]'; return $(removeAnswerLinks); }; var setVoteImage = function(voteType, undo, object){ var flag = undo ? false : true; if (object.hasClass("on")) { object.removeClass("on"); }else{ object.addClass("on"); } if(undo){ if(voteType == VoteType.questionUpVote || voteType == VoteType.questionDownVote){ $(getQuestionVoteUpButton()).removeClass("on"); $(getQuestionVoteDownButton()).removeClass("on"); } else{ $(getAnswerVoteUpButton(postId)).removeClass("on"); $(getAnswerVoteDownButton(postId)).removeClass("on"); } } }; var setVoteNumber = function(object, number){ var voteNumber = object.parent('div.'+ voteContainerId).find('div.'+ voteNumberClass); $(voteNumber).text(number); }; var bindEvents = function(){ // accept answers var acceptedButtons = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAccept +'"]'; $(acceptedButtons).unbind('click').click(function(event){ Vote.accept($(event.target)); }); // set favorite question var favoriteButton = getFavoriteButton(); favoriteButton.unbind('click').click(function(event){ //Vote.favorite($(event.target)); Vote.favorite(favoriteButton); }); // question vote up var questionVoteUpButton = getQuestionVoteUpButton(); questionVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionUpVote); }); var questionVoteDownButton = getQuestionVoteDownButton(); questionVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionDownVote); }); var answerVoteUpButton = getAnswerVoteUpButtons(); answerVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerUpVote); }); var answerVoteDownButton = getAnswerVoteDownButtons(); answerVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerDownVote); }); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveAllOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); getRemoveAllOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveAnswer); }); getquestionSubscribeUpdatesCheckbox().unbind('click').click(function(event){ //despeluchar esto if (this.checked){ getquestionSubscribeSidebarCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeSidebarCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getquestionSubscribeSidebarCheckbox().unbind('click').click(function(event){ if (this.checked){ getquestionSubscribeUpdatesCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeUpdatesCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getremoveAnswersLinks().unbind('click').click(function(event){ Vote.remove(this, VoteType.removeAnswer); }); }; var submit = function(object, voteType, callback) { //this function submits votes $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": voteType, "postId": postId }, error: handleFail, success: function(data) { callback(object, voteType, data); } }); }; var handleFail = function(xhr, msg){ alert("Callback invoke error: " + msg); }; // callback function for Accept Answer action var callback_accept = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage(object, acceptAnonymousMessage); } else if(data.allowed == "-1"){ showMessage(object, acceptOwnAnswerMessage); } else if(data.status == "1"){ $("#"+answerContainerIdPrefix+postId).removeClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).removeClass("comment-link-accepted"); } else if(data.success == "1"){ var answers = ('div[id^="'+answerContainerIdPrefix +'"]'); $(answers).removeClass('accepted-answer'); var commentLinks = ('div[id^="'+answerContainerIdPrefix +'"] div[id^="'+ commentLinkIdPrefix +'"]'); $(commentLinks).removeClass("comment-link-accepted"); $("#"+answerContainerIdPrefix+postId).addClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).addClass("comment-link-accepted"); } else{ showMessage(object, data.message); } }; var callback_favorite = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage( object, favoriteAnonymousMessage.replace( '{{QuestionID}}', questionId).replace( '{{questionSlug}}', '' ) ); } else if(data.status == "1"){ var follow_html = gettext('Follow'); object.attr("class", 'button follow'); object.html(follow_html); var fav = getFavoriteNumber(); fav.removeClass("my-favorite-number"); if(data.count === 0){ data.count = ''; fav.text(''); }else{ var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); } } else if(data.success == "1"){ var followed_html = gettext('<div>Following</div><div class="unfollow">Unfollow</div>'); object.html(followed_html); object.attr("class", 'button followed'); var fav = getFavoriteNumber(); var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); fav.addClass("my-favorite-number"); } else{ showMessage(object, data.message); } }; var callback_vote = function(object, voteType, data){ if (data.success == '0'){ showMessage(object, data.message); return; } else { if (data.status == '1'){ setVoteImage(voteType, true, object); } else { setVoteImage(voteType, false, object); } setVoteNumber(object, data.count); if (data.message && data.message.length > 0){ showMessage(object, data.message); } return; } //may need to take a look at this again if (data.status == "1"){ setVoteImage(voteType, true, object); setVoteNumber(object, data.count); } else if (data.success == "1"){ setVoteImage(voteType, false, object); setVoteNumber(object, data.count); if (data.message.length > 0){ showMessage(object, data.message); } } }; var callback_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("remove flag")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("flag-", "remove-flag-")); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0){ $(object).children('span[class="darkred"]').text("("+ data.count +")"); } else{ $(object).children('span[class="darkred"]').text(""); // Remove "remove all flags link" since there are no more flags to remove var remove_all = $(object).siblings('span.offensive-flag[id*="-offensive-remove-all-flag-"]'); $(remove_all).next("span.sep").remove(); $(remove_all).remove(); } // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("flag offensive")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("remove-flag-", "flag-")); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_all_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // remove the link. All flags are gone var remove_own = $(object).siblings('span.offensive-flag[id*="-offensive-remove-flag-"]'); $(remove_own).find("a.question-flag").html(gettext("flag offensive")); $(remove_own).attr("id", $(remove_own).attr("id").replace("remove-flag-", "flag-")); $(object).next("span.sep").remove(); $(object).remove(); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove = function(object, voteType, data){ if (data.success == "1"){ if (removeActionType == 'delete'){ postNode.addClass('deleted'); postRemoveLink.innerHTML = gettext('undelete'); showMessage(object, deletedMessage); } else if (removeActionType == 'undelete') { postNode.removeClass('deleted'); postRemoveLink.innerHTML = gettext('delete'); showMessage(object, recoveredMessage); } } else { showMessage(object, data.message) } }; return { init : function(qId, qSlug, questionAuthor, userId){ questionId = qId; questionSlug = qSlug; questionAuthorId = questionAuthor; currentUserId = '' + userId;//convert to string bindEvents(); }, //accept answer accept: function(object){ postId = object.attr("id").substring(imgIdPrefixAccept.length); submit(object, VoteType.acceptAnswer, callback_accept); }, //mark question as favorite favorite: function(object){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( object, favoriteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } postId = questionId; submit(object, VoteType.favorite, callback_favorite); }, vote: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE") { if (voteType == VoteType.questionSubscribeUpdates || voteType == VoteType.questionUnsubscribeUpdates){ getquestionSubscribeSidebarCheckbox().removeAttr('checked'); getquestionSubscribeUpdatesCheckbox().removeAttr('checked'); showMessage(object, subscribeAnonymousMessage); } else { showMessage( $(object), voteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); } return false; } // up and downvote processor if (voteType == VoteType.answerUpVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVoteup.length); } else if (voteType == VoteType.answerDownVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVotedown.length); } else { postId = questionId; } submit(object, voteType, callback_vote); }, //flag offensive offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(offensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_offensive); } }, //remove flag offensive remove_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_offensive); } }, remove_all_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_all_offensive); } }, //delete question or answer (comments are deleted separately) remove: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), removeAnonymousMessage.replace( '{{QuestionID}}', questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } bits = object.id.split('-'); postId = bits.pop();/* this seems to be used within submit! */ postType = bits.shift(); var do_proceed = false; postNode = $('#post-id-' + postId); postRemoveLink = object; if (postNode.hasClass('deleted')) { removeActionType = 'undelete'; do_proceed = true; } else { removeActionType = 'delete'; do_proceed = confirm(removeConfirmation); } if (do_proceed) { submit($(object), voteType, callback_remove); } } }; } (); var questionRetagger = function(){ var oldTagsHTML = ''; var tagInput = null; var tagsDiv = null; var retagLink = null; var restoreEventHandlers = function(){ $(document).unbind('click'); }; var cancelRetag = function(){ tagsDiv.html(oldTagsHTML); tagsDiv.removeClass('post-retag'); tagsDiv.addClass('post-tags'); restoreEventHandlers(); initRetagger(); }; var drawNewTags = function(new_tags){ tagsDiv.empty(); if (new_tags === ''){ return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tagsDiv.append(tag.getElement()); }); }; var doRetag = function(){ $.ajax({ type: "POST", url: retagUrl,//todo add this url to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; cancelRetag(); drawNewTags(new_tags.join(' ')); if (json['message']) { notify.show(json['message']); } } else { cancelRetag(); showMessage(tagsDiv, json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, gettext('sorry, something is not right here')); cancelRetag(); } }); return false; } var setupInputEventHandlers = function(input){ input.keydown(function(e){ if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)){ cancelRetag(); } }); $(document).unbind('click').click(cancelRetag, false); input.click(function(){return false}); }; var createRetagForm = function(old_tags_string){ var div = $('<form method="post"></form>'); tagInput = $('<input id="retag_tags" type="text" autocomplete="off" name="tags" size="30"/>'); //var tagLabel = $('<label for="retag_tags" class="error"></label>'); //populate input var tagAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagAc.decorate(tagInput); tagInput.val(old_tags_string); div.append(tagInput); //div.append(tagLabel); setupInputEventHandlers(tagInput); //button = $('<input type="submit" />'); //button.val(gettext('save tags')); //div.append(button); //setupButtonEventHandlers(button); div.validate({//copy-paste from utils.js rules: { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: askbot['settings']['maxTagsPerPost'] * askbot['settings']['maxTagLength'], limit_tag_count: true, limit_tag_length: true } }, messages: { tags: { required: gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] } }, submitHandler: doRetag, errorClass: "retag-error" }); return div; }; var getTagsAsString = function(tags_div){ var links = tags_div.find('a'); var tags_str = ''; links.each(function(index, element){ if (index === 0){ //this is pretty bad - we should use Tag.getName() tags_str = $(element).data('tagName'); } else { tags_str += ' ' + $(element).data('tagName'); } }); return tags_str; }; var noopHandler = function(){ tagInput.focus(); return false; }; var deactivateRetagLink = function(){ retagLink.unbind('click').click(noopHandler); retagLink.unbind('keypress').keypress(noopHandler); }; var startRetag = function(){ tagsDiv = $('#question-tags'); oldTagsHTML = tagsDiv.html();//save to restore on cancel var old_tags_string = getTagsAsString(tagsDiv); var retag_form = createRetagForm(old_tags_string); tagsDiv.html(''); tagsDiv.append(retag_form); tagsDiv.removeClass('post-tags'); tagsDiv.addClass('post-retag'); tagInput.focus(); deactivateRetagLink(); return false; }; var setupClickAndEnterHandler = function(element, callback){ element.unbind('click').click(callback); element.unbind('keypress').keypress(function(e){ if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ callback(); } }); } var initRetagger = function(){ setupClickAndEnterHandler(retagLink, startRetag); }; return { init: function(){ retagLink = $('#retag'); initRetagger(); } }; }(); /** * @constructor * Controls vor voting for a post */ var VoteControls = function() { WrappedElement.call(this); this._postAuthorId = undefined; this._postId = undefined; }; inherits(VoteControls, WrappedElement); VoteControls.prototype.setPostId = function(postId) { this._postId = postId; }; VoteControls.prototype.getPostId = function() { return this._postId; }; VoteControls.prototype.setPostAuthorId = function(userId) { this._postAuthorId = userId; }; VoteControls.prototype.setSlug = function(slug) { this._slug = slug; }; VoteControls.prototype.setPostType = function(postType) { this._postType = postType; }; VoteControls.prototype.getPostType = function() { return this._postType; }; VoteControls.prototype.clearVotes = function() { this._upvoteButton.removeClass('on'); this._downvoteButton.removeClass('on'); }; VoteControls.prototype.toggleButton = function(button) { if (button.hasClass('on')) { button.removeClass('on'); } else { button.addClass('on'); } }; VoteControls.prototype.toggleVote = function(voteType) { if (voteType === 'upvote') { this.toggleButton(this._upvoteButton); } else { this.toggleButton(this._downvoteButton); } }; VoteControls.prototype.setVoteCount = function(count) { this._voteCount.html(count); }; VoteControls.prototype.updateDisplay = function(voteType, data) { if (data['status'] == '1'){ this.clearVotes(); } else { this.toggleVote(voteType); } this.setVoteCount(data['count']); if (data['message'] && data['message'].length > 0){ showMessage(this._element, data.message); } }; VoteControls.prototype.getAnonymousMessage = function(message) { var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; message += pleaseLogin; message = message.replace("{{QuestionID}}", this._postId); return message.replace('{{questionSlug}}', this._slug); }; VoteControls.prototype.getVoteHandler = function(voteType) { var me = this; return function() { if (askbot['data']['userIsAuthenticated'] === false) { var message = me.getAnonymousMessage(gettext('anonymous users cannot vote')); showMessage(me.getElement(), message); } else { //this function submits votes var voteMap = { 'question': { 'upvote': 1, 'downvote': 2 }, 'answer': { 'upvote': 5, 'downvote': 6 } }; var legacyVoteType = voteMap[me.getPostType()][voteType]; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": legacyVoteType, "postId": me.getPostId() }, error: function() { showMessage(me.getElement(), gettext('sorry, something is not right here')); }, success: function(data) { if (data['success']) { me.updateDisplay(voteType, data); } else { showMessage(me.getElement(), data['message']); } } }); } }; }; VoteControls.prototype.decorate = function(element) { this._element = element; var upvoteButton = element.find('.upvote'); this._upvoteButton = upvoteButton; setupButtonEventHandlers(upvoteButton, this.getVoteHandler('upvote')); var downvoteButton = element.find('.downvote'); this._downvoteButton = downvoteButton; setupButtonEventHandlers(downvoteButton, this.getVoteHandler('downvote')); this._voteCount = element.find('.vote-number'); }; var DeletePostLink = function(){ SimpleControl.call(this); this._post_id = null; }; inherits(DeletePostLink, SimpleControl); DeletePostLink.prototype.setPostId = function(id){ this._post_id = id; }; DeletePostLink.prototype.getPostId = function(){ return this._post_id; }; DeletePostLink.prototype.getPostElement = function(){ return $('#post-id-' + this.getPostId()); }; DeletePostLink.prototype.isPostDeleted = function(){ return this._post_deleted; }; DeletePostLink.prototype.setPostDeleted = function(is_deleted){ var post = this.getPostElement(); if (is_deleted === true){ post.addClass('deleted'); this._post_deleted = true; this.getElement().html(gettext('undelete')); } else if (is_deleted === false){ post.removeClass('deleted'); this._post_deleted = false; this.getElement().html(gettext('delete')); } }; DeletePostLink.prototype.getDeleteHandler = function(){ var me = this; var post_id = this.getPostId(); return function(){ var data = { 'post_id': me.getPostId(), //todo rename cancel_vote -> undo 'cancel_vote': me.isPostDeleted() ? true: false }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['delete_post'], cache: false, success: function(data){ if (data['success'] == true){ me.setPostDeleted(data['is_deleted']); } else { showMessage(me.getElement(), data['message']); } } }); }; }; DeletePostLink.prototype.decorate = function(element){ this._element = element; this._post_deleted = this.getPostElement().hasClass('deleted'); this.setHandler(this.getDeleteHandler()); } /** * Form for editing and posting new comment * supports 3 editors: markdown, tinymce and plain textarea. * There is only one instance of this form in use on the question page. * It can be attached to any comment on the page, or to a new blank * comment. */ var EditCommentForm = function(){ WrappedElement.call(this); this._comment = null; this._comment_widget = null; this._element = null; this._editorReady = false; this._text = ''; }; inherits(EditCommentForm, WrappedElement); EditCommentForm.prototype.setWaitingStatus = function(isWaiting) { if (isWaiting === true) { this._editor.getElement().hide(); this._submit_btn.hide(); this._cancel_btn.hide(); this._minorEditBox.hide(); this._element.hide(); } else { this._element.show(); this._editor.getElement().show(); this._submit_btn.show(); this._cancel_btn.show(); this._minorEditBox.show(); } }; EditCommentForm.prototype.getEditorType = function() { if (askbot['settings']['commentsEditorType'] === 'rich-text') { return askbot['settings']['editorType']; } else { return 'plain-text'; } }; EditCommentForm.prototype.startTinyMCEEditor = function() { var editorId = this.makeId('comment-editor'); var opts = { mode: 'exact', content_css: mediaUrl('media/style/tinymce/comments-content.css'), elements: editorId, plugins: 'autoresize', theme: 'advanced', theme_advanced_toolbar_location: 'top', theme_advanced_toolbar_align: 'left', theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '', width: '100%', height: '70' }; var editor = new TinyMCE(opts); editor.setId(editorId); editor.setText(this._text); this._editorBox.prepend(editor.getElement()); editor.start(); this._editor = editor; }; EditCommentForm.prototype.startWMDEditor = function() { var editor = new WMD(); editor.setEnabledButtons('bold italic link code ol ul'); editor.setPreviewerEnabled(false); editor.setText(this._text); this._editorBox.prepend(editor.getElement());//attach DOM before start editor.start();//have to start after attaching DOM this._editor = editor; }; EditCommentForm.prototype.startSimpleEditor = function() { this._editor = new SimpleEditor(); this._editorBox.prepend(this._editor.getElement()); }; EditCommentForm.prototype.startEditor = function() { var editorType = this.getEditorType(); if (editorType === 'tinymce') { this.startTinyMCEEditor(); //@todo: implement save on enter and character counter in tinyMCE return; } else if (editorType === 'markdown') { this.startWMDEditor(); } else { this.startSimpleEditor(); } //code below is common to SimpleEditor and WMD var editorElement = this._editor.getElement(); var updateCounter = this.getCounterUpdater(); var escapeHandler = makeKeyHandler(27, this.getCancelHandler()); //todo: try this on the div var editor = this._editor; //this should be set on the textarea! editorElement.blur(updateCounter); editorElement.focus(updateCounter); editorElement.keyup(updateCounter) editorElement.keyup(escapeHandler); if (askbot['settings']['saveCommentOnEnter']){ var save_handler = makeKeyHandler(13, this.getSaveHandler()); editor.getElement().keydown(save_handler); } }; /** * attaches comment editor to a particular comment */ EditCommentForm.prototype.attachTo = function(comment, mode){ this._comment = comment; this._type = mode;//action: 'add' or 'edit' this._comment_widget = comment.getContainerWidget(); this._text = comment.getText(); comment.getElement().after(this.getElement()); comment.getElement().hide(); this._comment_widget.hideButton();//hide add comment button //fix up the comment submit button, depending on the mode if (this._type == 'add'){ this._submit_btn.html(gettext('add comment')); if (this._minorEditBox) { this._minorEditBox.hide(); } } else { this._submit_btn.html(gettext('save comment')); if (this._minorEditBox) { this._minorEditBox.show(); } } //enable the editor this.getElement().show(); this.enableForm(); this.startEditor(); this._editor.setText(this._text); var ed = this._editor var onFocus = function() { ed.putCursorAtEnd(); }; this._editor.focus(onFocus); setupButtonEventHandlers(this._submit_btn, this.getSaveHandler()); setupButtonEventHandlers(this._cancel_btn, this.getCancelHandler()); }; EditCommentForm.prototype.getCounterUpdater = function(){ //returns event handler var counter = this._text_counter; var editor = this._editor; var handler = function(){ var length = editor.getText().length; var length1 = maxCommentLength - 100; if (length1 < 0){ length1 = Math.round(0.7*maxCommentLength); } var length2 = maxCommentLength - 30; if (length2 < 0){ length2 = Math.round(0.9*maxCommentLength); } /* todo make smooth color transition, from gray to red * or rather - from start color to end color */ var color = 'maroon'; var chars = 10; if (length === 0){ var feedback = interpolate(gettext('enter at least %s characters'), [chars]); } else if (length < 10){ var feedback = interpolate(gettext('enter at least %s more characters'), [chars - length]); } else { if (length > length2) { color = '#f00'; } else if (length > length1) { color = '#f60'; } else { color = '#999'; } chars = maxCommentLength - length; var feedback = interpolate(gettext('%s characters left'), [chars]); } counter.html(feedback); counter.css('color', color); return true; }; return handler; }; /** * @todo: clean up this method so it does just one thing */ EditCommentForm.prototype.canCancel = function(){ if (this._element === null){ return true; } if (this._editor === undefined) { return true; }; var ctext = this._editor.getText(); if ($.trim(ctext) == $.trim(this._text)){ return true; } else if (this.confirmAbandon()){ return true; } this._editor.focus(); return false; }; EditCommentForm.prototype.getCancelHandler = function(){ var form = this; return function(evt){ if (form.canCancel()){ form.detach(); evt.preventDefault(); } return false; }; }; EditCommentForm.prototype.detach = function(){ if (this._comment === null){ return; } this._comment.getContainerWidget().showButton(); if (this._comment.isBlank()){ this._comment.dispose(); } else { this._comment.getElement().show(); } this.reset(); this._element = this._element.detach(); this._editor.dispose(); this._editor = undefined; removeButtonEventHandlers(this._submit_btn); removeButtonEventHandlers(this._cancel_btn); }; EditCommentForm.prototype.createDom = function(){ this._element = $('<form></form>'); this._element.attr('class', 'post-comments'); var div = $('<div></div>'); this._element.append(div); /** a stub container for the editor */ this._editorBox = div; /** * editor itself will live at this._editor * and will be initialized by the attachTo() */ this._controlsBox = this.makeElement('div'); this._controlsBox.addClass('edit-comment-buttons'); div.append(this._controlsBox); this._text_counter = $('<span></span>').attr('class', 'counter'); this._controlsBox.append(this._text_counter); this._submit_btn = $('<button class="submit"></button>'); this._controlsBox.append(this._submit_btn); this._cancel_btn = $('<button class="submit"></button>'); this._cancel_btn.html(gettext('cancel')); this._controlsBox.append(this._cancel_btn); //if email alerts are enabled, add a checkbox "suppress_email" if (askbot['settings']['enableEmailAlerts'] === true) { this._minorEditBox = this.makeElement('div'); this._minorEditBox.addClass('checkbox'); this._controlsBox.append(this._minorEditBox); var checkBox = this.makeElement('input'); checkBox.attr('type', 'checkbox'); checkBox.attr('name', 'suppress_email'); this._minorEditBox.append(checkBox); var label = this.makeElement('label'); label.attr('for', 'suppress_email'); label.html(gettext("minor edit (don't send alerts)")); this._minorEditBox.append(label); } }; EditCommentForm.prototype.isEnabled = function() { return (this._submit_btn.attr('disabled') !== 'disabled');//confusing! setters use boolean }; EditCommentForm.prototype.enableForm = function() { this._submit_btn.attr('disabled', false); this._cancel_btn.attr('disabled', false); }; EditCommentForm.prototype.disableForm = function() { this._submit_btn.attr('disabled', true); this._cancel_btn.attr('disabled', true); }; EditCommentForm.prototype.reset = function(){ this._comment = null; this._text = ''; this._editor.setText(''); this.enableForm(); }; EditCommentForm.prototype.confirmAbandon = function(){ this._editor.focus(); this._editor.getElement().scrollTop(); this._editor.setHighlight(true); var answer = confirm( gettext("Are you sure you don't want to post this comment?") ); this._editor.setHighlight(false); return answer; }; EditCommentForm.prototype.getSuppressEmail = function() { return this._element.find('input[name="suppress_email"]').is(':checked'); }; EditCommentForm.prototype.setSuppressEmail = function(bool) { this._element.find('input[name="suppress_email"]').prop('checked', bool); }; EditCommentForm.prototype.getSaveHandler = function(){ var me = this; var editor = this._editor; return function(){ if (me.isEnabled() === false) {//prevent double submits return false; } me.disableForm(); var text = editor.getText(); if (text.length < askbot['settings']['minCommentBodyLength']){ editor.focus(); me.enableForm(); return false; } //display the comment and show that it is not yet saved me.setWaitingStatus(true); me._comment.getElement().show(); var commentData = me._comment.getData(); var timestamp = commentData['comment_added_at'] || gettext('just now'); var userName = commentData['user_display_name'] || askbot['data']['userName']; me._comment.setContent({ 'html': editor.getHtml(), 'text': text, 'user_display_name': userName, 'comment_added_at': timestamp }); me._comment.setDraftStatus(true); me._comment.getContainerWidget().showButton(); var post_data = { comment: text }; if (me._type == 'edit'){ post_data['comment_id'] = me._comment.getId(); post_url = askbot['urls']['editComment']; post_data['suppress_email'] = me.getSuppressEmail(); me.setSuppressEmail(false); } else { post_data['post_type'] = me._comment.getParentType(); post_data['post_id'] = me._comment.getParentId(); post_url = askbot['urls']['postComments']; } $.ajax({ type: "POST", url: post_url, dataType: "json", data: post_data, success: function(json) { //type is 'edit' or 'add' me._comment.setDraftStatus(false); if (me._type == 'add'){ me._comment.dispose(); me._comment.getContainerWidget().reRenderComments(json); } else { me._comment.setContent(json); } me.setWaitingStatus(false); me.detach(); }, error: function(xhr, textStatus, errorThrown) { me._comment.getElement().show(); showMessage(me._comment.getElement(), xhr.responseText, 'after'); me._comment.setDraftStatus(false); me.setWaitingStatus(false); me.detach(); me.enableForm(); } }); return false; }; }; var Comment = function(widget, data){ WrappedElement.call(this); this._container_widget = widget; this._data = data || {}; this._blank = true;//set to false by setContent this._element = null; this._is_convertible = askbot['data']['userIsAdminOrMod']; this.convert_link = null; this._delete_prompt = gettext('delete this comment'); this._editorForm = undefined; if (data && data['is_deletable']){ this._deletable = data['is_deletable']; } else { this._deletable = false; } if (data && data['is_editable']){ this._editable = data['is_deletable']; } else { this._editable = false; } }; inherits(Comment, WrappedElement); Comment.prototype.getData = function() { return this._data; }; Comment.prototype.startEditing = function() { var form = this._editorForm || new EditCommentForm(); this._editorForm = form; // if new comment: if (this.isBlank()) { form.attachTo(this, 'add'); } else { form.attachTo(this, 'edit'); } }; Comment.prototype.decorate = function(element){ this._element = $(element); var parent_type = this._element.parent().parent().attr('id').split('-')[2]; var comment_id = this._element.attr('id').replace('comment-',''); this._data = {id: comment_id}; this._contentBox = this._element.find('.comment-content'); var timestamp = this._element.find('abbr.timeago'); this._data['comment_added_at'] = timestamp.attr('title'); var userLink = this._element.find('a.author'); this._data['user_display_name'] = userLink.html(); // @todo: read other data var commentBody = this._element.find('.comment-body'); if (commentBody.length > 0) { this._comment_body = commentBody; } var delete_img = this._element.find('span.delete-icon'); if (delete_img.length > 0){ this._deletable = true; this._delete_icon = new DeleteIcon(this.deletePrompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._delete_icon.decorate(delete_img); } var edit_link = this._element.find('a.edit'); if (edit_link.length > 0){ this._editable = true; this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()); this._edit_link.decorate(edit_link); } var convert_link = this._element.find('form.convert-comment'); if (this._is_convertible){ this._convert_link = new CommentConvertLink(comment_id); this._convert_link.decorate(convert_link); } var deleter = this._element.find('.comment-delete'); if (deleter.length > 0) { this._comment_delete = deleter; }; var vote = new CommentVoteButton(this); vote.decorate(this._element.find('.comment-votes .upvote')); this._blank = false; }; Comment.prototype.setDraftStatus = function(isDraft) { return; //@todo: implement nice feedback about posting in progress //maybe it should be an element that lasts at least a second //to avoid the possible brief flash if (isDraft === true) { this._normalBackground = this._element.css('background'); this._element.css('background', 'rgb(255, 243, 195)'); } else { this._element.css('background', this._normalBackground); } }; Comment.prototype.isBlank = function(){ return this._blank; }; Comment.prototype.getId = function(){ return this._data['id']; }; Comment.prototype.hasContent = function(){ return ('id' in this._data); //shortcut for 'user_url' 'html' 'user_display_name' 'comment_age' }; Comment.prototype.hasText = function(){ return ('text' in this._data); } Comment.prototype.getContainerWidget = function(){ return this._container_widget; }; Comment.prototype.getParentType = function(){ return this._container_widget.getPostType(); }; Comment.prototype.getParentId = function(){ return this._container_widget.getPostId(); }; /** * this function is basically an "updateDom" * for which we don't have the convention */ Comment.prototype.setContent = function(data){ this._data = $.extend(this._data, data); this._element.addClass('comment'); this._element.css('display', 'table');//@warning: hardcoded //display is set to "block" if .show() is called, but we need table. this._element.attr('id', 'comment-' + this._data['id']); // 1) create the votes element if it is not there var votesBox = this._element.find('.comment-votes'); if (votesBox.length === 0) { votesBox = this.makeElement('div'); votesBox.addClass('comment-votes'); this._element.append(votesBox); var vote = new CommentVoteButton(this); if (this._data['upvoted_by_user']){ vote.setVoted(true); } vote.setScore(this._data['score']); var voteElement = vote.getElement(); votesBox.append(vote.getElement()); } // 2) create the comment content container if (this._contentBox === undefined) { var contentBox = this.makeElement('div'); contentBox.addClass('comment-content'); this._contentBox = contentBox; this._element.append(contentBox); } // 2) create the comment deleter if it is not there if (this._comment_delete === undefined) { this._comment_delete = $('<div class="comment-delete"></div>'); if (this._deletable){ this._delete_icon = new DeleteIcon(this._delete_prompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._comment_delete.append(this._delete_icon.getElement()); } this._contentBox.append(this._comment_delete); } // 3) create or replace the comment body if (this._comment_body === undefined) { this._comment_body = $('<div class="comment-body"></div>'); this._contentBox.append(this._comment_body); } if (EditCommentForm.prototype.getEditorType() === 'tinymce') { var theComment = $('<div/>'); theComment.html(this._data['html']); //sanitize, just in case this._comment_body.empty(); this._comment_body.append(theComment); this._data['text'] = this._data['html']; } else { this._comment_body.empty(); this._comment_body.html(this._data['html']); } //this._comment_body.append(' &ndash; '); // 4) create user link if absent if (this._user_link !== undefined) { this._user_link.detach(); this._user_link = undefined; } this._user_link = $('<a></a>').attr('class', 'author'); this._user_link.attr('href', this._data['user_url']); this._user_link.html(this._data['user_display_name']); this._comment_body.append(' '); this._comment_body.append(this._user_link); // 5) create or update the timestamp if (this._comment_added_at !== undefined) { this._comment_added_at.detach(); this._comment_added_at = undefined; } this._comment_body.append(' ('); this._comment_added_at = $('<abbr class="timeago"></abbr>'); this._comment_added_at.html(this._data['comment_added_at']); this._comment_added_at.attr('title', this._data['comment_added_at']); this._comment_added_at.timeago(); this._comment_body.append(this._comment_added_at); this._comment_body.append(')'); if (this._editable) { if (this._edit_link !== undefined) { this._edit_link.dispose(); } this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()) this._comment_body.append(this._edit_link.getElement()); } if (this._is_convertible) { if (this._convert_link !== undefined) { this._convert_link.dispose(); } this._convert_link = new CommentConvertLink(this._data['id']); this._comment_body.append(this._convert_link.getElement()); } this._blank = false; }; Comment.prototype.dispose = function(){ if (this._comment_body){ this._comment_body.remove(); } if (this._comment_delete){ this._comment_delete.remove(); } if (this._user_link){ this._user_link.remove(); } if (this._comment_added_at){ this._comment_added_at.remove(); } if (this._delete_icon){ this._delete_icon.dispose(); } if (this._edit_link){ this._edit_link.dispose(); } if (this._convert_link){ this._convert_link.dispose(); } this._data = null; Comment.superClass_.dispose.call(this); }; Comment.prototype.getElement = function(){ Comment.superClass_.getElement.call(this); if (this.isBlank() && this.hasContent()){ this.setContent(); if (askbot['settings']['mathjaxEnabled'] === true){ MathJax.Hub.Queue(['Typeset', MathJax.Hub]); } } return this._element; }; Comment.prototype.loadText = function(on_load_handler){ var me = this; $.ajax({ type: "GET", url: askbot['urls']['getComment'], data: {id: this._data['id']}, success: function(json){ if (json['success']) { me._data['text'] = json['text']; on_load_handler() } else { showMessage(me.getElement(), json['message'], 'after'); } }, error: function(xhr, textStatus, exception) { showMessage(me.getElement(), xhr.responseText, 'after'); } }); }; Comment.prototype.getText = function(){ if (!this.isBlank()){ if ('text' in this._data){ return this._data['text']; } } return ''; } Comment.prototype.getEditHandler = function(){ var me = this; return function(){ if (me.hasText()){ me.startEditing(); } else { me.loadText(function(){ me.startEditing() }); } }; }; Comment.prototype.getDeleteHandler = function(){ var comment = this; var del_icon = this._delete_icon; return function(){ if (confirm(gettext('confirm delete comment'))){ comment.getElement().hide(); $.ajax({ type: 'POST', url: askbot['urls']['deleteComment'], data: { comment_id: comment.getId() }, success: function(json, textStatus, xhr) { comment.dispose(); }, error: function(xhr, textStatus, exception) { comment.getElement().show() showMessage(del_icon.getElement(), xhr.responseText); }, dataType: "json" }); } }; }; var PostCommentsWidget = function(){ WrappedElement.call(this); this._denied = false; }; inherits(PostCommentsWidget, WrappedElement); PostCommentsWidget.prototype.decorate = function(element){ var element = $(element); this._element = element; var widget_id = element.attr('id'); var id_bits = widget_id.split('-'); this._post_id = id_bits[3]; this._post_type = id_bits[2]; this._is_truncated = askbot['data'][widget_id]['truncated']; this._user_can_post = askbot['data'][widget_id]['can_post']; //see if user can comment here var controls = element.find('.controls'); this._activate_button = controls.find('.button'); if (this._user_can_post == false){ setupButtonEventHandlers( this._activate_button, this.getReadOnlyLoadHandler() ); } else { setupButtonEventHandlers( this._activate_button, this.getActivateHandler() ); } this._cbox = element.find('.content'); var comments = new Array(); var me = this; this._cbox.children('.comment').each(function(index, element){ var comment = new Comment(me); comments.push(comment) comment.decorate(element); }); this._comments = comments; }; PostCommentsWidget.prototype.getPostType = function(){ return this._post_type; }; PostCommentsWidget.prototype.getPostId = function(){ return this._post_id; }; PostCommentsWidget.prototype.hideButton = function(){ this._activate_button.hide(); }; PostCommentsWidget.prototype.showButton = function(){ if (this._is_truncated === false){ this._activate_button.html(askbot['messages']['addComment']); } this._activate_button.show(); } PostCommentsWidget.prototype.startNewComment = function(){ var opts = { 'is_deletable': true, 'is_editable': true }; var comment = new Comment(this, opts); this._cbox.append(comment.getElement()); comment.startEditing(); }; PostCommentsWidget.prototype.needToReload = function(){ return this._is_truncated; }; PostCommentsWidget.prototype.userCanPost = function() { var data = askbot['data']; if (data['userIsAuthenticated']) { //true if admin, post owner or high rep user if (data['userIsAdminOrMod']) { return true; } else if (this.getPostId() in data['user_posts']) { return true; } } return false; }; PostCommentsWidget.prototype.getActivateHandler = function(){ var me = this; var button = this._activate_button; return function() { if (me.needToReload()){ me.reloadAllComments(function(json){ me.reRenderComments(json); //2) change button text to "post a comment" button.html(gettext('post a comment')); }); } else { //if user can't post, we tell him something and refuse if (askbot['data']['userIsAuthenticated']) { me.startNewComment(); } else { var message = gettext('please sign in or register to post comments'); showMessage(button, message, 'after'); } } }; }; PostCommentsWidget.prototype.getReadOnlyLoadHandler = function(){ var me = this; return function(){ me.reloadAllComments(function(json){ me.reRenderComments(json); me._activate_button.remove(); }); }; }; PostCommentsWidget.prototype.reloadAllComments = function(callback){ var post_data = {post_id: this._post_id, post_type: this._post_type}; var me = this; $.ajax({ type: "GET", url: askbot['urls']['postComments'], data: post_data, success: function(json){ callback(json); me._is_truncated = false; }, dataType: "json" }); }; PostCommentsWidget.prototype.reRenderComments = function(json){ $.each(this._comments, function(i, item){ item.dispose(); }); this._comments = new Array(); var me = this; $.each(json, function(i, item){ var comment = new Comment(me, item); me._cbox.append(comment.getElement()); me._comments.push(comment); }); }; var socialSharing = function(){ var SERVICE_DATA = { //url - template for the sharing service url, params are for the popup identica: { url: "http://identi.ca/notice/new?status_textarea={TEXT}%20{URL}", params: "width=820, height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, twitter: { url: "http://twitter.com/share?url={URL}&ref=twitbtn&text={TEXT}", params: "width=820,height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, facebook: { url: "http://www.facebook.com/sharer.php?u={URL}&ref=fbshare&t={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" }, linkedin: { url: "http://www.linkedin.com/shareArticle?mini=true&url={URL}&title={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" } }; var URL = ""; var TEXT = ""; var share_page = function(service_name){ if (SERVICE_DATA[service_name]){ var url = SERVICE_DATA[service_name]['url']; url = url.replace('{TEXT}', TEXT); url = url.replace('{URL}', URL); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } return false; //@todo: change to some other url shortening service $.ajax({ url: "http://json-tinyurl.appspot.com/?&callback=?", dataType: "json", data: {'url':URL}, success: function(data) { url = url.replace('{URL}', data.tinyurl); }, error: function(xhr, opts, error) { url = url.replace('{URL}', URL); }, complete: function(data) { url = url.replace('{TEXT}', TEXT); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } } }); } } return { init: function(){ URL = window.location.href; var urlBits = URL.split('/'); URL = urlBits.slice(0, -2).join('/') + '/'; TEXT = encodeURIComponent($('h1 > a').html()); var hashtag = encodeURIComponent( askbot['settings']['sharingSuffixText'] ); TEXT = TEXT.substr(0, 134 - URL.length - hashtag.length); TEXT = TEXT + '... ' + hashtag; var fb = $('a.facebook-share') var tw = $('a.twitter-share'); var ln = $('a.linkedin-share'); var ica = $('a.identica-share'); copyAltToTitle(fb); copyAltToTitle(tw); copyAltToTitle(ln); copyAltToTitle(ica); setupButtonEventHandlers(fb, function(){ share_page("facebook") }); setupButtonEventHandlers(tw, function(){ share_page("twitter") }); setupButtonEventHandlers(ln, function(){ share_page("linkedin") }); setupButtonEventHandlers(ica, function(){ share_page("identica") }); } } }(); /** * @constructor * @extends {SimpleControl} */ var QASwapper = function(){ SimpleControl.call(this); this._ans_id = null; }; inherits(QASwapper, SimpleControl); QASwapper.prototype.decorate = function(element){ this._element = element; this._ans_id = parseInt(element.attr('id').split('-').pop()); var me = this; this.setHandler(function(){ me.startSwapping(); }); }; QASwapper.prototype.startSwapping = function(){ while (true){ var title = prompt(gettext('Please enter question title (>10 characters)')); if (title.length >= 10){ var data = {new_title: title, answer_id: this._ans_id}; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['swap_question_with_answer'], data: data, success: function(data){ window.location.href = data['question_url']; } }); break; } } }; /** * @constructor * An element that encloses an editor and everything inside it. * By default editor is hidden and user sees a box with a prompt * suggesting to make a post. * When user clicks, editor becomes accessible. */ var FoldedEditor = function() { WrappedElement.call(this); }; inherits(FoldedEditor, WrappedElement); FoldedEditor.prototype.getEditor = function() { return this._editor; }; FoldedEditor.prototype.getEditorInputId = function() { return this._element.find('textarea').attr('id'); }; FoldedEditor.prototype.onAfterOpenHandler = function() { var editor = this.getEditor(); if (editor) { setTimeout(function() {editor.focus()}, 500); } }; FoldedEditor.prototype.getOpenHandler = function() { var editorBox = this._editorBox; var promptBox = this._prompt; var externalTrigger = this._externalTrigger; var me = this; return function() { promptBox.hide(); editorBox.show(); var element = me.getElement(); element.addClass('unfolded'); /* make the editor one shot - once it unfolds it's * not accepting any events */ element.unbind('click'); element.unbind('focus'); /* this function will open the editor * and focus cursor on the editor */ me.onAfterOpenHandler(); /* external trigger is a clickable target * placed outside of the this._element * that will cause the editor to unfold */ if (externalTrigger) { var label = me.makeElement('label'); label.html(externalTrigger.html()); //set what the label is for label.attr('for', me.getEditorInputId()); externalTrigger.replaceWith(label); } }; }; FoldedEditor.prototype.setExternalTrigger = function(element) { this._externalTrigger = element; }; FoldedEditor.prototype.decorate = function(element) { this._element = element; this._prompt = element.find('.prompt'); this._editorBox = element.find('.editor-proper'); var editorType = askbot['settings']['editorType']; if (editorType === 'tinymce') { var editor = new TinyMCE(); editor.decorate(element.find('textarea')); this._editor = editor; } else if (editorType === 'markdown') { var editor = new WMD(); editor.decorate(element); this._editor = editor; } var openHandler = this.getOpenHandler(); element.click(openHandler); element.focus(openHandler); if (this._externalTrigger) { this._externalTrigger.click(openHandler); } }; /** * @constructor * a simple textarea-based editor */ var SimpleEditor = function(attrs) { WrappedElement.call(this); attrs = attrs || {}; this._rows = attrs['rows'] || 10; this._cols = attrs['cols'] || 60; this._maxlength = attrs['maxlength'] || 1000; }; inherits(SimpleEditor, WrappedElement); SimpleEditor.prototype.focus = function(onFocus) { this._textarea.focus(); if (onFocus) { onFocus(); } }; SimpleEditor.prototype.putCursorAtEnd = function() { putCursorAtEnd(this._textarea); }; /** * a noop function */ SimpleEditor.prototype.start = function() {}; SimpleEditor.prototype.setHighlight = function(isHighlighted) { if (isHighlighted === true) { this._textarea.addClass('highlight'); } else { this._textarea.removeClass('highlight'); } }; SimpleEditor.prototype.getText = function() { return $.trim(this._textarea.val()); }; SimpleEditor.prototype.getHtml = function() { return '<div class="transient-comment">' + this.getText() + '</div>'; }; SimpleEditor.prototype.setText = function(text) { this._text = text; if (this._textarea) { this._textarea.val(text); }; }; /** * a textarea inside a div, * the reason for this is that we subclass this * in WMD, and that one requires a more complex structure */ SimpleEditor.prototype.createDom = function() { this._element = this.makeElement('div'); this._element.addClass('wmd-container'); var textarea = this.makeElement('textarea'); this._element.append(textarea); this._textarea = textarea; if (this._text) { textarea.val(this._text); }; textarea.attr({ 'cols': this._cols, 'rows': this._rows, 'maxlength': this._maxlength }); } /** * @constructor * a wrapper for the WMD editor */ var WMD = function(){ SimpleEditor.call(this); this._text = undefined; this._enabled_buttons = 'bold italic link blockquote code ' + 'image attachment ol ul heading hr'; this._is_previewer_enabled = true; }; inherits(WMD, SimpleEditor); //@todo: implement getHtml method that runs text through showdown renderer WMD.prototype.setEnabledButtons = function(buttons){ this._enabled_buttons = buttons; }; WMD.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this._previewer){ this._previewer.hide(); } }; WMD.prototype.createDom = function(){ this._element = this.makeElement('div'); var clearfix = this.makeElement('div').addClass('clearfix'); this._element.append(clearfix); var wmd_container = this.makeElement('div'); wmd_container.addClass('wmd-container'); this._element.append(wmd_container); var wmd_buttons = this.makeElement('div') .attr('id', this.makeId('wmd-button-bar')) .addClass('wmd-panel'); wmd_container.append(wmd_buttons); var editor = this.makeElement('textarea') .attr('id', this.makeId('editor')); wmd_container.append(editor); this._textarea = editor; if (this._text){ editor.val(this._text); } var previewer = this.makeElement('div') .attr('id', this.makeId('previewer')) .addClass('wmd-preview'); wmd_container.append(previewer); this._previewer = previewer; if (this._is_previewer_enabled === false) { previewer.hide(); } }; WMD.prototype.decorate = function(element) { this._element = element; this._textarea = element.find('textarea'); this._previewer = element.find('.wmd-preview'); }; WMD.prototype.start = function(){ Attacklab.Util.startEditor(true, this._enabled_buttons, this.getIdSeed()); }; /** * @constructor */ var TinyMCE = function(config) { WrappedElement.call(this); this._config = config || {}; this._id = 'editor';//desired id of the textarea }; inherits(TinyMCE, WrappedElement); /* * not passed onto prototoype on purpose!!! */ TinyMCE.onInitHook = function() { //set initial content var ed = tinyMCE.activeEditor; ed.setContent(askbot['data']['editorContent'] || ''); //if we have spellchecker - enable it by default if (inArray('spellchecker', askbot['settings']['tinyMCEPlugins'])) { setTimeout(function() { ed.controlManager.setActive('spellchecker', true); tinyMCE.execCommand('mceSpellCheck', true); }, 1); } }; /* 3 dummy functions to match WMD api */ TinyMCE.prototype.setEnabledButtons = function() {}; TinyMCE.prototype.start = function() { //copy the options, because we need to modify them var opts = $.extend({}, this._config); var me = this; var extraOpts = { 'mode': 'exact', 'elements': this._id, }; opts = $.extend(opts, extraOpts); tinyMCE.init(opts); $('.mceStatusbar').remove(); }; TinyMCE.prototype.setPreviewerEnabled = function() {}; TinyMCE.prototype.setHighlight = function() {}; TinyMCE.prototype.putCursorAtEnd = function() { var ed = tinyMCE.activeEditor; //add an empty span with a unique id var endId = tinymce.DOM.uniqueId(); ed.dom.add(ed.getBody(), 'span', {'id': endId}, ''); //select that span var newNode = ed.dom.select('span#' + endId); ed.selection.select(newNode[0]); }; TinyMCE.prototype.focus = function(onFocus) { var editorId = this._id; var winH = $(window).height(); var winY = $(window).scrollTop(); var edY = this._element.offset().top; var edH = this._element.height(); //@todo: the fallacy of this method is timeout - should instead use queue //because at the time of calling focus() the editor may not be initialized yet setTimeout( function() { tinyMCE.execCommand('mceFocus', false, editorId); //@todo: make this general to all editors //if editor bottom is below viewport var isBelow = ((edY + edH) > (winY + winH)); var isAbove = (edY < winY); if (isBelow || isAbove) { //then center on screen $(window).scrollTop(edY - edH/2 - winY/2); } if (onFocus) { onFocus(); } }, 100 ); }; TinyMCE.prototype.setId = function(id) { this._id = id; }; TinyMCE.prototype.setText = function(text) { this._text = text; if (this.isLoaded()) { tinymce.get(this._id).setContent(text); } }; TinyMCE.prototype.getText = function() { return tinyMCE.activeEditor.getContent(); }; TinyMCE.prototype.getHtml = TinyMCE.prototype.getText; TinyMCE.prototype.isLoaded = function() { return (tinymce.get(this._id) !== undefined); }; TinyMCE.prototype.createDom = function() { var editorBox = this.makeElement('div'); editorBox.addClass('wmd-container'); this._element = editorBox; var textarea = this.makeElement('textarea'); textarea.attr('id', this._id); textarea.addClass('editor'); this._element.append(textarea); }; TinyMCE.prototype.decorate = function(element) { this._element = element; this._id = element.attr('id'); }; /** * @constructor * @todo: change this to generic object description editor */ var TagWikiEditor = function(){ WrappedElement.call(this); this._state = 'display';//'edit' or 'display' this._content_backup = ''; this._is_editor_loaded = false; this._enabled_editor_buttons = null; this._is_previewer_enabled = false; }; inherits(TagWikiEditor, WrappedElement); TagWikiEditor.prototype.backupContent = function(){ this._content_backup = this._content_box.contents(); }; TagWikiEditor.prototype.setEnabledEditorButtons = function(buttons){ this._enabled_editor_buttons = buttons; }; TagWikiEditor.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this.isEditorLoaded()){ this._editor.setPreviewerEnabled(this._is_previewer_enabled); } }; TagWikiEditor.prototype.setContent = function(content){ this._content_box.empty(); this._content_box.append(content); }; TagWikiEditor.prototype.setState = function(state){ if (state === 'edit'){ this._state = state; this._edit_btn.hide(); this._cancel_btn.show(); this._save_btn.show(); this._cancel_sep.show(); } else if (state === 'display'){ this._state = state; this._edit_btn.show(); this._cancel_btn.hide(); this._cancel_sep.hide(); this._save_btn.hide(); } }; TagWikiEditor.prototype.restoreContent = function(){ var content_box = this._content_box; content_box.empty(); $.each(this._content_backup, function(idx, element){ content_box.append(element); }); }; TagWikiEditor.prototype.getTagId = function(){ return this._tag_id; }; TagWikiEditor.prototype.isEditorLoaded = function(){ return this._is_editor_loaded; }; TagWikiEditor.prototype.setEditorLoaded = function(){ return this._is_editor_loaded = true; }; /** * loads initial data for the editor input and activates * the editor */ TagWikiEditor.prototype.startActivatingEditor = function(){ var editor = this._editor; var me = this; var data = { object_id: me.getTagId(), model_name: 'Group' }; $.ajax({ type: 'GET', url: askbot['urls']['load_object_description'], data: data, cache: false, success: function(data){ me.backupContent(); editor.setText(data); me.setContent(editor.getElement()); me.setState('edit'); if (me.isEditorLoaded() === false){ editor.start(); me.setEditorLoaded(); } } }); }; TagWikiEditor.prototype.saveData = function(){ var me = this; var text = this._editor.getText(); var data = { object_id: me.getTagId(), model_name: 'Group',//todo: fixme text: text }; $.ajax({ type: 'POST', dataType: 'json', url: askbot['urls']['save_object_description'], data: data, cache: false, success: function(data){ if (data['success']){ me.setState('display'); me.setContent(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; TagWikiEditor.prototype.cancelEdit = function(){ this.restoreContent(); this.setState('display'); }; TagWikiEditor.prototype.decorate = function(element){ //expect <div id='group-wiki-{{id}}'><div class="content"/><a class="edit"/></div> this._element = element; var edit_btn = element.find('.edit-description'); this._edit_btn = edit_btn; //adding two buttons... var save_btn = this.makeElement('a'); save_btn.html(gettext('save')); edit_btn.after(save_btn); save_btn.hide(); this._save_btn = save_btn; var cancel_btn = this.makeElement('a'); cancel_btn.html(gettext('cancel')); save_btn.after(cancel_btn); cancel_btn.hide(); this._cancel_btn = cancel_btn; this._cancel_sep = $('<span> | </span>'); cancel_btn.before(this._cancel_sep); this._cancel_sep.hide(); this._content_box = element.find('.content'); this._tag_id = element.attr('id').split('-').pop(); var me = this; if (askbot['settings']['editorType'] === 'markdown') { var editor = new WMD(); } else { var editor = new TinyMCE({//override defaults theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '' }); } if (this._enabled_editor_buttons){ editor.setEnabledButtons(this._enabled_editor_buttons); } editor.setPreviewerEnabled(this._is_previewer_enabled); this._editor = editor; setupButtonEventHandlers(edit_btn, function(){ me.startActivatingEditor() }); setupButtonEventHandlers(cancel_btn, function(){me.cancelEdit()}); setupButtonEventHandlers(save_btn, function(){me.saveData()}); }; var ImageChanger = function(){ WrappedElement.call(this); this._image_element = undefined; this._delete_button = undefined; this._save_url = undefined; this._delete_url = undefined; this._messages = undefined; }; inherits(ImageChanger, WrappedElement); ImageChanger.prototype.setImageElement = function(image_element){ this._image_element = image_element; }; ImageChanger.prototype.setMessages = function(messages){ this._messages = messages; }; ImageChanger.prototype.setDeleteButton = function(delete_button){ this._delete_button = delete_button; }; ImageChanger.prototype.setSaveUrl = function(url){ this._save_url = url; }; ImageChanger.prototype.setDeleteUrl = function(url){ this._delete_url = url; }; ImageChanger.prototype.setAjaxData = function(data){ this._ajax_data = data; }; ImageChanger.prototype.showImage = function(image_url){ this._image_element.attr('src', image_url); this._image_element.show(); }; ImageChanger.prototype.deleteImage = function(){ this._image_element.attr('src', ''); this._image_element.css('display', 'none'); var me = this; var delete_url = this._delete_url; var data = this._ajax_data; $.ajax({ type: 'POST', dataType: 'json', url: delete_url, data: data, cache: false, success: function(data){ if (data['success'] === true){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.saveImageUrl = function(image_url){ var me = this; var data = this._ajax_data; data['image_url'] = image_url; var save_url = this._save_url; $.ajax({ type: 'POST', dataType: 'json', url: save_url, data: data, cache: false, success: function(data){ if (!data['success']){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.startDialog = function(){ //reusing the wmd's file uploader var me = this; var change_image_text = this._messages['change_image']; var change_image_button = this._element; Attacklab.Util.prompt( "<h3>" + gettext('Enter the logo url or upload an image') + '</h3>', 'http://', function(image_url){ if (image_url){ me.saveImageUrl(image_url); me.showImage(image_url); change_image_button.html(change_image_text); me.showDeleteButton(); } }, 'image' ); }; ImageChanger.prototype.showDeleteButton = function(){ this._delete_button.show(); this._delete_button.prev().show(); }; ImageChanger.prototype.hideDeleteButton = function(){ this._delete_button.hide(); this._delete_button.prev().hide(); }; ImageChanger.prototype.startDeleting = function(){ if (confirm(gettext('Do you really want to remove the image?'))){ this.deleteImage(); this._element.html(this._messages['add_image']); this.hideDeleteButton(); this._delete_button.hide(); var sep = this._delete_button.prev(); sep.hide(); }; }; /** * decorates an element that will serve as the image changer button */ ImageChanger.prototype.decorate = function(element){ this._element = element; var me = this; setupButtonEventHandlers( element, function(){ me.startDialog(); } ); setupButtonEventHandlers( this._delete_button, function(){ me.startDeleting(); } ) }; var UserGroupProfileEditor = function(){ TagWikiEditor.call(this); }; inherits(UserGroupProfileEditor, TagWikiEditor); UserGroupProfileEditor.prototype.toggleEmailModeration = function(){ var btn = this._moderate_email_btn; var group_id = this.getTagId(); $.ajax({ type: 'POST', dataType: 'json', cache: false, data: {group_id: group_id}, url: askbot['urls']['toggle_group_email_moderation'], success: function(data){ if (data['success']){ btn.html(data['new_button_text']); } else { showMessage(btn, data['message']); } } }); }; UserGroupProfileEditor.prototype.decorate = function(element){ this.setEnabledEditorButtons('bold italic link ol ul'); this.setPreviewerEnabled(false); UserGroupProfileEditor.superClass_.decorate.call(this, element); var change_logo_btn = element.find('.change-logo'); this._change_logo_btn = change_logo_btn; var moderate_email_toggle = new TwoStateToggle(); moderate_email_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_email' }); var moderate_email_btn = element.find('#moderate-email'); this._moderate_email_btn = moderate_email_btn; moderate_email_toggle.decorate(moderate_email_btn); var moderate_publishing_replies_toggle = new TwoStateToggle(); moderate_publishing_replies_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_answers_to_enquirers' }); var btn = element.find('#moderate-answers-to-enquirers'); moderate_publishing_replies_toggle.decorate(btn); var vip_toggle = new TwoStateToggle(); vip_toggle.setPostData({ group_id: this.getTagId(), property_name: 'is_vip' }); var btn = element.find('#vip-toggle'); vip_toggle.decorate(btn); var opennessSelector = new DropdownSelect(); var selectorElement = element.find('#group-openness-selector'); opennessSelector.setPostData({ group_id: this.getTagId(), property_name: 'openness' }); opennessSelector.decorate(selectorElement); var email_editor = new TextPropertyEditor(); email_editor.decorate(element.find('#preapproved-emails')); var domain_editor = new TextPropertyEditor(); domain_editor.decorate(element.find('#preapproved-email-domains')); var logo_changer = new ImageChanger(); logo_changer.setImageElement(element.find('.group-logo')); logo_changer.setAjaxData({ group_id: this.getTagId() }); logo_changer.setSaveUrl(askbot['urls']['save_group_logo_url']); logo_changer.setDeleteUrl(askbot['urls']['delete_group_logo_url']); logo_changer.setMessages({ change_image: gettext('change logo'), add_image: gettext('add logo') }); var delete_logo_btn = element.find('.delete-logo'); logo_changer.setDeleteButton(delete_logo_btn); logo_changer.decorate(change_logo_btn); }; var GroupJoinButton = function(){ TwoStateToggle.call(this); }; inherits(GroupJoinButton, TwoStateToggle); GroupJoinButton.prototype.getPostData = function(){ return { group_id: this._group_id }; }; GroupJoinButton.prototype.getHandler = function(){ var me = this; return function(){ $.ajax({ type: 'POST', dataType: 'json', cache: false, data: me.getPostData(), url: askbot['urls']['join_or_leave_group'], success: function(data){ if (data['success']){ var level = data['membership_level']; var new_state = 'off-state'; if (level == 'full' || level == 'pending') { new_state = 'on-state'; } me.setState(new_state); } else { showMessage(me.getElement(), data['message']); } } }); }; }; GroupJoinButton.prototype.decorate = function(elem) { GroupJoinButton.superClass_.decorate.call(this, elem); this._group_id = this._element.data('groupId'); }; var TagEditor = function() { WrappedElement.call(this); this._has_hot_backspace = false; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(TagEditor, WrappedElement); TagEditor.prototype.getSelectedTags = function() { return $.trim(this._hidden_tags_input.val()).split(/\s+/); }; TagEditor.prototype.setSelectedTags = function(tag_names) { this._hidden_tags_input.val($.trim(tag_names.join(' '))); }; TagEditor.prototype.addSelectedTag = function(tag_name) { var tag_names = this._hidden_tags_input.val(); this._hidden_tags_input.val(tag_names + ' ' + tag_name); $('.acResults').hide();//a hack to hide the autocompleter }; TagEditor.prototype.isSelectedTagName = function(tag_name) { var tag_names = this.getSelectedTags(); return $.inArray(tag_name, tag_names) != -1; }; TagEditor.prototype.removeSelectedTag = function(tag_name) { var tag_names = this.getSelectedTags(); var idx = $.inArray(tag_name, tag_names); if (idx !== -1) { tag_names.splice(idx, 1) } this.setSelectedTags(tag_names); }; TagEditor.prototype.getTagDeleteHandler = function(tag){ var me = this; return function(){ me.removeSelectedTag(tag.getName()); me.clearErrorMessage(); tag.dispose(); $('.acResults').hide();//a hack to hide the autocompleter me.fixHeight(); }; }; TagEditor.prototype.cleanTag = function(tag_name, reject_dupe) { tag_name = $.trim(tag_name); tag_name = tag_name.replace(/\s+/, ' '); var force_lowercase = this._settings['force_lowercase_tags']; if (force_lowercase) { tag_name = tag_name.toLowerCase(); } if (reject_dupe && this.isSelectedTagName(tag_name)) { throw interpolate( gettext('tag "%s" was already added, no need to repeat (press "escape" to delete)'), [tag_name] ); } var max_tags = this._settings['max_tags_per_post']; if (this.getSelectedTags().length + 1 > max_tags) {//count current throw interpolate( ngettext( 'a maximum of %s tag is allowed', 'a maximum of %s tags are allowed', max_tags ), [max_tags] ); } //generic cleaning return cleanTag(tag_name, this._settings); }; TagEditor.prototype.addTag = function(tag_name) { var tag = new Tag(); tag.setName(tag_name); tag.setDeletable(true); tag.setLinkable(true); tag.setDeleteHandler(this.getTagDeleteHandler(tag)); this._tags_container.append(tag.getElement()); this.addSelectedTag(tag_name); }; TagEditor.prototype.immediateClearErrorMessage = function() { this._error_alert.html(''); this._error_alert.show(); //this._element.css('margin-top', '18px');//todo: the margin thing is a hack } TagEditor.prototype.clearErrorMessage = function(fade) { if (fade) { var me = this; this._error_alert.fadeOut(function(){ me.immediateClearErrorMessage(); }); } else { this.immediateClearErrorMessage(); } }; TagEditor.prototype.setErrorMessage = function(text) { var old_text = this._error_alert.html(); this._error_alert.html(text); if (old_text == '') { this._error_alert.hide(); this._error_alert.fadeIn(100); } //this._element.css('margin-top', '0');//todo: remove this hack }; TagEditor.prototype.getAddTagHandler = function() { var me = this; return function(tag_name) { if (me.isSelectedTagName(tag_name)) { return; } try { var clean_tag_name = me.cleanTag($.trim(tag_name)); me.addTag(clean_tag_name); me.clearNewTagInput(); me.fixHeight(); } catch (error) { me.setErrorMessage(error); setTimeout(function(){ me.clearErrorMessage(true); }, 1000); } }; }; TagEditor.prototype.getRawNewTagValue = function() { return this._visible_tags_input.val();//without trimming }; TagEditor.prototype.clearNewTagInput = function() { return this._visible_tags_input.val(''); }; TagEditor.prototype.editLastTag = function() { //delete rendered tag var tc = this._tags_container; tc.find('li:last').remove(); //remove from hidden tags input var tags = this.getSelectedTags(); var last_tag = tags.pop(); this.setSelectedTags(tags); //populate the tag editor this._visible_tags_input.val(last_tag); putCursorAtEnd(this._visible_tags_input); }; TagEditor.prototype.setHotBackspace = function(is_hot) { this._has_hot_backspace = is_hot; }; TagEditor.prototype.hasHotBackspace = function() { return this._has_hot_backspace; }; TagEditor.prototype.completeTagInput = function(reject_dupe) { var tag_name = $.trim(this._visible_tags_input.val()); try { tag_name = this.cleanTag(tag_name, reject_dupe); this.addTag(tag_name); this.clearNewTagInput(); } catch (error) { this.setErrorMessage(error); } }; TagEditor.prototype.saveHeight = function() { return; var elem = this._visible_tags_input; this._height = elem.offset().top; }; TagEditor.prototype.fixHeight = function() { return; var new_height = this._visible_tags_input.offset().top; //@todo: replace this by real measurement var element_height = parseInt( this._element.css('height').replace('px', '') ); if (new_height > this._height) { this._element.css('height', element_height + 28);//magic number!!! } else if (new_height < this._height) { this._element.css('height', element_height - 28);//magic number!!! } this.saveHeight(); }; TagEditor.prototype.closeAutoCompleter = function() { this._autocompleter.finish(); }; TagEditor.prototype.getTagInputKeyHandler = function() { var new_tags = this._visible_tags_input; var me = this; return function(e) { if (e.shiftKey) { return; } me.saveHeight(); var key = e.which || e.keyCode; var text = me.getRawNewTagValue(); //space 32, enter 13 if (key == 32 || key == 13) { var tag_name = $.trim(text); if (tag_name.length > 0) { me.completeTagInput(true);//true for reject dupes } me.fixHeight(); return false; } if (text == '') { me.clearErrorMessage(); me.closeAutoCompleter(); } else { try { /* do-nothing validation here * just to report any errors while * the user is typing */ me.cleanTag(text); me.clearErrorMessage(); } catch (error) { me.setErrorMessage(error); } } //8 is backspace if (key == 8 && text.length == 0) { if (me.hasHotBackspace() === true) { me.editLastTag(); me.setHotBackspace(false); } else { me.setHotBackspace(true); } } //27 is escape if (key == 27) { me.clearNewTagInput(); me.clearErrorMessage(); } if (key !== 8) { me.setHotBackspace(false); } me.fixHeight(); return false; }; } TagEditor.prototype.decorate = function(element) { this._element = element; this._hidden_tags_input = element.find('input[name="tags"]');//this one is hidden this._tags_container = element.find('ul.tags'); this._error_alert = $('.tag-editor-error-alert > span'); var me = this; this._tags_container.children().each(function(idx, elem){ var tag = new Tag(); tag.setDeletable(true); tag.setLinkable(false); tag.decorate($(elem)); tag.setDeleteHandler(me.getTagDeleteHandler(tag)); }); var visible_tags_input = element.find('.new-tags-input'); this._visible_tags_input = visible_tags_input; this.saveHeight(); var me = this; var tagsAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], onItemSelect: function(item){ if (me.isSelectedTagName(item['value']) === false) { me.completeTagInput(); } else { me.clearNewTagInput(); } }, minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagsAc.decorate(visible_tags_input); this._autocompleter = tagsAc; visible_tags_input.keyup(this.getTagInputKeyHandler()); element.click(function(e) { visible_tags_input.focus(); return false; }); }; /** * @constructor * Category is a select box item * that has CategoryEditControls */ var Category = function() { SelectBoxItem.call(this); this._state = 'display'; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(Category, SelectBoxItem); Category.prototype.setCategoryTree = function(tree) { this._tree = tree; }; Category.prototype.getCategoryTree = function() { return this._tree; }; Category.prototype.getName = function() { return this.getContent().getContent(); }; Category.prototype.getPath = function() { return this._tree.getPathToItem(this); }; Category.prototype.setState = function(state) { this._state = state; if ( !this._element ) { return; } this._input_box.val(''); if (state === 'display') { this.showContent(); this.hideEditor(); this.hideEditControls(); } else if (state === 'editable') { this._tree._state = 'editable';//a hack this.showContent(); this.hideEditor(); this.showEditControls(); } else if (state === 'editing') { this._prev_tree_state = this._tree.getState(); this._tree._state = 'editing';//a hack this._input_box.val(this.getName()); this.hideContent(); this.showEditor(); this.hideEditControls(); } }; Category.prototype.hideEditControls = function() { this._delete_button.hide(); this._edit_button.hide(); this._element.unbind('mouseenter mouseleave'); }; Category.prototype.showEditControls = function() { var del = this._delete_button; var edit = this._edit_button; this._element.hover( function(){ del.show(); edit.show(); }, function(){ del.hide(); edit.hide(); } ); }; Category.prototype.showEditControlsNow = function() { this._delete_button.show(); this._edit_button.show(); }; Category.prototype.hideContent = function() { this.getContent().getElement().hide(); }; Category.prototype.showContent = function() { this.getContent().getElement().show(); }; Category.prototype.showEditor = function() { this._input_box.show(); this._input_box.focus(); this._save_button.show(); this._cancel_button.show(); }; Category.prototype.hideEditor = function() { this._input_box.hide(); this._save_button.hide(); this._cancel_button.hide(); }; Category.prototype.getInput = function() { return this._input_box.val(); }; Category.prototype.getDeleteHandler = function() { var me = this; return function() { if (confirm(gettext('Delete category?'))) { var tree = me.getCategoryTree(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ tag_name: me.getName(), path: me.getPath() }), cache: false, url: askbot['urls']['delete_tag'], success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); //re-open current branch tree.selectPath(tree.getCurrentPath()); tree.setState('editable'); } else { alert(data['message']); } } }); } return false; }; }; Category.prototype.getSaveHandler = function() { var me = this; var settings = this._settings; //here we need old value and new value return function(){ var to_name = me.getInput(); try { to_name = cleanTag(to_name, settings); var data = { from_name: me.getOriginalName(), to_name: to_name, path: me.getPath() }; $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify(data), cache: false, url: askbot['urls']['rename_tag'], success: function(data) { if (data['success']) { me.setName(to_name); me.setState('editable'); me.showEditControlsNow(); } else { alert(data['message']); } } }); } catch (error) { alert(error); } return false; }; }; Category.prototype.addControls = function() { var input_box = this.makeElement('input'); this._input_box = input_box; this._element.append(input_box); var save_button = this.makeButton( gettext('save'), this.getSaveHandler() ); this._save_button = save_button; this._element.append(save_button); var me = this; var cancel_button = this.makeButton( 'x', function(){ me.setState('editable'); me.showEditControlsNow(); return false; } ); this._cancel_button = cancel_button; this._element.append(cancel_button); var edit_button = this.makeButton( gettext('edit'), function(){ //todo: I would like to make only one at a time editable //var tree = me.getCategoryTree(); //tree.closeAllEditors(); //tree.setState('editable'); //calc path, then select it var tree = me.getCategoryTree(); tree.selectPath(me.getPath()); me.setState('editing'); return false; } ); this._edit_button = edit_button; this._element.append(edit_button); var delete_button = this.makeButton( 'x', this.getDeleteHandler() ); this._delete_button = delete_button; this._element.append(delete_button); }; Category.prototype.getOriginalName = function() { return this._original_name; }; Category.prototype.createDom = function() { Category.superClass_.createDom.call(this); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; Category.prototype.decorate = function(element) { Category.superClass_.decorate.call(this, element); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; var CategoryAdder = function() { WrappedElement.call(this); this._state = 'disabled';//waitedit this._tree = undefined;//category tree this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(CategoryAdder, WrappedElement); CategoryAdder.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategoryAdder.prototype.setLevel = function(level) { this._level = level; }; CategoryAdder.prototype.setState = function(state) { this._state = state; if (!this._element) { return; } if (state === 'waiting') { this._element.show(); this._input.val(''); this._input.hide(); this._save_button.hide(); this._cancel_button.hide(); this._trigger.show(); } else if (state === 'editable') { this._element.show(); this._input.show(); this._input.val(''); this._input.focus(); this._save_button.show(); this._cancel_button.show(); this._trigger.hide(); } else if (state === 'disabled') { this.setState('waiting');//a little hack this._state = 'disabled'; this._element.hide(); } }; CategoryAdder.prototype.cleanCategoryName = function(name) { name = $.trim(name); if (name === '') { throw gettext('category name cannot be empty'); } //if ( this._tree.hasCategory(name) ) { //throw interpolate( //throw gettext('this category already exists'); // [this._tree.getDisplayPathByName(name)] //) //} return cleanTag(name, this._settings); }; CategoryAdder.prototype.getPath = function() { var path = this._tree.getCurrentPath(); if (path.length > this._level + 1) { return path.slice(0, this._level + 1); } else { return path; } }; CategoryAdder.prototype.getSelectBox = function() { return this._tree.getSelectBox(this._level); }; CategoryAdder.prototype.startAdding = function() { try { var name = this._input.val(); name = this.cleanCategoryName(name); } catch (error) { alert(error); return; } //don't add dupes to the same level var existing_names = this.getSelectBox().getNames(); if ($.inArray(name, existing_names) != -1) { alert(gettext('already exists at the current level!')); return; } var me = this; var tree = this._tree; var adder_path = this.getPath(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ path: adder_path, new_category_name: name }), url: askbot['urls']['add_tag_category'], cache: false, success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); tree.selectPath(data['new_path']); tree.setState('editable'); me.setState('waiting'); } else { alert(data['message']); } } }); }; CategoryAdder.prototype.createDom = function() { this._element = this.makeElement('li'); //add open adder link var trigger = this.makeElement('a'); this._trigger = trigger; trigger.html(gettext('add category')); this._element.append(trigger); //add input box and the add button var input = this.makeElement('input'); this._input = input; input.addClass('add-category'); input.attr('name', 'add_category'); this._element.append(input); //add save category button var save_button = this.makeElement('button'); this._save_button = save_button; save_button.html(gettext('save')); this._element.append(save_button); var cancel_button = this.makeElement('button'); this._cancel_button = cancel_button; cancel_button.html('x'); this._element.append(cancel_button); this.setState(this._state); var me = this; setupButtonEventHandlers( trigger, function(){ me.setState('editable'); } ) setupButtonEventHandlers( save_button, function() { me.startAdding(); return false;//prevent form submit } ); setupButtonEventHandlers( cancel_button, function() { me.setState('waiting'); return false;//prevent submit } ); //create input box, button and the "activate" link }; /** * @constructor * SelectBox subclass to create/edit/delete * categories */ var CategorySelectBox = function() { SelectBox.call(this); this._item_class = Category; this._category_adder = undefined; this._tree = undefined;//cat tree this._level = undefined; }; inherits(CategorySelectBox, SelectBox); CategorySelectBox.prototype.setState = function(state) { this._state = state; if (state === 'select') { if (this._category_adder) { this._category_adder.setState('disabled'); } $.each(this._items, function(idx, item){ item.setState('display'); }); } else if (state === 'editable') { this._category_adder.setState('waiting'); $.each(this._items, function(idx, item){ item.setState('editable'); }); } }; CategorySelectBox.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategorySelectBox.prototype.getCategoryTree = function() { }; CategorySelectBox.prototype.setLevel = function(level) { this._level = level; }; CategorySelectBox.prototype.getNames = function() { var names = []; $.each(this._items, function(idx, item) { names.push(item.getName()); }); return names; }; CategorySelectBox.prototype.appendCategoryAdder = function() { var adder = new CategoryAdder(); adder.setLevel(this._level); adder.setCategoryTree(this._tree); this._category_adder = adder; this._element.append(adder.getElement()); }; CategorySelectBox.prototype.createDom = function() { CategorySelectBox.superClass_.createDom(); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; CategorySelectBox.prototype.decorate = function(element) { CategorySelectBox.superClass_.decorate.call(this, element); this.setState(this._state); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; /** * @constructor * turns on/off the category editor */ var CategoryEditorToggle = function() { TwoStateToggle.call(this); }; inherits(CategoryEditorToggle, TwoStateToggle); CategoryEditorToggle.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategoryEditorToggle.prototype.getCategorySelector = function() { return this._category_selector; }; CategoryEditorToggle.prototype.decorate = function(element) { CategoryEditorToggle.superClass_.decorate.call(this, element); }; CategoryEditorToggle.prototype.getDefaultHandler = function() { var me = this; return function() { var editor = me.getCategorySelector(); if (me.isOn()) { me.setState('off-state'); editor.setState('select'); } else { me.setState('on-state'); editor.setState('editable'); } }; }; var CategorySelector = function() { Widget.call(this); this._data = null; this._select_handler = function(){};//dummy default this._current_path = [0];//path points to selected item in tree }; inherits(CategorySelector, Widget); /** * propagates state to the individual selectors */ CategorySelector.prototype.setState = function(state) { this._state = state; if (state === 'editing') { return;//do not propagate this state } $.each(this._selectors, function(idx, selector){ selector.setState(state); }); }; CategorySelector.prototype.getPathToItem = function(item) { function findPathToItemInTree(tree, item) { for (var i = 0; i < tree.length; i++) { var node = tree[i]; if (node[2] === item) { return [i]; } var path = findPathToItemInTree(node[1], item); if (path.length > 0) { path.unshift(i); return path; } } return []; }; return findPathToItemInTree(this._data, item); }; CategorySelector.prototype.applyToDataItems = function(func) { function applyToDataItems(tree) { $.each(tree, function(idx, item) { func(item); applyToDataItems(item[1]); }); }; if (this._data) { applyToDataItems(this._data); } }; CategorySelector.prototype.setData = function(data) { this._clearData this._data = data; var tree = this; function attachCategory(item) { var cat = new Category(); cat.setName(item[0]); cat.setCategoryTree(tree); item[2] = cat; }; this.applyToDataItems(attachCategory); }; /** * clears contents of selector boxes starting from * the given level, in range 0..2 */ CategorySelector.prototype.clearCategoryLevels = function(level) { for (var i = level; i < 3; i++) { this._selectors[i].detachAllItems(); } }; CategorySelector.prototype.getLeafItems = function(selection_path) { //traverse the tree down to items pointed to by the path var data = this._data[0]; for (var i = 1; i < selection_path.length; i++) { data = data[1][selection_path[i]]; } return data[1]; } /** * called when a sub-level needs to open */ CategorySelector.prototype.populateCategoryLevel = function(source_path) { var level = source_path.length - 1; if (level >= 3) { return; } //clear all items downstream this.clearCategoryLevels(level); //populate current selector var selector = this._selectors[level]; var items = this.getLeafItems(source_path); $.each(items, function(idx, item) { var category_name = item[0]; var category_subtree = item[1]; var category_object = item[2]; selector.addItemObject(category_object); if (category_subtree.length > 0) { category_object.addCssClass('tree'); } }); this.setState(this._state);//update state selector.clearSelection(); }; CategorySelector.prototype.selectPath = function(path) { for (var i = 1; i <= path.length; i++) { this.populateCategoryLevel(path.slice(0, i)); } for (var i = 1; i < path.length; i++) { var sel_box = this._selectors[i-1]; var category = sel_box.getItemByIndex(path[i]); sel_box.selectItem(category); } }; CategorySelector.prototype.getSelectBox = function(level) { return this._selectors[level]; }; CategorySelector.prototype.getSelectedPath = function(selected_level) { var path = [0];//root, todo: better use names for path??? /* * upper limit capped by current clicked level * we ignore all selection above the current level */ for (var i = 0; i < selected_level + 1; i++) { var selector = this._selectors[i]; var item = selector.getSelectedItem(); if (item) { path.push(selector.getItemIndex(item)); } else { return path; } } return path; }; /** getter and setter are not symmetric */ CategorySelector.prototype.setSelectHandler = function(handler) { this._select_handler = handler; }; CategorySelector.prototype.getSelectHandlerInternal = function() { return this._select_handler; }; CategorySelector.prototype.setCurrentPath = function(path) { return this._current_path = path; }; CategorySelector.prototype.getCurrentPath = function() { return this._current_path; }; CategorySelector.prototype.getEditorToggle = function() { return this._editor_toggle; }; /*CategorySelector.prototype.closeAllEditors = function() { $.each(this._selectors, function(idx, sel) { sel._category_adder.setState('wait'); $.each(sel._items, function(idx2, item) { item.setState('editable'); }); }); };*/ CategorySelector.prototype.getSelectHandler = function(level) { var me = this; return function(item_data) { if (me.getState() === 'editing') { return;//don't navigate when editing } //1) run the assigned select handler var tag_name = item_data['title'] if (me.getState() === 'select') { /* this one will actually select the tag * maybe a bit too implicit */ me.getSelectHandlerInternal()(tag_name); } //2) if appropriate, populate the higher level if (level < 2) { var current_path = me.getSelectedPath(level); me.setCurrentPath(current_path); me.populateCategoryLevel(current_path); } } }; CategorySelector.prototype.decorate = function(element) { this._element = element; this._selectors = []; var selector0 = new CategorySelectBox(); selector0.setLevel(0); selector0.setCategoryTree(this); selector0.decorate(element.find('.cat-col-0')); selector0.setSelectHandler(this.getSelectHandler(0)); this._selectors.push(selector0); var selector1 = new CategorySelectBox(); selector1.setLevel(1); selector1.setCategoryTree(this); selector1.decorate(element.find('.cat-col-1')); selector1.setSelectHandler(this.getSelectHandler(1)); this._selectors.push(selector1) var selector2 = new CategorySelectBox(); selector2.setLevel(2); selector2.setCategoryTree(this); selector2.decorate(element.find('.cat-col-2')); selector2.setSelectHandler(this.getSelectHandler(2)); this._selectors.push(selector2); if (askbot['data']['userIsAdminOrMod']) { var editor_toggle = new CategoryEditorToggle(); editor_toggle.setCategorySelector(this); var toggle_element = $('.category-editor-toggle'); toggle_element.show(); editor_toggle.decorate(toggle_element); this._editor_toggle = editor_toggle; } this.populateCategoryLevel([0]); }; /** * @constructor * loads html for the category selector from * the server via ajax and activates the * CategorySelector on the loaded HTML */ var CategorySelectorLoader = function() { WrappedElement.call(this); this._is_loaded = false; }; inherits(CategorySelectorLoader, WrappedElement); CategorySelectorLoader.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategorySelectorLoader.prototype.setLoaded = function(is_loaded) { this._is_loaded = is_loaded; }; CategorySelectorLoader.prototype.isLoaded = function() { return this._is_loaded; }; CategorySelectorLoader.prototype.setEditor = function(editor) { this._editor = editor; }; CategorySelectorLoader.prototype.closeEditor = function() { this._editor.hide(); this._editor_buttons.hide(); this._display_tags_container.show(); this._question_body.show(); this._question_controls.show(); }; CategorySelectorLoader.prototype.openEditor = function() { this._editor.show(); this._editor_buttons.show(); this._display_tags_container.hide(); this._question_body.hide(); this._question_controls.hide(); var sel = this._category_selector; sel.setState('select'); sel.getEditorToggle().setState('off-state'); }; CategorySelectorLoader.prototype.addEditorButtons = function() { this._editor.after(this._editor_buttons); }; CategorySelectorLoader.prototype.getOnLoadHandler = function() { var me = this; return function(html){ me.setLoaded(true); //append loaded html to dom var editor = $('<div>' + html + '</div>'); me.setEditor(editor); $('#question-tags').after(editor); var selector = askbot['functions']['initCategoryTree'](); me.setCategorySelector(selector); me.addEditorButtons(); me.openEditor(); //add the save button }; }; CategorySelectorLoader.prototype.startLoadingHTML = function(on_load) { var me = this; $.ajax({ type: 'GET', dataType: 'json', data: { template_name: 'widgets/tag_category_selector.html' }, url: askbot['urls']['get_html_template'], cache: true, success: function(data) { if (data['success']) { on_load(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; CategorySelectorLoader.prototype.getRetagHandler = function() { var me = this; return function() { if (me.isLoaded() === false) { me.startLoadingHTML(me.getOnLoadHandler()); } else { me.openEditor(); } return false; } }; CategorySelectorLoader.prototype.drawNewTags = function(new_tags) { if (new_tags === ''){ this._display_tags_container.html(''); return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tags_html += tag.getElement().outerHTML(); }); this._display_tags_container.html(tags_html); }; CategorySelectorLoader.prototype.getSaveHandler = function() { var me = this; return function() { var tagInput = $('input[name="tags"]'); $.ajax({ type: "POST", url: retagUrl,//add to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ var new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; me.closeEditor(); me.drawNewTags(new_tags.join(' ')); } else { me.closeEditor(); showMessage(me.getElement(), json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, 'sorry, something is not right here'); cancelRetag(); } }); return false; }; }; CategorySelectorLoader.prototype.getCancelHandler = function() { var me = this; return function() { me.closeEditor(); }; }; CategorySelectorLoader.prototype.decorate = function(element) { this._element = element; this._display_tags_container = $('#question-tags'); this._question_body = $('.question .post-body'); this._question_controls = $('#question-controls'); this._editor_buttons = this.makeElement('div'); this._done_button = this.makeElement('button'); this._done_button.html(gettext('save tags')); this._editor_buttons.append(this._done_button); this._cancel_button = this.makeElement('button'); this._cancel_button.html(gettext('cancel')); this._editor_buttons.append(this._cancel_button); this._editor_buttons.find('button').addClass('submit'); this._editor_buttons.addClass('retagger-buttons'); //done button setupButtonEventHandlers( this._done_button, this.getSaveHandler() ); //cancel button setupButtonEventHandlers( this._cancel_button, this.getCancelHandler() ); //retag button setupButtonEventHandlers( element, this.getRetagHandler() ); }; $(document).ready(function() { $('[id^="comments-for-"]').each(function(index, element){ var comments = new PostCommentsWidget(); comments.decorate(element); }); $('[id^="swap-question-with-answer-"]').each(function(idx, element){ var swapper = new QASwapper(); swapper.decorate($(element)); }); $('[id^="post-id-"]').each(function(idx, element){ var deleter = new DeletePostLink(); //confusingly .question-delete matches the answers too need rename var post_id = element.id.split('-').pop(); deleter.setPostId(post_id); deleter.decorate($(element).find('.question-delete')); }); //todo: convert to "control" class var publishBtns = $('.answer-publish, .answer-unpublish'); publishBtns.each(function(idx, btn) { setupButtonEventHandlers($(btn), function() { var answerId = $(btn).data('answerId'); $.ajax({ type: 'POST', dataType: 'json', data: {'answer_id': answerId}, url: askbot['urls']['publishAnswer'], success: function(data) { if (data['success']) { window.location.reload(true); } else { showMessage($(btn), data['message']); } } }); }); }); if (askbot['settings']['tagSource'] == 'category-tree') { var catSelectorLoader = new CategorySelectorLoader(); catSelectorLoader.decorate($('#retag')); } else { questionRetagger.init(); } socialSharing.init(); var proxyUserNameInput = $('#id_post_author_username'); var proxyUserEmailInput = $('#id_post_author_email'); if (proxyUserNameInput.length === 1) { var userSelectHandler = function(data) { proxyUserEmailInput.val(data['data'][0]); }; var fakeUserAc = new AutoCompleter({ url: '/get-users-info/',//askbot['urls']['get_users_info'], promptText: gettext('User name:'), minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10, onItemSelect: userSelectHandler }); fakeUserAc.decorate(proxyUserNameInput); if (proxyUserEmailInput.length === 1) { var tip = new TippedInput(); tip.decorate(proxyUserEmailInput); } } //if groups are enabled - activate share functions var groupsInput = $('#share_group_name'); if (groupsInput.length === 1) { var groupsAc = new AutoCompleter({ url: askbot['urls']['getGroupsList'], promptText: gettext('Group name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); groupsAc.decorate(groupsInput); } var usersInput = $('#share_user_name'); if (usersInput.length === 1) { var usersAc = new AutoCompleter({ url: '/get-users-info/', promptText: gettext('User name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); usersAc.decorate(usersInput); } var showSharedUsers = $('.see-related-users'); if (showSharedUsers.length) { var usersPopup = new ThreadUsersDialog(); usersPopup.setHeadingText(gettext('Shared with the following users:')); usersPopup.decorate(showSharedUsers); } var showSharedGroups = $('.see-related-groups'); if (showSharedGroups.length) { var groupsPopup = new ThreadUsersDialog(); groupsPopup.setHeadingText(gettext('Shared with the following groups:')); groupsPopup.decorate(showSharedGroups); } }); /* google prettify.js from google code */ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c< f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&& (j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r= {b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length, t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b=== "string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value", m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m= a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue= j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m, 250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit", PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
gpl-3.0
drugis/addis
application/src/main/java/org/drugis/addis/entities/relativeeffect/GaussianBase.java
3288
/* * This file is part of ADDIS (Aggregate Data Drug Information System). * ADDIS is distributed from http://drugis.org/. * Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen. * Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels, * Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel * Reid. * Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin * Schimbinschi. * Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter * Reckman. * Copyright © 2013 Gert van Valkenhoef, Joël Kuiper. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.drugis.addis.entities.relativeeffect; import org.apache.commons.math3.distribution.NormalDistribution; import org.drugis.common.beans.AbstractObservable; public abstract class GaussianBase extends AbstractObservable implements Distribution { private double d_mu; private double d_sigma; private NormalDistribution d_dist; public GaussianBase(double mu, double sigma) { if (Double.isNaN(mu)) throw new IllegalArgumentException("mu may not be NaN"); if (Double.isNaN(sigma)) throw new IllegalArgumentException("sigma may not be NaN"); if (sigma < 0.0) throw new IllegalArgumentException("sigma must be >= 0.0"); d_mu = mu; d_sigma = sigma; if (getSigma() != 0.0) { d_dist = new NormalDistribution(d_mu, d_sigma); } } protected double calculateQuantile(double p) { if (getSigma() == 0.0) { return getMu(); } return d_dist.inverseCumulativeProbability(p); } protected double calculateCumulativeProbability(double x) { return d_dist.cumulativeProbability(x); } public double getSigma() { return d_sigma; } public double getMu() { return d_mu; } public GaussianBase plus(GaussianBase other) { if (!canEqual(other)) throw new IllegalArgumentException( "Cannot add together " + getClass().getSimpleName() + " and " + other.getClass().getSimpleName()); return newInstance(getMu() + other.getMu(), Math.sqrt(getSigma() * getSigma() + other.getSigma() * other.getSigma())); } protected abstract GaussianBase newInstance(double mu, double sigma); abstract protected boolean canEqual(GaussianBase other); @Override public boolean equals(Object obj) { if (obj instanceof GaussianBase) { GaussianBase other = (GaussianBase) obj; return canEqual(other) && d_mu == other.d_mu && d_sigma == other.d_sigma; } return false; } @Override public int hashCode() { return ((Double)d_mu).hashCode() + 31 * ((Double)d_sigma).hashCode(); } @Override public String toString() { return getClass().getSimpleName() + "(mu=" + getMu() + ", sigma=" + getSigma() + ")"; } }
gpl-3.0
gera2ld/Stylish-mx
.eslintrc.js
1429
// http://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, extends: 'airbnb-base', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'scripts/webpack.conf.js' } } }, // add your custom rules here 'rules': { // don't require .vue extension when importing 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'no-console': ['warn', { allow: ['error', 'warn', 'info'], }], 'no-param-reassign': ['error', { props: false, }], 'consistent-return': 'off', 'no-use-before-define': ['error', 'nofunc'], 'object-shorthand': ['error', 'always'], 'no-mixed-operators': 'off', 'no-bitwise': ['error', { int32Hint: true }], 'no-underscore-dangle': 'off', 'arrow-parens': ['error', 'as-needed'], 'prefer-promise-reject-errors': 'off', 'prefer-destructuring': ['error', { array: false }], indent: ['error', 2, { MemberExpression: 0, flatTernaryExpressions: true, }], }, globals: { browser: true, zip: true, }, }
gpl-3.0
lastship/plugin.video.lastship
resources/lib/sources/de/movie4k.py
8599
# -*- coding: UTF-8 -*- """ Lastship Add-on (C) 2019 Credits to Lastship, Placenta and Covenant; our thanks go to their creators This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ # Addon Name: Lastship # Addon id: plugin.video.lastship # Addon Provider: Lastship import re import urlparse from resources.lib.modules import cache from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import source_utils from resources.lib.modules import dom_parser from resources.lib.modules import source_faultlog from resources.lib.modules.handler.requestHandler import cRequestHandler class source: def __init__(self): self.priority = 1 self.language = ['de'] self.domains = ['movie4k.sg', 'movie4k.lol', 'movie4k.pe', 'movie4k.tv', 'movie.to', 'movie4k.me', 'movie4k.org', 'movie2k.cm', 'movie2k.nu', 'movie4k.am', 'movie4k.io'] self._base_link = None self.search_link = '/movies.php?list=search&search=%s' @property def base_link(self): if not self._base_link: self._base_link = cache.get(self.__get_base_url, 120, 'http://%s' % self.domains[0]) return self._base_link def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search(False, [localtitle] + source_utils.aliases_to_array(aliases), year) if not url and title != localtitle: url = self.__search(False, [title] + source_utils.aliases_to_array(aliases), year) return url except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year): try: url = self.__search(True, [localtvshowtitle] + source_utils.aliases_to_array(aliases), year) if not url and tvshowtitle != localtvshowtitle: url = self.__search(True, [tvshowtitle] + source_utils.aliases_to_array(aliases), year) if url: return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if url is None: return url = urlparse.urljoin(self.base_link, url) oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() seasonMapping = dom_parser.parse_dom(r, 'select', attrs={'name': 'season'}) seasonMapping = dom_parser.parse_dom(seasonMapping, 'option', req='value') seasonIndex = [i.attrs['value'] for i in seasonMapping if season in i.content] seasonIndex = int(seasonIndex[0]) - 1 seasons = dom_parser.parse_dom(r, 'div', attrs={'id': re.compile('episodediv.+?')}) seasons = seasons[seasonIndex] episodes = dom_parser.parse_dom(seasons, 'option', req='value') url = [i.attrs['value'] for i in episodes if episode == re.findall('\d+', i.content)[0]] if len(url) > 0: return url[0] except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources url = urlparse.urljoin(self.base_link, url) oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = r.replace('\\"', '"') links = dom_parser.parse_dom(r, 'tr', attrs={'id': 'tablemoviesindex2'}) for i in links: try: host = dom_parser.parse_dom(i, 'img', req='alt')[0].attrs['alt'] host = host.split()[0].rsplit('.', 1)[0].strip().lower() host = host.encode('utf-8') valid, host = source_utils.is_host_valid(host, hostDict) if not valid: continue link = dom_parser.parse_dom(i, 'a', req='href')[0].attrs['href'] link = client.replaceHTMLCodes(link) link = urlparse.urljoin(self.base_link, link) link = link.encode('utf-8') sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': link, 'direct': False, 'debridonly': False}) except: pass if len(sources) == 0: raise Exception() return sources except: source_faultlog.logFault(__name__,source_faultlog.tagScrape, url) return sources def resolve(self, url): try: h = urlparse.urlparse(url.strip().lower()).netloc oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = r.rsplit('"underplayer"')[0].rsplit("'underplayer'")[0] u = re.findall('\'(.+?)\'', r) + re.findall('\"(.+?)\"', r) u = [client.replaceHTMLCodes(i) for i in u] u = [i for i in u if i.startswith('http') and not h in i] url = u[-1].encode('utf-8') if 'bit.ly' in url: oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) oRequest.request() url = oRequest.getHeaderLocationUrl() elif 'nullrefer.com' in url: url = url.replace('nullrefer.com/?', '') return url except: source_faultlog.logFault(__name__,source_faultlog.tagResolve) return def __search(self, isSerieSearch, titles, year): try: q = self.search_link % titles[0] q = urlparse.urljoin(self.base_link, q) t = [cleantitle.get(i) for i in set(titles) if i] oRequest = cRequestHandler(q) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() links = dom_parser.parse_dom(r, 'tr', attrs={'id': re.compile('coverPreview.+?')}) tds = [dom_parser.parse_dom(i, 'td') for i in links] tuples = [(dom_parser.parse_dom(i[0], 'a')[0], re.findall('>(\d{4})', i[1].content)) for i in tds if 'ger' in i[4].content] tuplesSortByYear = [(i[0].attrs['href'], i[0].content) for i in tuples if year in i[1]] if len(tuplesSortByYear) > 0 and not isSerieSearch: tuples = tuplesSortByYear elif isSerieSearch: tuples = [(i[0].attrs['href'], i[0].content) for i in tuples if "serie" in i[0].content.lower()] else: tuples = [(i[0].attrs['href'], i[0].content) for i in tuples] urls = [i[0] for i in tuples if cleantitle.get(i[1]) in t] if len(urls) == 0: urls = [i[0] for i in tuples if 'untertitel' not in i[1]] if len(urls) > 0: return source_utils.strip_domain(urls[0]) except: try: source_faultlog.logFault(__name__, source_faultlog.tagSearch, titles[0]) except: return return def __get_base_url(self, fallback): try: for domain in self.domains: try: url = 'http://%s' % domain oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = dom_parser.parse_dom(r, 'meta', attrs={'name': 'author'}, req='content') if r and 'movie4k.io' in r[0].attrs.get('content').lower(): return url except: pass except: pass return fallback
gpl-3.0
opendomo/OpenDomoOS
src/odbase/var/www/scripts/wizFirstConfigurationStep5.sh.js
389
var interval = setInterval(function () { $("button[type=submit]").hide(); $("p.info").hide(); try { var prompting = loadTXT("/data/status.json"); if (prompting.indexOf("started")>0 || prompting.indexOf("active")>0 ) { $("button[type=submit]").show(); $("p.warning").hide(); $("p.info").show(); clearInterval(interval); } } catch (e) { // Silently quit } }, 1000);
gpl-3.0
pureexe/FossilGraderTuToi9
data/grader/compiler/Dev-Cpp/include/basetyps.h
5029
#ifndef _BASETYPS_H #define _BASETYPS_H #if __GNUC__ >=3 #pragma GCC system_header #endif #ifndef __OBJC__ # ifdef __cplusplus # define EXTERN_C extern "C" # else # define EXTERN_C extern # endif /* __cplusplus */ # ifndef __int64 # define __int64 long long # endif # ifndef __int32 # define __int32 long # endif # ifndef __int16 # define __int16 int # endif # ifndef __int8 # define __int8 char # endif # ifndef __small # define __small char # endif # ifndef __hyper # define __hyper long long # endif # define STDMETHODCALLTYPE __stdcall # define STDMETHODVCALLTYPE __cdecl # define STDAPICALLTYPE __stdcall # define STDAPIVCALLTYPE __cdecl # define STDAPI EXTERN_C HRESULT STDAPICALLTYPE # define STDAPI_(t) EXTERN_C t STDAPICALLTYPE # define STDMETHODIMP HRESULT STDMETHODCALLTYPE # define STDMETHODIMP_(t) t STDMETHODCALLTYPE # define STDAPIV EXTERN_C HRESULT STDAPIVCALLTYPE # define STDAPIV_(t) EXTERN_C t STDAPIVCALLTYPE # define STDMETHODIMPV HRESULT STDMETHODVCALLTYPE # define STDMETHODIMPV_(t) t STDMETHODVCALLTYPE # define interface struct # if defined(__cplusplus) && !defined(CINTERFACE) # define STDMETHOD(m) virtual HRESULT STDMETHODCALLTYPE m # define STDMETHOD_(t,m) virtual t STDMETHODCALLTYPE m # define PURE =0 # define THIS_ # define THIS void /* __attribute__((com_interface)) is obsolete in __GNUC__ >= 3 g++ vtables are now COM-compatible by default */ # if defined(__GNUC__) && __GNUC__ < 3 && !defined(NOCOMATTRIBUTE) # define DECLARE_INTERFACE(i) interface __attribute__((com_interface)) i # define DECLARE_INTERFACE_(i,b) interface __attribute__((com_interface)) i : public b # else # define DECLARE_INTERFACE(i) interface i # define DECLARE_INTERFACE_(i,b) interface i : public b # endif # else # define STDMETHOD(m) HRESULT(STDMETHODCALLTYPE *m) # define STDMETHOD_(t,m) t(STDMETHODCALLTYPE *m) # define PURE # define THIS_ INTERFACE *, # define THIS INTERFACE * # ifndef CONST_VTABLE # define CONST_VTABLE # endif # define DECLARE_INTERFACE(i) \ typedef interface i { CONST_VTABLE struct i##Vtbl *lpVtbl; } i; \ typedef CONST_VTABLE struct i##Vtbl i##Vtbl; \ CONST_VTABLE struct i##Vtbl # define DECLARE_INTERFACE_(i,b) DECLARE_INTERFACE(i) # endif # define BEGIN_INTERFACE # define END_INTERFACE # define FWD_DECL(i) typedef interface i i # if defined(__cplusplus) && !defined(CINTERFACE) # define IENUM_THIS(T) # define IENUM_THIS_(T) # else # define IENUM_THIS(T) T* # define IENUM_THIS_(T) T*, # endif # define DECLARE_ENUMERATOR_(I,T) \ DECLARE_INTERFACE_(I,IUnknown) \ { \ STDMETHOD(QueryInterface)(IENUM_THIS_(I) REFIID,PVOID*) PURE; \ STDMETHOD_(ULONG,AddRef)(IENUM_THIS(I)) PURE; \ STDMETHOD_(ULONG,Release)(IENUM_THIS(I)) PURE; \ STDMETHOD(Next)(IENUM_THIS_(I) ULONG,T*,ULONG*) PURE; \ STDMETHOD(Skip)(IENUM_THIS_(I) ULONG) PURE; \ STDMETHOD(Reset)(IENUM_THIS(I)) PURE; \ STDMETHOD(Clone)(IENUM_THIS_(I) I**) PURE; \ } # define DECLARE_ENUMERATOR(T) DECLARE_ENUMERATOR_(IEnum##T,T) #endif /* __OBJC__ */ #ifdef _GUID_DEFINED # warning _GUID_DEFINED is deprecated, use GUID_DEFINED instead #endif #if ! (defined _GUID_DEFINED || defined GUID_DEFINED) /* also defined in winnt.h */ #define GUID_DEFINED typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID,*REFGUID,*LPGUID; #endif /* GUID_DEFINED */ #ifndef UUID_DEFINED #define UUID_DEFINED typedef GUID UUID; #endif /* UUID_DEFINED */ typedef GUID IID; typedef GUID CLSID; typedef CLSID *LPCLSID; typedef IID *LPIID; typedef IID *REFIID; typedef CLSID *REFCLSID; typedef GUID FMTID; typedef FMTID *REFFMTID; typedef unsigned long error_status_t; #define uuid_t UUID typedef unsigned long PROPID; #ifndef _REFGUID_DEFINED #if defined (__cplusplus) && !defined (CINTERFACE) #define REFGUID const GUID& #define REFIID const IID& #define REFCLSID const CLSID& #else #define REFGUID const GUID* const #define REFIID const IID* const #define REFCLSID const CLSID* const #endif #define _REFGUID_DEFINED #define _REFIID_DEFINED #define _REFCLSID_DEFINED #endif #ifndef GUID_SECTION #define GUID_SECTION ".text" #endif /* Explicit naming of .text section for readonly data is only needed for older GGC (pre-2.95). More recent (3.4) GCC puts readonly data in .rdata. */ #if defined (__GNUC__) && (__GNUC__ <= 2 && __GNUC_MINOR__ < 95) #define GUID_SECT __attribute__ ((section (GUID_SECTION))) #else #define GUID_SECT #endif #if !defined(INITGUID) || (defined(INITGUID) && defined(__cplusplus)) #define GUID_EXT EXTERN_C #else #define GUID_EXT #endif #ifdef INITGUID #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) GUID_EXT const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #define DEFINE_OLEGUID(n,l,w1,w2) DEFINE_GUID(n,l,w1,w2,0xC0,0,0,0,0,0,0,0x46) #else #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) GUID_EXT const GUID n #define DEFINE_OLEGUID(n,l,w1,w2) DEFINE_GUID(n,l,w1,w2,0xC0,0,0,0,0,0,0,0x46) #endif #endif
gpl-3.0
zomeki/zomeki2-development
lib/cms/controller/admin/base.rb
1475
class Cms::Controller::Admin::Base < Sys::Controller::Admin::Base include Cms::Controller::Layout helper Cms::FormHelper layout 'admin/cms' def default_url_options Core.concept ? { :concept => Core.concept.id } : {} end def initialize_application return false unless super if params[:cms_navi] && params[:cms_navi][:site] site_id = params[:cms_navi][:site] expires = site_id.blank? ? Time.now - 60 : Time.now + 60*60*24*7 unless Core.user.root? # システム管理者以外は所属サイトしか操作できない site_id = Core.user.site_ids.first unless Core.user.site_ids.include?(site_id.to_i) end cookies[:cms_site] = {:value => site_id, :path => '/', :expires => expires} Core.set_concept(session, 0) return redirect_to "/#{ZomekiCMS::ADMIN_URL_PREFIX}" end if cookies[:cms_site] && !Core.site cookies.delete(:cms_site) Core.site = nil end if Core.user if params[:concept] concept = Cms::Concept.find_by(id: params[:concept]) if concept && Core.site.id != concept.site_id Core.set_concept(session, 0) else Core.set_concept(session, params[:concept]) end elsif Core.request_uri == "/#{ZomekiCMS::ADMIN_URL_PREFIX}" Core.set_concept(session, 0) else Core.set_concept(session) end end return true end end
gpl-3.0
bhalash/sheepie
partials/pagination-post.php
760
<?php /** * Next/Previous Post Pagination Link * ----------------------------------------------------------------------------- * @category PHP Script * @package Sheepie * @author Mark Grealish <[email protected]> * @copyright Copyright (c) 2015 Mark Grealish * @license https://www.gnu.org/copyleft/gpl.html The GNU GPL v3.0 * @version 1.0 * @link https://github.com/bhalash/sheepie */ ?> <nav class="pagination pagination--post noprint vcenter--full" id="pagination--post"> <p class="pagination__previous previous-post meta"> <?php next_post_link('%link', '%title', false); ?> </p> <p class="pagination__next next-post meta"> <?php previous_post_link('%link', '%title', false); ?> </p> </nav>
gpl-3.0
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/checkbox/reports/__init__.py
58
../../../../../share/pyshared/checkbox/reports/__init__.py
gpl-3.0
BitPrepared/Mayalinux
.game/livello_3/azione.sh
3334
#!/bin/bash #controllo se esiste la directory "uomo" e quindi se la risposta al quesito del governatore è giusta o no ok() { cat ../.settings/$GAME/testi_livello_3/ok cp ../.settings/$GAME/testi_livello_4/leggimi.txt ../livello_4/leggimi.txt if [ $GAME == "monkey_island" ] ; then PAROLA='banana' RISPOSTA='monkey' fi if [ $GAME == "matrix" ] ; then PAROLA='cella' RISPOSTA='vigilant' fi if [ $GAME == "star_wars" ] ; then PAROLA='jarjar' RISPOSTA='fener' fi touch ../livello_4/$PAROLA echo "| Dovrai ** creare una parola ** utilizzando le lettere di altre parole. |" >> ../livello_4/leggimi.txt echo "| Le parole che ti serviranno sono i nomi dei file contenuti |" >> ../livello_4/leggimi.txt echo "| nella cartella archivio |" >> ../livello_4/leggimi.txt echo "| visualizza i file all'interno di archivio con il comando |" >> ../livello_4/leggimi.txt echo "| ls -l archivio |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "| Esempio: $ ls -l archivio |" >> ../livello_4/leggimi.txt echo "|Permessi H.Link Utente gruppo Dim. Data +++Ore e minuti +++ Nome |" >> ../livello_4/leggimi.txt echo "| -rw-r--r-- 1 scout scout 2403 ago 27 20:10 leggimi.txt |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "| per decifrare la parola è importante fare attenzione all'ordine |" >> ../livello_4/leggimi.txt echo "| in cui sono disposte le ore, i minuti e i nomi |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "| Quando avrai scoperto la parola |" >> ../livello_4/leggimi.txt echo "| rinomina il file $PAROLA con il comando |" >> ../livello_4/leggimi.txt echo "| mv $PAROLA codice_trovato |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "| e passa al livello sucessivo con il comando |" >> ../livello_4/leggimi.txt echo "| source azione.sh |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "| |" >> ../livello_4/leggimi.txt echo "|___________________________________________________________________________|" >> ../livello_4/leggimi.txt rm -r uomo mkdir -p ../livello_4/archivio source .oggetti.sh #alias ls='function _ls() { ls -l $0| awk '{print $8 "\t" $9}'}; _ls' NUMERO_LIVELLO=4 export LIVELLO=$LIVELLO_STRINGA$NUMERO_LIVELLO cd ../livello_4 } sbagliato() { echo echo Mi spiace, ma la risposta è errata! Puoi riprovare. echo } if [ -d ./uomo ]; then ok else sbagliato fi
gpl-3.0
galengold/split70
qmk_firmware/quantum/process_keycode/process_chording.h
309
#ifndef PROCESS_CHORDING_H #define PROCESS_CHORDING_H #include "quantum.h" // Chording stuff #define CHORDING_MAX 4 bool chording = false; uint8_t chord_keys[CHORDING_MAX] = {0}; uint8_t chord_key_count = 0; uint8_t chord_key_down = 0; bool process_chording(uint16_t keycode, keyrecord_t *record); #endif
gpl-3.0
hacktoberfest17/programming
linked_list/linkedList_java/README.md
60
# DataStructures Basics of Creating Data Structures in JAVA
gpl-3.0
platinummonkey/Vizwall-Website
vizwall/templates/thankyou.html
395
{% extends "base.html" %} {% block title %} Thank You {% endblock %} {% block content %} <!-- LEFT SIDE --> <h1>Your Request Has Been Submitted</span></h1> <div class="textholder_wide"> <p>Please allow 24 hours to process your request. If approved, you will receive a confirmation email with your event details.</p> </div> <div class="clear"></div> <!-- END CONTENT --> {% endblock %}
gpl-3.0
michaelkeiluweit/oxideshop_ce
source/Application/Model/ActionList.php
7605
<?php /** * Copyright © OXID eSales AG. All rights reserved. * See LICENSE file for license details. */ namespace OxidEsales\EshopCommunity\Application\Model; use oxRegistry; use oxDb; /** * Promotion List manager. */ class ActionList extends \OxidEsales\Eshop\Core\Model\ListModel { /** * List Object class name * * @var string */ protected $_sObjectsInListName = 'oxactions'; /** * Loads x last finished promotions * * @param int $iCount count to load */ public function loadFinishedByCount($iCount) { $sViewName = $this->getBaseObject()->getViewName(); $sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto>0 and oxactiveto < " . $oDb->quote($sDate) . " " . $this->_getUserGroupFilter() . " order by oxactiveto desc, oxactivefrom desc limit " . (int) $iCount; $this->selectString($sQ); $this->_aArray = array_reverse($this->_aArray, true); } /** * Loads last finished promotions after given timespan * * @param int $iTimespan timespan to load */ public function loadFinishedByTimespan($iTimespan) { $sViewName = $this->getBaseObject()->getViewName(); $sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()); $sDateFrom = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() - $iTimespan); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto < " . $oDb->quote($sDateTo) . " and oxactiveto > " . $oDb->quote($sDateFrom) . " " . $this->_getUserGroupFilter() . " order by oxactiveto, oxactivefrom"; $this->selectString($sQ); } /** * Loads current promotions */ public function loadCurrent() { $sViewName = $this->getBaseObject()->getViewName(); $sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom != 0 and oxactivefrom < " . $oDb->quote($sDate) . " " . $this->_getUserGroupFilter() . " order by oxactiveto, oxactivefrom"; $this->selectString($sQ); } /** * Loads next not yet started promotions by cound * * @param int $iCount count to load */ public function loadFutureByCount($iCount) { $sViewName = $this->getBaseObject()->getViewName(); $sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . " " . $this->_getUserGroupFilter() . " order by oxactiveto, oxactivefrom limit " . (int) $iCount; $this->selectString($sQ); } /** * Loads next not yet started promotions before the given timespan * * @param int $iTimespan timespan to load */ public function loadFutureByTimespan($iTimespan) { $sViewName = $this->getBaseObject()->getViewName(); $sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()); $sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() + $iTimespan); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . " and oxactivefrom < " . $oDb->quote($sDateTo) . " " . $this->_getUserGroupFilter() . " order by oxactiveto, oxactivefrom"; $this->selectString($sQ); } /** * Returns part of user group filter query * * @param \OxidEsales\Eshop\Application\Model\User $oUser user object * * @return string * @deprecated underscore prefix violates PSR12, will be renamed to "getUserGroupFilter" in next major */ protected function _getUserGroupFilter($oUser = null) // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore { $oUser = ($oUser == null) ? $this->getUser() : $oUser; $sTable = getViewName('oxactions'); $sGroupTable = getViewName('oxgroups'); $aIds = []; // checking for current session user which gives additional restrictions for user itself, users group and country if ($oUser && count($aGroupIds = $oUser->getUserGroups())) { foreach ($aGroupIds as $oGroup) { $aIds[] = $oGroup->getId(); } } $sGroupSql = count($aIds) ? "EXISTS(select oxobject2action.oxid from oxobject2action where oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' and oxobject2action.OXOBJECTID in (" . implode(', ', \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteArray($aIds)) . ") )" : '0'; return " and ( select if(EXISTS(select 1 from oxobject2action, $sGroupTable where $sGroupTable.oxid=oxobject2action.oxobjectid and oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' LIMIT 1), $sGroupSql, 1) ) "; } /** * return true if there are any active promotions * * @return boolean */ public function areAnyActivePromotions() { return (bool) $this->fetchExistsActivePromotion(); } /** * Fetch the information, if there is an active promotion. * * @return string One, if there is an active promotion. */ protected function fetchExistsActivePromotion() { $query = "select 1 from " . getViewName('oxactions') . " where oxtypex = :oxtype and oxactive = :oxactive and oxshopid = :oxshopid limit 1"; return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($query, [ ':oxtype' => 2, ':oxactive' => 1, ':oxshopid' => \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() ]); } /** * load active shop banner list */ public function loadBanners() { $oBaseObject = $this->getBaseObject(); $oViewName = $oBaseObject->getViewName(); $sQ = "select * from {$oViewName} where oxtype=3 and " . $oBaseObject->getSqlActiveSnippet() . " and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' " . $this->_getUserGroupFilter() . " order by oxsort"; $this->selectString($sQ); } }
gpl-3.0
soonhokong/capd4
capdDynSys4/src/mpcapd/poincare/AbstractSection.cpp
1168
///////////////////////////////////////////////////////////////////////////// /// @file AbstractSection.cpp /// /// @author Daniel Wilczak ///////////////////////////////////////////////////////////////////////////// // Copyright (C) 2000-2013 by the CAPD Group. // // This file constitutes a part of the CAPD library, // distributed under the terms of the GNU General Public License. // Consult http://capd.ii.uj.edu.pl/ for details. #ifdef __HAVE_MPFR__ #include "capd/vectalg/mplib.h" #include "capd/poincare/AbstractSection.h" #include "capd/poincare/AbstractSection.hpp" #include "capd/poincare/AffineSection.h" #include "capd/poincare/CoordinateSection.h" #include "capd/poincare/NonlinearSection.h" using namespace capd; template class poincare::AbstractSection<MpMatrix>; template class poincare::AbstractSection<MpIMatrix>; template class poincare::AffineSection<MpMatrix>; template class poincare::AffineSection<MpIMatrix>; template class poincare::CoordinateSection<MpMatrix>; template class poincare::CoordinateSection<MpIMatrix>; template class poincare::NonlinearSection<MpMatrix>; template class poincare::NonlinearSection<MpIMatrix>; #endif
gpl-3.0
rajmahesh/magento2-master
vendor/magento/framework/App/Test/Unit/View/Deployment/Version/Storage/FileTest.php
2744
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\App\Test\Unit\View\Deployment\Version\Storage; use \Magento\Framework\App\View\Deployment\Version\Storage\File; class FileTest extends \PHPUnit_Framework_TestCase { /** * @var File */ private $object; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $directory; protected function setUp() { $this->directory = $this->getMock('Magento\Framework\Filesystem\Directory\WriteInterface'); $filesystem = $this->getMock('Magento\Framework\Filesystem', [], [], '', false); $filesystem ->expects($this->once()) ->method('getDirectoryWrite') ->with('fixture_dir') ->will($this->returnValue($this->directory)); $this->object = new File($filesystem, 'fixture_dir', 'fixture_file.txt'); } public function testLoad() { $this->directory ->expects($this->once()) ->method('readFile') ->with('fixture_file.txt') ->will($this->returnValue('123')); $this->assertEquals('123', $this->object->load()); } /** * @expectedException \Exception * @expectedExceptionMessage Exception to be propagated */ public function testLoadExceptionPropagation() { $this->directory ->expects($this->once()) ->method('readFile') ->with('fixture_file.txt') ->will($this->throwException(new \Exception('Exception to be propagated'))); $this->object->load(); } /** * @expectedException \UnexpectedValueException * @expectedExceptionMessage Unable to retrieve deployment version of static files from the file system */ public function testLoadExceptionWrapping() { $filesystemException = new \Magento\Framework\Exception\FileSystemException( new \Magento\Framework\Phrase('File does not exist') ); $this->directory ->expects($this->once()) ->method('readFile') ->with('fixture_file.txt') ->will($this->throwException($filesystemException)); try { $this->object->load(); } catch (\Exception $e) { $this->assertSame($filesystemException, $e->getPrevious(), 'Wrapping of original exception is expected'); throw $e; } } public function testSave() { $this->directory ->expects($this->once()) ->method('writeFile') ->with('fixture_file.txt', 'input_data', 'w'); $this->object->save('input_data'); } }
gpl-3.0
waterlgndx/darkstar
scripts/zones/Monastic_Cavern/npcs/Loo_Kohor.lua
474
----------------------------------- -- Area: Monastic Cavern -- NPC: Loo Kohor -- Type: Quest NPC -- !pos -48.744 -17.741 -104.954 150 ----------------------------------- package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil; ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(5); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
FernandoUnix/AcessoRestrito
metronic_v4.7.1/theme_rtl/admin_2_rounded/layout_full_height_portlet.html
170487
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7 Version: 4.7.1 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: [email protected] Follow: www.twitter.com/keenthemes Dribbble: www.dribbble.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en" dir="rtl"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8" /> <title>Metronic Admin RTL Theme #2 | Full Height Portlet</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1" name="viewport" /> <meta content="Preview page of Metronic Admin RTL Theme #2 for layout with full height portlet" name="description" /> <meta content="" name="author" /> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME GLOBAL STYLES --> <link href="../assets/global/css/components-rounded-rtl.min.css" rel="stylesheet" id="style_components" type="text/css" /> <link href="../assets/global/css/plugins-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME GLOBAL STYLES --> <!-- BEGIN THEME LAYOUT STYLES --> <link href="../assets/layouts/layout2/css/layout-rtl.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/layouts/layout2/css/themes/blue-rtl.min.css" rel="stylesheet" type="text/css" id="style_color" /> <link href="../assets/layouts/layout2/css/custom-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME LAYOUT STYLES --> <link rel="shortcut icon" href="favicon.ico" /> </head> <!-- END HEAD --> <body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-sidebar-fixed"> <!-- BEGIN HEADER --> <div class="page-header navbar navbar-fixed-top"> <!-- BEGIN HEADER INNER --> <div class="page-header-inner "> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../assets/layouts/layout2/img/logo-default.png" alt="logo" class="logo-default" /> </a> <div class="menu-toggler sidebar-toggler"> <!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header --> </div> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN PAGE ACTIONS --> <!-- DOC: Remove "hide" class to enable the page header actions --> <div class="page-actions"> <div class="btn-group"> <button type="button" class="btn btn-circle btn-outline red dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-plus"></i>&nbsp; <span class="hidden-sm hidden-xs">New&nbsp;</span>&nbsp; <i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="javascript:;"> <i class="icon-docs"></i> New Post </a> </li> <li> <a href="javascript:;"> <i class="icon-tag"></i> New Comment </a> </li> <li> <a href="javascript:;"> <i class="icon-share"></i> Share </a> </li> <li class="divider"> </li> <li> <a href="javascript:;"> <i class="icon-flag"></i> Comments <span class="badge badge-success">4</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span> </a> </li> </ul> </div> </div> <!-- END PAGE ACTIONS --> <!-- BEGIN PAGE TOP --> <div class="page-top"> <!-- BEGIN HEADER SEARCH BOX --> <!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box --> <form class="search-form search-form-expanded" action="page_general_search_3.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search..." name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"> <i class="icon-magnifier"></i> </a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class below "dropdown-extended" to change the dropdown styte --> <!-- DOC: Apply "dropdown-hoverable" class after below "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode --> <!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class --> <li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default"> 7 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3> <span class="bold">12 pending</span> notifications</h3> <a href="page_user_profile_1.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN INBOX DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-envelope-open"></i> <span class="badge badge-default"> 4 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <span class="bold">7 New</span> Messages</h3> <a href="app_inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default"> 3 </span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <span class="bold">12 pending</span> tasks</h3> <a href="app_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">65% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">98% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">10% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">58% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">85% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">38% Complete</span> </span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-user"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../assets/layouts/layout2/img/avatar3_small.jpg" /> <span class="username username-hide-on-mobile"> Nick </span> <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="page_user_profile_1.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="app_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="app_inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="app_todo_2.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="page_user_lock_1.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="page_user_login_1.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> <!-- BEGIN QUICK SIDEBAR TOGGLER --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended quick-sidebar-toggler"> <span class="sr-only">Toggle Quick Sidebar</span> <i class="icon-logout"></i> </li> <!-- END QUICK SIDEBAR TOGGLER --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> <!-- END PAGE TOP --> </div> <!-- END HEADER INNER --> </div> <!-- END HEADER --> <!-- BEGIN HEADER & CONTENT DIVIDER --> <div class="clearfix"> </div> <!-- END HEADER & CONTENT DIVIDER --> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> <!-- END SIDEBAR --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar navbar-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) --> <!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode --> <!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Set data-keep-expand="true" to keep the submenues expanded --> <!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed --> <ul class="page-sidebar-menu page-header-fixed " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <li class="nav-item start "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-home"></i> <span class="title">Dashboard</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item start "> <a href="index.html" class="nav-link "> <i class="icon-bar-chart"></i> <span class="title">Dashboard 1</span> </a> </li> <li class="nav-item start "> <a href="dashboard_2.html" class="nav-link "> <i class="icon-bulb"></i> <span class="title">Dashboard 2</span> <span class="badge badge-success">1</span> </a> </li> <li class="nav-item start "> <a href="dashboard_3.html" class="nav-link "> <i class="icon-graph"></i> <span class="title">Dashboard 3</span> <span class="badge badge-danger">5</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-diamond"></i> <span class="title">UI Features</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="ui_colors.html" class="nav-link "> <span class="title">Color Library</span> </a> </li> <li class="nav-item "> <a href="ui_metronic_grid.html" class="nav-link "> <span class="title">Metronic Grid System</span> </a> </li> <li class="nav-item "> <a href="ui_general.html" class="nav-link "> <span class="title">General Components</span> </a> </li> <li class="nav-item "> <a href="ui_buttons.html" class="nav-link "> <span class="title">Buttons</span> </a> </li> <li class="nav-item "> <a href="ui_buttons_spinner.html" class="nav-link "> <span class="title">Spinner Buttons</span> </a> </li> <li class="nav-item "> <a href="ui_confirmations.html" class="nav-link "> <span class="title">Popover Confirmations</span> </a> </li> <li class="nav-item "> <a href="ui_sweetalert.html" class="nav-link "> <span class="title">Bootstrap Sweet Alerts</span> </a> </li> <li class="nav-item "> <a href="ui_icons.html" class="nav-link "> <span class="title">Font Icons</span> </a> </li> <li class="nav-item "> <a href="ui_socicons.html" class="nav-link "> <span class="title">Social Icons</span> </a> </li> <li class="nav-item "> <a href="ui_typography.html" class="nav-link "> <span class="title">Typography</span> </a> </li> <li class="nav-item "> <a href="ui_tabs_accordions_navs.html" class="nav-link "> <span class="title">Tabs, Accordions & Navs</span> </a> </li> <li class="nav-item "> <a href="ui_timeline.html" class="nav-link "> <span class="title">Timeline 1</span> </a> </li> <li class="nav-item "> <a href="ui_timeline_2.html" class="nav-link "> <span class="title">Timeline 2</span> </a> </li> <li class="nav-item "> <a href="ui_timeline_horizontal.html" class="nav-link "> <span class="title">Horizontal Timeline</span> </a> </li> <li class="nav-item "> <a href="ui_tree.html" class="nav-link "> <span class="title">Tree View</span> </a> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <span class="title">Page Progress Bar</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="ui_page_progress_style_1.html" class="nav-link "> Flash </a> </li> <li class="nav-item "> <a href="ui_page_progress_style_2.html" class="nav-link "> Big Counter </a> </li> </ul> </li> <li class="nav-item "> <a href="ui_blockui.html" class="nav-link "> <span class="title">Block UI</span> </a> </li> <li class="nav-item "> <a href="ui_bootstrap_growl.html" class="nav-link "> <span class="title">Bootstrap Growl Notifications</span> </a> </li> <li class="nav-item "> <a href="ui_notific8.html" class="nav-link "> <span class="title">Notific8 Notifications</span> </a> </li> <li class="nav-item "> <a href="ui_toastr.html" class="nav-link "> <span class="title">Toastr Notifications</span> </a> </li> <li class="nav-item "> <a href="ui_bootbox.html" class="nav-link "> <span class="title">Bootbox Dialogs</span> </a> </li> <li class="nav-item "> <a href="ui_alerts_api.html" class="nav-link "> <span class="title">Metronic Alerts API</span> </a> </li> <li class="nav-item "> <a href="ui_session_timeout.html" class="nav-link "> <span class="title">Session Timeout</span> </a> </li> <li class="nav-item "> <a href="ui_idle_timeout.html" class="nav-link "> <span class="title">User Idle Timeout</span> </a> </li> <li class="nav-item "> <a href="ui_modals.html" class="nav-link "> <span class="title">Modals</span> </a> </li> <li class="nav-item "> <a href="ui_extended_modals.html" class="nav-link "> <span class="title">Extended Modals</span> </a> </li> <li class="nav-item "> <a href="ui_tiles.html" class="nav-link "> <span class="title">Tiles</span> </a> </li> <li class="nav-item "> <a href="ui_datepaginator.html" class="nav-link "> <span class="title">Date Paginator</span> </a> </li> <li class="nav-item "> <a href="ui_nestable.html" class="nav-link "> <span class="title">Nestable List</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-puzzle"></i> <span class="title">Components</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="components_date_time_pickers.html" class="nav-link "> <span class="title">Date & Time Pickers</span> </a> </li> <li class="nav-item "> <a href="components_color_pickers.html" class="nav-link "> <span class="title">Color Pickers</span> <span class="badge badge-danger">2</span> </a> </li> <li class="nav-item "> <a href="components_select2.html" class="nav-link "> <span class="title">Select2 Dropdowns</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_multiselect_dropdown.html" class="nav-link "> <span class="title">Bootstrap Multiselect Dropdowns</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_select.html" class="nav-link "> <span class="title">Bootstrap Select</span> </a> </li> <li class="nav-item "> <a href="components_multi_select.html" class="nav-link "> <span class="title">Bootstrap Multiple Select</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_select_splitter.html" class="nav-link "> <span class="title">Select Splitter</span> </a> </li> <li class="nav-item "> <a href="components_clipboard.html" class="nav-link "> <span class="title">Clipboard</span> </a> </li> <li class="nav-item "> <a href="components_typeahead.html" class="nav-link "> <span class="title">Typeahead Autocomplete</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_tagsinput.html" class="nav-link "> <span class="title">Bootstrap Tagsinput</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_switch.html" class="nav-link "> <span class="title">Bootstrap Switch</span> <span class="badge badge-success">6</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_maxlength.html" class="nav-link "> <span class="title">Bootstrap Maxlength</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_fileinput.html" class="nav-link "> <span class="title">Bootstrap File Input</span> </a> </li> <li class="nav-item "> <a href="components_bootstrap_touchspin.html" class="nav-link "> <span class="title">Bootstrap Touchspin</span> </a> </li> <li class="nav-item "> <a href="components_form_tools.html" class="nav-link "> <span class="title">Form Widgets & Tools</span> </a> </li> <li class="nav-item "> <a href="components_context_menu.html" class="nav-link "> <span class="title">Context Menu</span> </a> </li> <li class="nav-item "> <a href="components_editors.html" class="nav-link "> <span class="title">Markdown & WYSIWYG Editors</span> </a> </li> <li class="nav-item "> <a href="components_code_editors.html" class="nav-link "> <span class="title">Code Editors</span> </a> </li> <li class="nav-item "> <a href="components_ion_sliders.html" class="nav-link "> <span class="title">Ion Range Sliders</span> </a> </li> <li class="nav-item "> <a href="components_noui_sliders.html" class="nav-link "> <span class="title">NoUI Range Sliders</span> </a> </li> <li class="nav-item "> <a href="components_knob_dials.html" class="nav-link "> <span class="title">Knob Circle Dials</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-settings"></i> <span class="title">Form Stuff</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="form_controls.html" class="nav-link "> <span class="title">Bootstrap Form <br>Controls</span> </a> </li> <li class="nav-item "> <a href="form_controls_md.html" class="nav-link "> <span class="title">Material Design <br>Form Controls</span> </a> </li> <li class="nav-item "> <a href="form_validation.html" class="nav-link "> <span class="title">Form Validation</span> </a> </li> <li class="nav-item "> <a href="form_validation_states_md.html" class="nav-link "> <span class="title">Material Design <br>Form Validation States</span> </a> </li> <li class="nav-item "> <a href="form_validation_md.html" class="nav-link "> <span class="title">Material Design <br>Form Validation</span> </a> </li> <li class="nav-item "> <a href="form_layouts.html" class="nav-link "> <span class="title">Form Layouts</span> </a> </li> <li class="nav-item "> <a href="form_repeater.html" class="nav-link "> <span class="title">Form Repeater</span> </a> </li> <li class="nav-item "> <a href="form_input_mask.html" class="nav-link "> <span class="title">Form Input Mask</span> </a> </li> <li class="nav-item "> <a href="form_editable.html" class="nav-link "> <span class="title">Form X-editable</span> </a> </li> <li class="nav-item "> <a href="form_wizard.html" class="nav-link "> <span class="title">Form Wizard</span> </a> </li> <li class="nav-item "> <a href="form_icheck.html" class="nav-link "> <span class="title">iCheck Controls</span> </a> </li> <li class="nav-item "> <a href="form_image_crop.html" class="nav-link "> <span class="title">Image Cropping</span> </a> </li> <li class="nav-item "> <a href="form_fileupload.html" class="nav-link "> <span class="title">Multiple File Upload</span> </a> </li> <li class="nav-item "> <a href="form_dropzone.html" class="nav-link "> <span class="title">Dropzone File Upload</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-bulb"></i> <span class="title">Elements</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="elements_steps.html" class="nav-link "> <span class="title">Steps</span> </a> </li> <li class="nav-item "> <a href="elements_lists.html" class="nav-link "> <span class="title">Lists</span> </a> </li> <li class="nav-item "> <a href="elements_ribbons.html" class="nav-link "> <span class="title">Ribbons</span> </a> </li> <li class="nav-item "> <a href="elements_overlay.html" class="nav-link "> <span class="title">Overlays</span> </a> </li> <li class="nav-item "> <a href="elements_cards.html" class="nav-link "> <span class="title">User Cards</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-briefcase"></i> <span class="title">Tables</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="table_static_basic.html" class="nav-link "> <span class="title">Basic Tables</span> </a> </li> <li class="nav-item "> <a href="table_static_responsive.html" class="nav-link "> <span class="title">Responsive Tables</span> </a> </li> <li class="nav-item "> <a href="table_bootstrap.html" class="nav-link "> <span class="title">Bootstrap Tables</span> </a> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <span class="title">Datatables</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="table_datatables_managed.html" class="nav-link "> Managed Datatables </a> </li> <li class="nav-item "> <a href="table_datatables_buttons.html" class="nav-link "> Buttons Extension </a> </li> <li class="nav-item "> <a href="table_datatables_colreorder.html" class="nav-link "> Colreorder Extension </a> </li> <li class="nav-item "> <a href="table_datatables_rowreorder.html" class="nav-link "> Rowreorder Extension </a> </li> <li class="nav-item "> <a href="table_datatables_scroller.html" class="nav-link "> Scroller Extension </a> </li> <li class="nav-item "> <a href="table_datatables_fixedheader.html" class="nav-link "> FixedHeader Extension </a> </li> <li class="nav-item "> <a href="table_datatables_responsive.html" class="nav-link "> Responsive Extension </a> </li> <li class="nav-item "> <a href="table_datatables_editable.html" class="nav-link "> Editable Datatables </a> </li> <li class="nav-item "> <a href="table_datatables_ajax.html" class="nav-link "> Ajax Datatables </a> </li> </ul> </li> </ul> </li> <li class="nav-item "> <a href="?p=" class="nav-link nav-toggle"> <i class="icon-wallet"></i> <span class="title">Portlets</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="portlet_boxed.html" class="nav-link "> <span class="title">Boxed Portlets</span> </a> </li> <li class="nav-item "> <a href="portlet_light.html" class="nav-link "> <span class="title">Light Portlets</span> </a> </li> <li class="nav-item "> <a href="portlet_solid.html" class="nav-link "> <span class="title">Solid Portlets</span> </a> </li> <li class="nav-item "> <a href="portlet_ajax.html" class="nav-link "> <span class="title">Ajax Portlets</span> </a> </li> <li class="nav-item "> <a href="portlet_draggable.html" class="nav-link "> <span class="title">Draggable Portlets</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-bar-chart"></i> <span class="title">Charts</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="charts_amcharts.html" class="nav-link "> <span class="title">amChart</span> </a> </li> <li class="nav-item "> <a href="charts_flotcharts.html" class="nav-link "> <span class="title">Flot Charts</span> </a> </li> <li class="nav-item "> <a href="charts_flowchart.html" class="nav-link "> <span class="title">Flow Charts</span> </a> </li> <li class="nav-item "> <a href="charts_google.html" class="nav-link "> <span class="title">Google Charts</span> </a> </li> <li class="nav-item "> <a href="charts_echarts.html" class="nav-link "> <span class="title">eCharts</span> </a> </li> <li class="nav-item "> <a href="charts_morris.html" class="nav-link "> <span class="title">Morris Charts</span> </a> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <span class="title">HighCharts</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="charts_highcharts.html" class="nav-link "> HighCharts </a> </li> <li class="nav-item "> <a href="charts_highstock.html" class="nav-link "> HighStock </a> </li> <li class="nav-item "> <a href="charts_highmaps.html" class="nav-link "> HighMaps </a> </li> </ul> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-pointer"></i> <span class="title">Maps</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="maps_google.html" class="nav-link "> <span class="title">Google Maps</span> </a> </li> <li class="nav-item "> <a href="maps_vector.html" class="nav-link "> <span class="title">Vector Maps</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-layers"></i> <span class="title">Page Layouts</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="layout_blank_page.html" class="nav-link "> <span class="title">Blank Page</span> </a> </li> <li class="nav-item "> <a href="layout_ajax_page.html" class="nav-link "> <span class="title">Ajax Content Layout</span> </a> </li> <li class="nav-item "> <a href="layout_language_bar.html" class="nav-link "> <span class="title">Header Language Bar</span> </a> </li> <li class="nav-item "> <a href="layout_footer_fixed.html" class="nav-link "> <span class="title">Fixed Footer</span> </a> </li> <li class="nav-item "> <a href="layout_boxed_page.html" class="nav-link "> <span class="title">Boxed Page</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-feed"></i> <span class="title">Sidebar Layouts</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="layout_sidebar_menu_accordion.html" class="nav-link "> <span class="title">Sidebar Accordion Menu</span> </a> </li> <li class="nav-item "> <a href="layout_sidebar_menu_compact.html" class="nav-link "> <span class="title">Sidebar Compact Menu</span> </a> </li> <li class="nav-item "> <a href="layout_sidebar_reversed.html" class="nav-link "> <span class="title">Reversed Sidebar Page</span> </a> </li> <li class="nav-item "> <a href="layout_sidebar_fixed.html" class="nav-link "> <span class="title">Fixed Sidebar Layout</span> </a> </li> <li class="nav-item "> <a href="layout_sidebar_closed.html" class="nav-link "> <span class="title">Closed Sidebar Layout</span> </a> </li> </ul> </li> <li class="nav-item active open"> <a href="javascript:;" class="nav-link nav-toggle"> <i class=" icon-wrench"></i> <span class="title">Custom Layouts</span> <span class="selected"></span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="layout_disabled_menu.html" class="nav-link "> <span class="title">Disabled Menu Links</span> </a> </li> <li class="nav-item active open"> <a href="layout_full_height_portlet.html" class="nav-link "> <span class="title">Full Height Portlet</span> <span class="selected"></span> </a> </li> <li class="nav-item "> <a href="layout_full_height_content.html" class="nav-link "> <span class="title">Full Height Content</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-basket"></i> <span class="title">eCommerce</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="ecommerce_index.html" class="nav-link "> <i class="icon-home"></i> <span class="title">Dashboard</span> </a> </li> <li class="nav-item "> <a href="ecommerce_orders.html" class="nav-link "> <i class="icon-basket"></i> <span class="title">Orders</span> </a> </li> <li class="nav-item "> <a href="ecommerce_orders_view.html" class="nav-link "> <i class="icon-tag"></i> <span class="title">Order View</span> </a> </li> <li class="nav-item "> <a href="ecommerce_products.html" class="nav-link "> <i class="icon-graph"></i> <span class="title">Products</span> </a> </li> <li class="nav-item "> <a href="ecommerce_products_edit.html" class="nav-link "> <i class="icon-graph"></i> <span class="title">Product Edit</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-docs"></i> <span class="title">Apps</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="app_todo.html" class="nav-link "> <i class="icon-clock"></i> <span class="title">Todo 1</span> </a> </li> <li class="nav-item "> <a href="app_todo_2.html" class="nav-link "> <i class="icon-check"></i> <span class="title">Todo 2</span> </a> </li> <li class="nav-item "> <a href="app_inbox.html" class="nav-link "> <i class="icon-envelope"></i> <span class="title">Inbox</span> </a> </li> <li class="nav-item "> <a href="app_calendar.html" class="nav-link "> <i class="icon-calendar"></i> <span class="title">Calendar</span> </a> </li> <li class="nav-item "> <a href="app_ticket.html" class="nav-link "> <i class="icon-notebook"></i> <span class="title">Support</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-user"></i> <span class="title">User</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_user_profile_1.html" class="nav-link "> <i class="icon-user"></i> <span class="title">Profile 1</span> </a> </li> <li class="nav-item "> <a href="page_user_profile_1_account.html" class="nav-link "> <i class="icon-user-female"></i> <span class="title">Profile 1 Account</span> </a> </li> <li class="nav-item "> <a href="page_user_profile_1_help.html" class="nav-link "> <i class="icon-user-following"></i> <span class="title">Profile 1 Help</span> </a> </li> <li class="nav-item "> <a href="page_user_profile_2.html" class="nav-link "> <i class="icon-users"></i> <span class="title">Profile 2</span> </a> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> <span class="title">Login</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a> </li> <li class="nav-item "> <a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a> </li> <li class="nav-item "> <a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a> </li> <li class="nav-item "> <a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a> </li> <li class="nav-item "> <a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a> </li> <li class="nav-item "> <a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a> </li> </ul> </li> <li class="nav-item "> <a href="page_user_lock_1.html" class="nav-link " target="_blank"> <i class="icon-lock"></i> <span class="title">Lock Screen 1</span> </a> </li> <li class="nav-item "> <a href="page_user_lock_2.html" class="nav-link " target="_blank"> <i class="icon-lock-open"></i> <span class="title">Lock Screen 2</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-social-dribbble"></i> <span class="title">General</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_general_about.html" class="nav-link "> <i class="icon-info"></i> <span class="title">About</span> </a> </li> <li class="nav-item "> <a href="page_general_contact.html" class="nav-link "> <i class="icon-call-end"></i> <span class="title">Contact</span> </a> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> <span class="title">Portfolio</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_general_portfolio_1.html" class="nav-link "> Portfolio 1 </a> </li> <li class="nav-item "> <a href="page_general_portfolio_2.html" class="nav-link "> Portfolio 2 </a> </li> <li class="nav-item "> <a href="page_general_portfolio_3.html" class="nav-link "> Portfolio 3 </a> </li> <li class="nav-item "> <a href="page_general_portfolio_4.html" class="nav-link "> Portfolio 4 </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-magnifier"></i> <span class="title">Search</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_general_search.html" class="nav-link "> Search 1 </a> </li> <li class="nav-item "> <a href="page_general_search_2.html" class="nav-link "> Search 2 </a> </li> <li class="nav-item "> <a href="page_general_search_3.html" class="nav-link "> Search 3 </a> </li> <li class="nav-item "> <a href="page_general_search_4.html" class="nav-link "> Search 4 </a> </li> <li class="nav-item "> <a href="page_general_search_5.html" class="nav-link "> Search 5 </a> </li> </ul> </li> <li class="nav-item "> <a href="page_general_pricing.html" class="nav-link "> <i class="icon-tag"></i> <span class="title">Pricing</span> </a> </li> <li class="nav-item "> <a href="page_general_faq.html" class="nav-link "> <i class="icon-wrench"></i> <span class="title">FAQ</span> </a> </li> <li class="nav-item "> <a href="page_general_blog.html" class="nav-link "> <i class="icon-pencil"></i> <span class="title">Blog</span> </a> </li> <li class="nav-item "> <a href="page_general_blog_post.html" class="nav-link "> <i class="icon-note"></i> <span class="title">Blog Post</span> </a> </li> <li class="nav-item "> <a href="page_general_invoice.html" class="nav-link "> <i class="icon-envelope"></i> <span class="title">Invoice</span> </a> </li> <li class="nav-item "> <a href="page_general_invoice_2.html" class="nav-link "> <i class="icon-envelope"></i> <span class="title">Invoice 2</span> </a> </li> </ul> </li> <li class="nav-item "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-settings"></i> <span class="title">System</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="page_cookie_consent_1.html" class="nav-link "> <span class="title">Cookie Consent 1</span> </a> </li> <li class="nav-item "> <a href="page_cookie_consent_2.html" class="nav-link "> <span class="title">Cookie Consent 2</span> </a> </li> <li class="nav-item "> <a href="page_system_coming_soon.html" class="nav-link " target="_blank"> <span class="title">Coming Soon</span> </a> </li> <li class="nav-item "> <a href="page_system_404_1.html" class="nav-link "> <span class="title">404 Page 1</span> </a> </li> <li class="nav-item "> <a href="page_system_404_2.html" class="nav-link " target="_blank"> <span class="title">404 Page 2</span> </a> </li> <li class="nav-item "> <a href="page_system_404_3.html" class="nav-link " target="_blank"> <span class="title">404 Page 3</span> </a> </li> <li class="nav-item "> <a href="page_system_500_1.html" class="nav-link "> <span class="title">500 Page 1</span> </a> </li> <li class="nav-item "> <a href="page_system_500_2.html" class="nav-link " target="_blank"> <span class="title">500 Page 2</span> </a> </li> </ul> </li> <li class="nav-item"> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-folder"></i> <span class="title">Multi Level Menu</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li class="nav-item"> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-settings"></i> Item 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item"> <a href="?p=dashboard-2" target="_blank" class="nav-link"> <i class="icon-user"></i> Arrow Toggle <span class="arrow nav-toggle"></span> </a> <ul class="sub-menu"> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-power"></i> Sample Link 1</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-paper-plane"></i> Sample Link 1</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-star"></i> Sample Link 1</a> </li> </ul> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-camera"></i> Sample Link 1</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-link"></i> Sample Link 2</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-pointer"></i> Sample Link 3</a> </li> </ul> </li> <li class="nav-item"> <a href="?p=dashboard-2" target="_blank" class="nav-link"> <i class="icon-globe"></i> Arrow Toggle <span class="arrow nav-toggle"></span> </a> <ul class="sub-menu"> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-tag"></i> Sample Link 1</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-pencil"></i> Sample Link 1</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-graph"></i> Sample Link 1</a> </li> </ul> </li> <li class="nav-item"> <a href="#" class="nav-link"> <i class="icon-bar-chart"></i> Item 3 </a> </li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> </div> <!-- END SIDEBAR --> </div> <!-- END SIDEBAR --> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <!-- BEGIN CONTENT BODY --> <div class="page-content"> <!-- BEGIN PAGE HEADER--> <!-- BEGIN THEME PANEL --> <div class="theme-panel"> <div class="toggler tooltips" data-container="body" data-placement="left" data-html="true" data-original-title="Click to open advance theme customizer panel"> <i class="icon-settings"></i> </div> <div class="toggler-close"> <i class="icon-close"></i> </div> <div class="theme-options"> <div class="theme-option theme-colors clearfix"> <span> THEME COLOR </span> <ul> <li class="color-default current tooltips" data-style="default" data-container="body" data-original-title="Default"> </li> <li class="color-grey tooltips" data-style="grey" data-container="body" data-original-title="Grey"> </li> <li class="color-blue tooltips" data-style="blue" data-container="body" data-original-title="Blue"> </li> <li class="color-dark tooltips" data-style="dark" data-container="body" data-original-title="Dark"> </li> <li class="color-light tooltips" data-style="light" data-container="body" data-original-title="Light"> </li> </ul> </div> <div class="theme-option"> <span> Theme Style </span> <select class="layout-style-option form-control input-small"> <option value="square" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </div> <div class="theme-option"> <span> Layout </span> <select class="layout-option form-control input-small"> <option value="fluid" selected="selected">Fluid</option> <option value="boxed">Boxed</option> </select> </div> <div class="theme-option"> <span> Header </span> <select class="page-header-option form-control input-small"> <option value="fixed" selected="selected">Fixed</option> <option value="default">Default</option> </select> </div> <div class="theme-option"> <span> Top Dropdown</span> <select class="page-header-top-dropdown-style-option form-control input-small"> <option value="light" selected="selected">Light</option> <option value="dark">Dark</option> </select> </div> <div class="theme-option"> <span> Sidebar Mode</span> <select class="sidebar-option form-control input-small"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> <div class="theme-option"> <span> Sidebar Style</span> <select class="sidebar-style-option form-control input-small"> <option value="default" selected="selected">Default</option> <option value="compact">Compact</option> </select> </div> <div class="theme-option"> <span> Sidebar Menu </span> <select class="sidebar-menu-option form-control input-small"> <option value="accordion" selected="selected">Accordion</option> <option value="hover">Hover</option> </select> </div> <div class="theme-option"> <span> Sidebar Position </span> <select class="sidebar-pos-option form-control input-small"> <option value="left" selected="selected">Left</option> <option value="right">Right</option> </select> </div> <div class="theme-option"> <span> Footer </span> <select class="page-footer-option form-control input-small"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </div> </div> </div> <!-- END THEME PANEL --> <h1 class="page-title"> Full Height Portlet <small>layout with full height portlet</small> </h1> <div class="page-bar"> <ul class="page-breadcrumb"> <li> <i class="icon-home"></i> <a href="index.html">Home</a> <i class="fa fa-angle-right"></i> </li> <li> <span>Custom Layouts</span> </li> </ul> <div class="page-toolbar"> <div class="btn-group pull-right"> <button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true"> Actions <i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu pull-right" role="menu"> <li> <a href="#"> <i class="icon-bell"></i> Action</a> </li> <li> <a href="#"> <i class="icon-shield"></i> Another action</a> </li> <li> <a href="#"> <i class="icon-user"></i> Something else here</a> </li> <li class="divider"> </li> <li> <a href="#"> <i class="icon-bag"></i> Separated link</a> </li> </ul> </div> </div> </div> <!-- END PAGE HEADER--> <div class="portlet light portlet-fit full-height-content full-height-content-scrollable "> <div class="portlet-title"> <div class="caption"> <i class=" icon-layers font-green"></i> <span class="caption-subject font-green bold uppercase">Basic Diagram</span> </div> <div class="actions"> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-cloud-upload"></i> </a> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-wrench"></i> </a> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-trash"></i> </a> </div> </div> <div class="portlet-body"> <div class="full-height-content-body"> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? </p> <p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. </p> <p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> </div> </div> </div> </div> <!-- END CONTENT BODY --> </div> <!-- END CONTENT --> <!-- BEGIN QUICK SIDEBAR --> <a href="javascript:;" class="page-quick-sidebar-toggler"> <i class="icon-login"></i> </a> <div class="page-quick-sidebar-wrapper" data-close-on-body-click="false"> <div class="page-quick-sidebar"> <ul class="nav nav-tabs"> <li class="active"> <a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users <span class="badge badge-danger">2</span> </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts <span class="badge badge-success">7</span> </a> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu pull-right"> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-bell"></i> Alerts </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-info"></i> Notifications </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-speech"></i> Activities </a> </li> <li class="divider"></li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-settings"></i> Settings </a> </li> </ul> </li> </ul> <div class="tab-content"> <div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1"> <div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list"> <h3 class="list-heading">Staff</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-success">8</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Bob Nilson</h4> <div class="media-heading-sub"> Project Manager </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Nick Larson</h4> <div class="media-heading-sub"> Art Director </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">3</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Hubert</h4> <div class="media-heading-sub"> CTO </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ella Wong</h4> <div class="media-heading-sub"> CEO </div> </div> </li> </ul> <h3 class="list-heading">Customers</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-warning">2</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lara Kunis</h4> <div class="media-heading-sub"> CEO, Loop Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="label label-sm label-success">new</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ernie Kyllonen</h4> <div class="media-heading-sub"> Project Manager, <br> SmartBizz PTL </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lisa Stone</h4> <div class="media-heading-sub"> CTO, Keort Inc </div> <div class="media-heading-small"> Last seen 13:10 PM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-success">7</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Portalatin</h4> <div class="media-heading-sub"> CFO, H&D LTD </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Irina Savikova</h4> <div class="media-heading-sub"> CEO, Tizda Motors Inc </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">4</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Maria Gomez</h4> <div class="media-heading-sub"> Manager, Infomatic Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> </ul> </div> <div class="page-quick-sidebar-item"> <div class="page-quick-sidebar-chat-user"> <div class="page-quick-sidebar-nav"> <a href="javascript:;" class="page-quick-sidebar-back-to-list"> <i class="icon-arrow-left"></i>Back</a> </div> <div class="page-quick-sidebar-chat-user-messages"> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> When could you send me the report ? </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:15</span> <span class="body"> Its almost done. I will be sending it shortly </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> Alright. Thanks! :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:16</span> <span class="body"> You are most welcome. Sorry for the delay. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> No probs. Just take your time :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Alright. I just emailed it to you. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Great! Thanks. Will check it right away. </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Please let me know if you have any comment. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span> </div> </div> </div> <div class="page-quick-sidebar-chat-user-form"> <div class="input-group"> <input type="text" class="form-control" placeholder="Type a message here..."> <div class="input-group-btn"> <button type="button" class="btn green"> <i class="icon-paper-clip"></i> </button> </div> </div> </div> </div> </div> </div> <div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2"> <div class="page-quick-sidebar-alerts-list"> <h3 class="list-heading">General</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-warning"> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> <h3 class="list-heading">System</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-warning"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-default "> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> </div> </div> <div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3"> <div class="page-quick-sidebar-settings-list"> <h3 class="list-heading">General Settings</h3> <ul class="list-items borderless"> <li> Enable Notifications <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Allow Tracking <input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Log Errors <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Auto Sumbit Issues <input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Enable SMS Alerts <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <h3 class="list-heading">System Settings</h3> <ul class="list-items borderless"> <li> Security Level <select class="form-control input-inline input-sm input-small"> <option value="1">Normal</option> <option value="2" selected>Medium</option> <option value="e">High</option> </select> </li> <li> Failed Email Attempts <input class="form-control input-inline input-sm input-small" value="5" /> </li> <li> Secondary SMTP Port <input class="form-control input-inline input-sm input-small" value="3560" /> </li> <li> Notify On System Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Notify On SMTP Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <div class="inner-content"> <button class="btn btn-success"> <i class="icon-settings"></i> Save Changes</button> </div> </div> </div> </div> </div> </div> <!-- END QUICK SIDEBAR --> </div> <!-- END CONTAINER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="page-footer-inner"> 2016 &copy; Metronic Theme By <a target="_blank" href="http://keenthemes.com">Keenthemes</a> &nbsp;|&nbsp; <a href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> </div> <!-- END FOOTER --> <!-- BEGIN QUICK NAV --> <nav class="quick-nav"> <a class="quick-nav-trigger" href="#0"> <span aria-hidden="true"></span> </a> <ul> <li> <a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" target="_blank" class="active"> <span>Purchase Metronic</span> <i class="icon-basket"></i> </a> </li> <li> <a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/reviews/4021469?ref=keenthemes" target="_blank"> <span>Customer Reviews</span> <i class="icon-users"></i> </a> </li> <li> <a href="http://keenthemes.com/showcast/" target="_blank"> <span>Showcase</span> <i class="icon-user"></i> </a> </li> <li> <a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank"> <span>Changelog</span> <i class="icon-graph"></i> </a> </li> </ul> <span aria-hidden="true" class="quick-nav-bg"></span> </nav> <div class="quick-nav-overlay"></div> <!-- END QUICK NAV --> <!--[if lt IE 9]> <script src="../assets/global/plugins/respond.min.js"></script> <script src="../assets/global/plugins/excanvas.min.js"></script> <script src="../assets/global/plugins/ie8.fix.min.js"></script> <![endif]--> <!-- BEGIN CORE PLUGINS --> <script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN THEME GLOBAL SCRIPTS --> <script src="../assets/global/scripts/app.min.js" type="text/javascript"></script> <!-- END THEME GLOBAL SCRIPTS --> <!-- BEGIN THEME LAYOUT SCRIPTS --> <script src="../assets/layouts/layout2/scripts/layout.min.js" type="text/javascript"></script> <script src="../assets/layouts/layout2/scripts/demo.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script> <!-- END THEME LAYOUT SCRIPTS --> </body> </html>
gpl-3.0
ffurano/xrootd-xrdhttp
src/XrdSecgsi/XrdSecgsiProxy.cc
25410
/******************************************************************************/ /* */ /* X r d S e c g s i P r o x y . c c */ /* */ /* (c) 2005, G. Ganis / CERN */ /* */ /* This file is part of the XRootD software suite. */ /* */ /* XRootD 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. */ /* */ /* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */ /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */ /* */ /* The copyright holder's institutional names and contributor's names may not */ /* be used to endorse or promote products derived from this software without */ /* specific prior written permission of the institution or contributor. */ /* */ /******************************************************************************/ /* ************************************************************************** */ /* */ /* Manage GSI proxies */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #include <pwd.h> #include <time.h> #include "XrdOuc/XrdOucString.hh" #include "XrdSys/XrdSysLogger.hh" #include "XrdSys/XrdSysError.hh" #include "XrdSys/XrdSysPwd.hh" #include "XrdSut/XrdSutAux.hh" #include "XrdCrypto/XrdCryptoAux.hh" #include "XrdCrypto/XrdCryptoFactory.hh" #include "XrdCrypto/XrdCryptoX509.hh" #include "XrdCrypto/XrdCryptoX509Req.hh" #include "XrdCrypto/XrdCryptoX509Chain.hh" #include "XrdCrypto/XrdCryptoX509Crl.hh" #include "XrdCrypto/XrdCryptosslgsiX509Chain.hh" #include "XrdCrypto/XrdCryptosslgsiAux.hh" #include "XrdSecgsi/XrdSecgsiTrace.hh" #define PRT(x) {cerr <<x <<endl;} // // enum enum kModes { kM_undef = 0, kM_init = 1, kM_info, kM_destroy, kM_help }; const char *gModesStr[] = { "kM_undef", "kM_init", "kM_info", "kM_destroy", "kM_help" }; // // Prototypes // void Menu(); int ParseArguments(int argc, char **argv); bool CheckOption(XrdOucString opt, const char *ref, int &ival); void Display(XrdCryptoX509 *xp); // // Globals // int Mode = kM_undef; bool Debug = 0; bool Exists = 0; XrdCryptoFactory *gCryptoFactory = 0; XrdOucString CryptoMod = "ssl"; XrdOucString CAdir = "/etc/grid-security/certificates/"; XrdOucString CRLdir = "/etc/grid-security/certificates/"; XrdOucString DefEEcert = "/.globus/usercert.pem"; XrdOucString DefEEkey = "/.globus/userkey.pem"; XrdOucString DefPXcert = "/tmp/x509up_u"; XrdOucString EEcert = ""; XrdOucString EEkey = ""; XrdOucString PXcert = ""; XrdOucString Valid = "12:00"; int Bits = 512; int PathLength = 0; int ClockSkew = 30; // For error logging and tracing static XrdSysLogger Logger; static XrdSysError eDest(0,"proxy_"); XrdOucTrace *gsiTrace = 0; int main( int argc, char **argv ) { // Test implemented functionality int secValid = 0; XrdProxyOpt_t pxopt; XrdCryptosslgsiX509Chain *cPXp = 0; XrdCryptoX509 *xPXp = 0, *xPXPp = 0; XrdCryptoRSA *kPXp = 0; XrdCryptoX509ParseFile_t ParseFile = 0; int prc = 0; int nci = 0; int exitrc = 0; // Parse arguments if (ParseArguments(argc,argv)) { exit(1); } // // Initiate error logging and tracing eDest.logger(&Logger); if (!gsiTrace) gsiTrace = new XrdOucTrace(&eDest); if (gsiTrace) { if (Debug) // Medium level gsiTrace->What |= (TRACE_Authen | TRACE_Debug); } // // Set debug flags in other modules if (Debug) { XrdSutSetTrace(sutTRACE_Debug); XrdCryptoSetTrace(cryptoTRACE_Debug); } // // Load the crypto factory if (!(gCryptoFactory = XrdCryptoFactory::GetCryptoFactory(CryptoMod.c_str()))) { PRT(": cannot instantiate factory "<<CryptoMod); exit(1); } if (Debug) gCryptoFactory->SetTrace(cryptoTRACE_Debug); // // Depending on the mode switch (Mode) { case kM_help: // // We should not get here ... print the menu and go Menu(); break; case kM_init: // // Init proxies secValid = XrdSutParseTime(Valid.c_str(), 1); pxopt.bits = Bits; pxopt.valid = secValid; pxopt.depthlen = PathLength; cPXp = new XrdCryptosslgsiX509Chain(); prc = XrdSslgsiX509CreateProxy(EEcert.c_str(), EEkey.c_str(), &pxopt, cPXp, &kPXp, PXcert.c_str()); if (prc == 0) { // The proxy is the first certificate xPXp = cPXp->Begin(); if (xPXp) { Display(xPXp); } else { PRT( ": proxy certificate not found"); } } else { PRT( ": problems creating proxy"); } break; case kM_destroy: // // Destroy existing proxies if (unlink(PXcert.c_str()) == -1) { perror("xrdgsiproxy"); } break; case kM_info: // // Display info about existing proxies if (!(ParseFile = gCryptoFactory->X509ParseFile())) { PRT("cannot attach to ParseFile function!"); break; } // Parse the proxy file cPXp = new XrdCryptosslgsiX509Chain(); nci = (*ParseFile)(PXcert.c_str(), cPXp); if (nci < 2) { if (Exists) { exitrc = 1; } else { PRT("proxy files must have at least two certificates" " (found only: "<<nci<<")"); } break; } // The proxy is the first certificate xPXp = cPXp->Begin(); if (xPXp) { if (!Exists) { Display(xPXp); if (strstr(xPXp->Subject(), "CN=limited proxy")) { xPXPp = cPXp->SearchBySubject(xPXp->Issuer()); if (xPXPp) { Display(xPXPp); } else { PRT("WARNING: found 'limited proxy' but not the associated proxy!"); } } } else { // Check time validity secValid = XrdSutParseTime(Valid.c_str(), 1); int tl = xPXp->NotAfter() -(int)time(0); if (Debug) PRT("secValid: " << secValid<< ", tl: "<<tl<<", ClockSkew:"<<ClockSkew); if (secValid > tl + ClockSkew) { exitrc = 1; break; } // Check bit strenght if (Debug) PRT("BitStrength: " << xPXp->BitStrength()<< ", Bits: "<<Bits); if (xPXp->BitStrength() < Bits) { exitrc = 1; break; } } } else { if (Exists) { exitrc = 1; } else { PRT( ": proxy certificate not found"); } } break; default: // // Print menu Menu(); } exit(exitrc); } int ParseArguments(int argc, char **argv) { // Parse application arguments filling relevant global variables // Number of arguments if (argc < 0 || !argv[0]) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Insufficient number or arguments! +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); // Print main menu Menu(); return 1; } --argc; ++argv; // // Loop over arguments while ((argc >= 0) && (*argv)) { XrdOucString opt = ""; int ival = -1; if(*(argv)[0] == '-') { opt = *argv; opt.erase(0,1); if (CheckOption(opt,"h",ival) || CheckOption(opt,"help",ival) || CheckOption(opt,"menu",ival)) { Mode = kM_help; } else if (CheckOption(opt,"debug",ival)) { Debug = ival; } else if (CheckOption(opt,"e",ival)) { Exists = 1; } else if (CheckOption(opt,"exists",ival)) { Exists = 1; } else if (CheckOption(opt,"f",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { PXcert = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-f' requires a proxy file name: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"file",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { PXcert = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-file' requires a proxy file name: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"out",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { PXcert = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-out' requires a proxy file name: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"cert",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { EEcert = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-cert' requires a cert file name: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"key",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { EEkey = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-key' requires a key file name: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"certdir",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { CAdir = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-certdir' requires a dir path: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"valid",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { Valid = *argv; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-valid' requires a time string: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"path-length",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { PathLength = strtol(*argv,0,10); if (PathLength < -1 || errno == ERANGE) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-path-length' requires a number >= -1: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-path-length' requires a number >= -1: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"bits",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { Bits = strtol(*argv, 0, 10); Bits = (Bits > 512) ? Bits : 512; if (errno == ERANGE) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-bits' requires a number: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-bits' requires a number: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else if (CheckOption(opt,"clockskew",ival)) { --argc; ++argv; if (argc >= 0 && (*argv && *(argv)[0] != '-')) { ClockSkew = strtol(*argv, 0, 10); if (ClockSkew < -1 || errno == ERANGE) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-clockskew' requires a number >= -1: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Option '-clockskew' requires a number >= -1: ignoring +"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); argc++; argv--; } } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Ignoring unrecognized option: "<<*argv); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } } else { // // Mode keyword opt = *argv; if (CheckOption(opt,"init",ival)) { Mode = kM_init; } else if (CheckOption(opt,"info",ival)) { Mode = kM_info; } else if (CheckOption(opt,"destroy",ival)) { Mode = kM_destroy; } else if (CheckOption(opt,"help",ival)) { Mode = kM_help; } else { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Ignoring unrecognized keyword mode: "<<opt.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } } --argc; ++argv; } // // Default mode 'info' Mode = (Mode == 0) ? kM_info : Mode; // // If help mode, print menu and exit if (Mode == kM_help) { // Print main menu Menu(); return 1; } // // we may need later struct passwd *pw = 0; XrdSysPwd thePwd; // // Check proxy file if (PXcert.length() <= 0) { // Use defaults if (!pw && !(pw = thePwd.Get(getuid()))) { // Cannot get info about current user PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot get info about current user - exit "); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } // Build proxy file name PXcert = DefPXcert + (int)(pw->pw_uid); } // // Expand Path XrdSutExpand(PXcert); // Get info struct stat st; if (stat(PXcert.c_str(),&st) != 0) { if (errno != ENOENT) { // Path exists but we cannot access it - exit PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot access requested proxy file: "<<PXcert.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } else { if (Mode != kM_init) { // Path exists but we cannot access it - exit if (!Exists) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ proxy file: "<<PXcert.c_str()<<" not found"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } return 1; } } } // // The following applies in 'init' mode only if (Mode == kM_init) { // // Check certificate file if (EEcert.length()) { // // Expand Path XrdSutExpand(EEcert); // Get info if (stat(EEcert.c_str(),&st) != 0) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot access certificate file: "<<EEcert.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } } else { // Use defaults if (!pw && !(pw = thePwd.Get(getuid()))) { // Cannot get info about current user PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot get info about current user - exit "); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } EEcert = DefEEcert; EEcert.insert(XrdSutHome(), 0); if (stat(EEcert.c_str(),&st) != 0) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot access certificate file: "<<EEcert.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } } // // Check key file if (EEkey.length()) { // // Expand Path XrdSutExpand(EEkey); // Get info if (stat(EEkey.c_str(),&st) != 0) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot access private key file: "<<EEkey.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } } else { // Use defaults if (!pw && !(pw = thePwd.Get(getuid()))) { // Cannot get info about current user PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot get info about current user - exit "); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } EEkey = DefEEkey; EEkey.insert(XrdSutHome(), 0); if (stat(EEkey.c_str(),&st) != 0) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Cannot access private key file: "<<EEkey.c_str()); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } } // Check permissions if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || (st.st_mode & (S_IWGRP | S_IWOTH)) != 0 || (st.st_mode & (S_IRGRP | S_IROTH)) != 0) { PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); PRT("+ Wrong permissions for file: "<<EEkey.c_str()<< " (should be 0600)"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return 1; } } return 0; } void Menu() { // Print the menu PRT(" "); PRT(" xrdgsiproxy: application to manage GSI proxies "); PRT(" "); PRT(" Syntax:"); PRT(" "); PRT(" xrdgsiproxy [-h] [<mode>] [options] "); PRT(" "); PRT(" "); PRT(" -h display this menu"); PRT(" "); PRT(" mode (info, init, destroy) [info]"); PRT(" "); PRT(" info: display content of existing proxy file"); PRT(" "); PRT(" init: create proxy certificate and related proxy file"); PRT(" "); PRT(" destroy: delete existing proxy file"); PRT(" "); PRT(" options:"); PRT(" "); PRT(" -debug Print more information while running this" " query (use if something goes wrong) "); PRT(" "); PRT(" -f,-file,-out <file> Non-standard location of proxy file"); PRT(" "); PRT(" init mode only:"); PRT(" "); PRT(" -certdir <dir> Non-standard location of directory" " with information about known CAs"); PRT(" -cert <file> Non-standard location of certificate" " for which proxies are wanted"); PRT(" -key <file> Non-standard location of the private" " key to be used to sign the proxy"); PRT(" -bits <bits> strength in bits of the key [512]"); PRT(" -valid <hh:mm> Time validity of the proxy certificate [12:00]"); PRT(" -path-length <len> max number of descendent levels below" " this proxy [0] "); PRT(" -e,-exists [options] returns 0 if valid proxy exists, 1 otherwise;"); PRT(" valid options: '-valid <hh:mm>', -bits <bits>"); PRT(" -clockskew <secs> max clock-skewness allowed when checking time validity [30 secs]"); PRT(" "); } bool CheckOption(XrdOucString opt, const char *ref, int &ival) { // Check opt against ref // Return 1 if ok, 0 if not // Fills ival = 1 if match is exact // ival = 0 if match is exact with no<ref> // ival = -1 in the other cases bool rc = 0; int lref = (ref) ? strlen(ref) : 0; if (!lref) return rc; XrdOucString noref = ref; noref.insert("no",0); ival = -1; if (opt == ref) { ival = 1; rc = 1; } else if (opt == noref) { ival = 0; rc = 1; } return rc; } void Display(XrdCryptoX509 *xp) { // display content of proxy certificate PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); if (!xp) { PRT(" Empty certificate! "); return; } // File PRT("file : "<<PXcert); // Issuer PRT("issuer : "<<xp->Issuer()); // Subject PRT("subject : "<<xp->Subject()); // Path length field int pathlen = 0; XrdSslgsiProxyCertInfo(xp->GetExtension(gsiProxyCertInfo_OID), pathlen); PRT("path length : "<<pathlen); // Key strength PRT("bits : "<<xp->BitStrength()); // Time left int now = int(time(0)) - XrdCryptoTZCorr(); int tl = xp->NotAfter() - now; int hh = (tl >= 3600) ? (tl/3600) : 0; tl -= (hh*3600); int mm = (tl >= 60) ? (tl/60) : 0; tl -= (mm*60); int ss = (tl >= 0) ? tl : 0; PRT("time left : "<<hh<<"h:"<<mm<<"m:"<<ss<<"s"); PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); // Show VOMS attributes, if any XrdOucString vatts, vat; if (XrdSslgsiX509GetVOMSAttr(xp, vatts) == 0) { int from = 0; while ((from = vatts.tokenize(vat, from, ',')) != -1) { if (vat.length() > 0) PRT("VOMS attributes: "<<vat); } PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } }
gpl-3.0
lpeter218065/yydota
sql/init.sql
62
ALTER USER postgres PASSWORD 'postgres'; CREATE DATABASE yasp;
gpl-3.0
thespeeder/lcdui
lcdui.cpp
5873
/* lcdui - A simple framework for embedded systems with an LCD/button interface Copyright (C) 2012 by Al Williams ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "lcdui.h" using namespace std; namespace liblcdui { // This kicks off a menu (or a submenu) // if level is zero (default) you can't go back from here void lcdui::go(unsigned int level) { // This mode is 0 for normal, 1 for changing a number, and // 2 for changing an enumeration int mode=0; while (1) { // skip anything disabled while (menu[current].mstring && !menu[current].enabled) current++; // if at the end back up if (menu[current].mstring==NULL) do { current--; } while (current && !menu[current].enabled); // now current is correct // get string #ifndef NOSTRING string work=menu[current].mstring; ostringstream digits; #else char work[81]; #endif // modify based on type switch (menu[current].menutype) { case T_INT: // add number #ifndef NOSTRING work+="\t"; digits<<*menu[current].value; work+=digits.str(); #else // assume 8 bit char work[0]='\t'; itoa(*menu[current].value,work+1,10); #endif break; case T_ENUM: // add enumerated value #ifndef NOSTRING work+="\t"; work+=+menu[current].enumeration[*menu[current].value].name; #else work[0]='\t'; strcpy(work+1,menu[current].enumeration[*menu[current].value].name); #endif break; } // write it output(work); // get input INTYPE in; do { in=getInput(); if (in==IN_NONE) idle(); // call idle if nothing } while (in==IN_NONE); // See what to do switch (in) { case IN_UP: // Up arrow if (mode==1) // if modifying # { if (((*menu[current].value)-menu[current].step)<menu[current].min) break; (*menu[current].value)-=menu[current].step; callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value); break; } if (mode==2) // if modifying an enum { if (*menu[current].value==0) break; (*menu[current].value)--; callback(menu[current].id,menu[current].menutype,EV_CHANGE, menu[current].value); break; } // none of the above, just navigating the menu if (current) current--; break; case IN_DN: // down arrow if (mode==1) // change number { if (((*menu[current].value)+menu[current].step)>menu[current].max) break; (*menu[current].value)+=menu[current].step; callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value); break; } if (mode==2) // change enum { (*menu[current].value)++; if (menu[current].enumeration[*menu[current].value].name==NULL) (*menu[current].value)--; callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value); break; } // none of the above, navigate the menu current++; break; // Select key either executes menu, // modifies int or enum // or finishes modification case IN_OK: if (mode) // changing a value so exit change { mode=0; // note we have no way to roll back with the current // scheme; changes are "hot" unless you override callback callback(menu[current].id,menu[current].menutype,EV_SAVE,menu[current].value); break; } // Do a submenu if (menu[current].menutype==T_MENU) { // remember where we are MENU *parent=menu; unsigned parentcur=current; // go to new menu menu=menu[current].submenu; current=0; callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value); go(level+1); // back, so restore current=parentcur; menu=parent; break; } // integer and not read only if (menu[current].menutype==T_INT && !menu[current].readonly) { callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value); mode=1; // start edit break; } // enum and not read only if (menu[current].menutype==T_ENUM && !menu[current].readonly) { callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value); mode=2; // start edit break; } // none of the above, so must be T_ACTION callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value); break; // back button gets out of a menu; case IN_BACK: if (mode) { mode=0; // stop editing callback(menu[current].id,menu[current].menutype,EV_CANCEL,menu[current].value); break; // don't leave submenu if editing } // note could save edited value and restore here // or edit a local copy and only save on ok if (level) return; // only return if nested break; } } } void lcdui::callback(int id, MENUTYPE mtype, EVTYPE event, int *value) { switch (mtype) { case T_ACTION: dispatch(id); break; // A custom override could get notified when anything changes here case T_INT: case T_ENUM: case T_MENU: break; } } }
gpl-3.0
nipunreddevil/bayespy
bayespy/inference/vmp/nodes/gaussian_wishart.py
10240
###################################################################### # Copyright (C) 2014 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ###################################################################### # This file is part of BayesPy. # # BayesPy 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. # # BayesPy 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 BayesPy. If not, see <http://www.gnu.org/licenses/>. ###################################################################### """ Module for the Gaussian-Wishart and similar distributions. """ import numpy as np from scipy import special from .expfamily import (ExponentialFamily, ExponentialFamilyDistribution, useconstructor) from .gaussian import GaussianMoments from .gamma import GammaMoments from .wishart import (WishartMoments, WishartPriorMoments) from .node import (Moments, ensureparents) from bayespy.utils import random from bayespy.utils import utils class GaussianGammaISOMoments(Moments): """ Class for the moments of Gaussian-gamma-ISO variables. """ def compute_fixed_moments(self, x, alpha): """ Compute the moments for a fixed value `x` is a mean vector. `alpha` is a precision scale """ x = np.asanyarray(x) alpha = np.asanyarray(alpha) u0 = np.einsum('...,...i->...i', alpha, x) u1 = np.einsum('...,...i,...j->...ij', alpha, x, x) u2 = np.copy(alpha) u3 = np.log(alpha) u = [u0, u1, u2, u3] return u def compute_dims_from_values(self, x, alpha): """ Return the shape of the moments for a fixed value. """ if np.ndim(x) < 1: raise ValueError("Mean must be a vector") D = np.shape(x)[-1] return ( (D,), (D,D), (), () ) class GaussianGammaARDMoments(Moments): """ Class for the moments of Gaussian-gamma-ARD variables. """ def compute_fixed_moments(self, x, alpha): """ Compute the moments for a fixed value `x` is a mean vector. `alpha` is a precision scale """ x = np.asanyarray(x) alpha = np.asanyarray(alpha) if np.ndim(x) < 1: raise ValueError("Mean must be a vector") if np.ndim(alpha) < 1: raise ValueError("ARD scales must be a vector") if np.shape(x)[-1] != np.shape(alpha)[-1]: raise ValueError("Mean and ARD scales have inconsistent shapes") u0 = np.einsum('...i,...i->...i', alpha, x) u1 = np.einsum('...k,...k,...k->...k', alpha, x, x) u2 = np.copy(alpha) u3 = np.log(alpha) u = [u0, u1, u2, u3] return u def compute_dims_from_values(self, x, alpha): """ Return the shape of the moments for a fixed value. """ if np.ndim(x) < 1: raise ValueError("Mean must be a vector") if np.ndim(alpha) < 1: raise ValueError("ARD scales must be a vector") D = np.shape(x)[-1] if np.shape(alpha)[-1] != D: raise ValueError("Mean and ARD scales have inconsistent shapes") return ( (D,), (D,), (D,), (D,) ) class GaussianWishartMoments(Moments): """ Class for the moments of Gaussian-Wishart variables. """ def compute_fixed_moments(self, x, Lambda): """ Compute the moments for a fixed value `x` is a vector. `Lambda` is a precision matrix """ x = np.asanyarray(x) Lambda = np.asanyarray(Lambda) u0 = np.einsum('...ik,...k->...i', Lambda, x) u1 = np.einsum('...i,...ij,...j->...', x, Lambda, x) u2 = np.copy(Lambda) u3 = linalg.logdet_cov(Lambda) return [u0, u1, u2, u3] def compute_dims_from_values(self, x, Lambda): """ Return the shape of the moments for a fixed value. """ if np.ndim(x) < 1: raise ValueError("Mean must be a vector") if np.ndim(Lambda) < 2: raise ValueError("Precision must be a matrix") D = np.shape(x)[-1] if np.shape(Lambda)[-2:] != (D,D): raise ValueError("Mean vector and precision matrix have " "inconsistent shapes") return ( (D,), (), (D,D), () ) class GaussianGammaISODistribution(ExponentialFamilyDistribution): """ Class for the VMP formulas of Gaussian-Gamma-ISO variables. """ def compute_message_to_parent(self, parent, index, u, u_mu_Lambda, u_a, u_b): """ Compute the message to a parent node. """ if index == 0: raise NotImplementedError() elif index == 1: raise NotImplementedError() elif index == 2: raise NotImplementedError() else: raise ValueError("Index out of bounds") def compute_phi_from_parents(self, u_mu_Lambda, u_a, u_b, mask=True): """ Compute the natural parameter vector given parent moments. """ raise NotImplementedError() def compute_moments_and_cgf(self, phi, mask=True): """ Compute the moments and :math:`g(\phi)`. """ raise NotImplementedError() return (u, g) def compute_cgf_from_parents(self, u_mu_Lambda, u_a, u_b): """ Compute :math:`\mathrm{E}_{q(p)}[g(p)]` """ raise NotImplementedError() return g def compute_fixed_moments_and_f(self, x, alpha, mask=True): """ Compute the moments and :math:`f(x)` for a fixed value. """ raise NotImplementedError() return (u, f) class GaussianWishartDistribution(ExponentialFamilyDistribution): """ Class for the VMP formulas of Gaussian-Wishart variables. """ def compute_message_to_parent(self, parent, index, u, u_mu, u_alpha, u_V, u_n): """ Compute the message to a parent node. """ if index == 0: raise NotImplementedError() elif index == 1: raise NotImplementedError() elif index == 2: raise NotImplementedError() elif index == 3: raise NotImplementedError() else: raise ValueError("Index out of bounds") def compute_phi_from_parents(self, u_mu, u_alpha, u_V, u_n, mask=True): """ Compute the natural parameter vector given parent moments. """ raise NotImplementedError() def compute_moments_and_cgf(self, phi, mask=True): """ Compute the moments and :math:`g(\phi)`. """ raise NotImplementedError() return (u, g) def compute_cgf_from_parents(self, u_mu, u_alpha, u_V, u_n): """ Compute :math:`\mathrm{E}_{q(p)}[g(p)]` """ raise NotImplementedError() return g def compute_fixed_moments_and_f(self, x, Lambda, mask=True): """ Compute the moments and :math:`f(x)` for a fixed value. """ raise NotImplementedError() return (u, f) class GaussianWishart(ExponentialFamily): """ Node for Gaussian-Wishart random variables. The prior: .. math:: p(x, \Lambda| \mu, \alpha, V, n) p(x|\Lambda, \mu, \alpha) = \mathcal(N)(x | \mu, \alpha^{-1} Lambda^{-1}) p(\Lambda|V, n) = \mathcal(W)(\Lambda | n, V) The posterior approximation :math:`q(x, \Lambda)` has the same Gaussian-Wishart form. """ _moments = GaussianWishartMoments() _parent_moments = (GaussianGammaMoments(), GammaMoments(), WishartMoments(), WishartPriorMoments()) _distribution = GaussianWishartDistribution() @classmethod @ensureparents def _constructor(cls, mu, alpha, V, n, plates_lambda=None, plates_x=None, **kwargs): """ Constructs distribution and moments objects. This method is called if useconstructor decorator is used for __init__. `mu` is the mean/location vector `alpha` is the scale `V` is the scale matrix `n` is the degrees of freedom """ D = mu.dims[0][0] # Check shapes if mu.dims != ( (D,), (D,D), (), () ): raise ValueError("Mean vector has wrong shape") if alpha.dims != ( (), () ): raise ValueError("Scale has wrong shape") if V.dims != ( (D,D), () ): raise ValueError("Precision matrix has wrong shape") if n.dims != ( (), () ): raise ValueError("Degrees of freedom has wrong shape") dims = ( (D,), (), (D,D), () ) return (dims, kwargs, cls._total_plates(kwargs.get('plates'), cls._distribution.plates_from_parent(0, mu.plates), cls._distribution.plates_from_parent(1, alpha.plates), cls._distribution.plates_from_parent(2, V.plates), cls._distribution.plates_from_parent(3, n.plates)), cls._distribution, cls._moments, cls._parent_moments) def random(self): """ Draw a random sample from the distribution. """ raise NotImplementedError() def show(self): """ Print the distribution using standard parameterization. """ raise NotImplementedError()
gpl-3.0
greeduomacro/xrunuo
Scripts/Distro/Items/Armor/Plate/DecorativePlateKabuto.cs
1204
using System; using Server.Items; namespace Server.Items { public class DecorativePlateKabuto : BaseArmor { public override int BasePhysicalResistance { get { return 6; } } public override int BaseFireResistance { get { return 2; } } public override int BaseColdResistance { get { return 2; } } public override int BasePoisonResistance { get { return 2; } } public override int BaseEnergyResistance { get { return 3; } } public override int InitMinHits { get { return 55; } } public override int InitMaxHits { get { return 75; } } public override int StrengthReq { get { return 70; } } public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Plate; } } [Constructable] public DecorativePlateKabuto() : base( 0x2778 ) { Weight = 6.0; } public DecorativePlateKabuto( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); } } }
gpl-3.0
quicky2000/soda
repository/soda_analyzer_dom_if/include/dom_analyzer_if.h
1303
/* This file is part of osm_diff_analyzer_dom_if, Interface definitions of DOM based Openstreetmap diff analyzers Copyright (C) 2012 Julien Thevenon ( julien_thevenon at yahoo.fr ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef _DOM_ANALYZER_IF_H_ #define _DOM_ANALYZER_IF_H_ #include "dom_analyzer_generic_if.h" #include "diff_analyzer_if.h" #include "dom_tree.h" namespace osm_diff_analyzer_dom_if { class dom_analyzer_if: public osm_diff_analyzer_if::diff_analyzer_if, public dom_analyzer_generic_if<XMLNode> { public: virtual void analyze(const XMLNode & p_tree)=0; inline virtual ~dom_analyzer_if(void){}; }; } #endif // _DOM_ANALYZER_IF_H_ //EOF
gpl-3.0
zlatebogdan/gnunet
src/include/gnunet_datacache_lib.h
4419
/* This file is part of GNUnet (C) 2006, 2009 Christian Grothoff (and other contributing authors) GNUnet 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, or (at your option) any later version. GNUnet 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 GNUnet; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * @file include/gnunet_datacache_lib.h * @brief datacache is a simple, transient hash table * of bounded size with content expiration. * In contrast to the sqstore there is * no prioritization, deletion or iteration. * All of the data is discarded when the peer shuts down! * @author Christian Grothoff */ #ifndef GNUNET_DATACACHE_LIB_H #define GNUNET_DATACACHE_LIB_H #include "gnunet_util_lib.h" #include "gnunet_block_lib.h" #ifdef __cplusplus extern "C" { #if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif /** * Handle to the cache. */ struct GNUNET_DATACACHE_Handle; /** * Create a data cache. * * @param cfg configuration to use * @param section section in the configuration that contains our options * @return handle to use to access the service */ struct GNUNET_DATACACHE_Handle * GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, const char *section); /** * Destroy a data cache (and free associated resources). * * @param h handle to the datastore */ void GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h); /** * An iterator over a set of items stored in the datacache. * * @param cls closure * @param key key for the content * @param size number of bytes in data * @param data content stored * @param type type of the content * @param exp when will the content expire? * @param path_info_len number of entries in 'path_info' * @param path_info a path through the network * @return GNUNET_OK to continue iterating, GNUNET_SYSERR to abort */ typedef int (*GNUNET_DATACACHE_Iterator) (void *cls, const struct GNUNET_HashCode *key, size_t size, const char *data, enum GNUNET_BLOCK_Type type, struct GNUNET_TIME_Absolute exp, unsigned int path_info_len, const struct GNUNET_PeerIdentity *path_info); /** * Store an item in the datacache. * * @param h handle to the datacache * @param key key to store data under * @param size number of bytes in data * @param data data to store * @param type type of the value * @param discard_time when to discard the value in any case * @param path_info_len number of entries in 'path_info' * @param path_info a path through the network * @return GNUNET_OK on success, GNUNET_SYSERR on error, GNUNET_NO if duplicate */ int GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h, const struct GNUNET_HashCode * key, size_t size, const char *data, enum GNUNET_BLOCK_Type type, struct GNUNET_TIME_Absolute discard_time, unsigned int path_info_len, const struct GNUNET_PeerIdentity *path_info); /** * Iterate over the results for a particular key * in the datacache. * * @param h handle to the datacache * @param key what to look up * @param type entries of which type are relevant? * @param iter maybe NULL (to just count) * @param iter_cls closure for iter * @return the number of results found */ unsigned int GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h, const struct GNUNET_HashCode * key, enum GNUNET_BLOCK_Type type, GNUNET_DATACACHE_Iterator iter, void *iter_cls); #if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus } #endif /* end of gnunet_datacache_lib.h */ #endif
gpl-3.0
woakes070048/crm-php
htdocs/langs/da_DK/contracts.lang.php
6072
<?php /* Copyright (C) 2012 Regis Houssin <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $contracts = array( 'CHARSET' => 'UTF-8', 'ContractsArea' => 'Kontrakter område', 'ListOfContracts' => 'Liste over kontrakter', 'LastContracts' => 'Seneste %s modificerede kontrakter', 'AllContracts' => 'Alle kontrakter', 'ContractCard' => 'Kontrakt-kortet', 'ContractStatus' => 'Kontrakt status', 'ContractStatusNotRunning' => 'Ikke kører', 'ContractStatusRunning' => 'Kørsel', 'ContractStatusDraft' => 'Udkast', 'ContractStatusValidated' => 'Valideret', 'ContractStatusClosed' => 'Lukket', 'ServiceStatusInitial' => 'Ikke kører', 'ServiceStatusRunning' => 'Kørsel', 'ServiceStatusNotLate' => 'Kører, ikke er udløbet', 'ServiceStatusNotLateShort' => 'Ikke er udløbet', 'ServiceStatusLate' => 'Kører, er udløbet', 'ServiceStatusLateShort' => 'Udløbet', 'ServiceStatusClosed' => 'Lukket', 'ServicesLegend' => 'Services legend', 'Contracts' => 'Kontrakter', 'Contract' => 'Kontrakt', 'NoContracts' => 'Nr. kontrakter', 'MenuServices' => 'Services', 'MenuInactiveServices' => 'Tjenester, der ikke er aktive', 'MenuRunningServices' => 'Kørsel tjenester', 'MenuExpiredServices' => 'Udløbet tjenester', 'MenuClosedServices' => 'Lukket tjenester', 'NewContract' => 'Ny kontrakt', 'AddContract' => 'Tilføj kontrakt', 'SearchAContract' => 'Søg en kontrakt', 'DeleteAContract' => 'Slet en kontrakt', 'CloseAContract' => 'Luk en kontrakt', 'ConfirmDeleteAContract' => 'Er du sikker på du vil slette denne kontrakt og alle dets tjenester?', 'ConfirmValidateContract' => 'Er du sikker på at du ønsker at validere denne kontrakt?', 'ConfirmCloseContract' => 'Dette vil lukke alle tjenester (aktiv eller ej). Er du sikker på du ønsker at lukke denne kontrakt?', 'ConfirmCloseService' => 'Er du sikker på du ønsker at lukke denne service med <b>dato %s?</b>', 'ValidateAContract' => 'Validere en kontrakt', 'ActivateService' => 'Aktivér service', 'ConfirmActivateService' => 'Er du sikker på du vil aktivere denne tjeneste med datoen <b>for %s?</b>', 'RefContract' => 'Contract reference', 'DateContract' => 'Kontrakt dato', 'DateServiceActivate' => 'Forkyndelsesdato aktivering', 'DateServiceUnactivate' => 'Forkyndelsesdato unactivation', 'DateServiceStart' => 'Dato for starten af service', 'DateServiceEnd' => 'Datoen for afslutningen af tjenesten', 'ShowContract' => 'Vis kontrakt', 'ListOfServices' => 'Liste over tjenesteydelser', 'ListOfInactiveServices' => 'Liste over ikke aktive tjenester', 'ListOfExpiredServices' => 'Liste over udløb aktive tjenester', 'ListOfClosedServices' => 'Liste over lukkede tjenester', 'ListOfRunningContractsLines' => 'Liste over kører kontrakt linjer', 'ListOfRunningServices' => 'Liste over kører tjenester', 'NotActivatedServices' => 'Ikke aktiverede tjenester (blandt valideret kontrakter)', 'BoardNotActivatedServices' => 'Tjenester for at aktivere blandt valideret kontrakter', 'LastContracts' => 'Seneste %s modificerede kontrakter', 'LastActivatedServices' => 'Seneste %s aktiveret tjenester', 'LastModifiedServices' => 'Seneste %s modificerede tjenester', 'EditServiceLine' => 'Rediger service line', 'ContractStartDate' => 'Startdato', 'ContractEndDate' => 'Slutdato', 'DateStartPlanned' => 'Planlagt startdato', 'DateStartPlannedShort' => 'Planlagt startdato', 'DateEndPlanned' => 'Planlagte slutdato', 'DateEndPlannedShort' => 'Planlagte slutdato', 'DateStartReal' => 'Real startdato', 'DateStartRealShort' => 'Real startdato', 'DateEndReal' => 'Real slutdato', 'DateEndRealShort' => 'Real slutdato', 'NbOfServices' => 'Nb af tjenesteydelser', 'CloseService' => 'Luk service', 'ServicesNomberShort' => '%s tjeneste (r)', 'RunningServices' => 'Kørsel tjenester', 'BoardRunningServices' => 'Udløbet kører tjenester', 'ServiceStatus' => 'Status for service', 'DraftContracts' => 'Drafts kontrakter', 'CloseRefusedBecauseOneServiceActive' => 'Kontrakten ikke kan lukkes, da der er mindst en åben tjeneste på det', 'CloseAllContracts' => 'Luk alle kontrakter', 'DeleteContractLine' => 'Slet en kontrakt linje', 'ConfirmDeleteContractLine' => 'Er du sikker på du vil slette denne kontrakt linje?', 'MoveToAnotherContract' => 'Flyt tjeneste i en anden kontrakt.', 'ConfirmMoveToAnotherContract' => 'Jeg choosed nyt mål kontrakt og bekræfte, jeg ønsker at flytte denne tjeneste i denne kontrakt.', 'ConfirmMoveToAnotherContractQuestion' => 'Vælg, hvor eksisterende kontrakt (af samme tredjemand), du ønsker at flytte denne service?', 'PaymentRenewContractId' => 'Forny kontrakten linje (antal %s)', 'ExpiredSince' => 'Udløbsdatoen', 'RelatedContracts' => 'Relaterede kontrakter', 'NoExpiredServices' => 'Ingen udløbne aktive tjenester', ////////// Types de contacts ////////// 'TypeContact_contrat_internal_SALESREPSIGN' => 'Salg repræsentant, der underskriver kontrakt', 'TypeContact_contrat_internal_SALESREPFOLL' => 'Salg repræsentant opfølgning kontrakt', 'TypeContact_contrat_external_BILLING' => 'Faktureringsindstillinger kunde kontakt', 'TypeContact_contrat_external_CUSTOMER' => 'Opfølgning kunde kontakt', 'TypeContact_contrat_external_SALESREPSIGN' => 'Undertegnelse kontrakt kunde kontakt', 'Error_CONTRACT_ADDON_NotDefined' => 'Konstant CONTRACT_ADDON ikke defineret' ); ?>
gpl-3.0
hofschroeer/gnuradio
cmake/Modules/FindGSL.cmake
4639
# Try to find gnu scientific library GSL # See # http://www.gnu.org/software/gsl/ and # http://gnuwin32.sourceforge.net/packages/gsl.htm # # Based on a script of Felix Woelk and Jan Woetzel # (www.mip.informatik.uni-kiel.de) # # It defines the following variables: # GSL_FOUND - system has GSL lib # GSL_INCLUDE_DIRS - where to find headers # GSL_LIBRARIES - full path to the libraries # GSL_LIBRARY_DIRS, the directory where the PLplot library is found. # CMAKE_GSL_CXX_FLAGS = Unix compiler flags for GSL, essentially "`gsl-config --cxxflags`" # GSL_LINK_DIRECTORIES = link directories, useful for rpath on Unix # GSL_EXE_LINKER_FLAGS = rpath on Unix INCLUDE(FindPkgConfig) PKG_CHECK_MODULES(GSL "gsl >= 1.10") IF(GSL_FOUND) set(GSL_LIBRARY_DIRS ${GSL_LIBDIR}) set(GSL_INCLUDE_DIRS ${GSL_INCLUDEDIR}) ELSE(GSL_FOUND) set( GSL_FOUND OFF ) set( GSL_CBLAS_FOUND OFF ) # Windows, but not for Cygwin and MSys where gsl-config is available if( WIN32 AND NOT CYGWIN AND NOT MSYS ) # look for headers find_path( GSL_INCLUDE_DIRS NAMES gsl/gsl_cdf.h gsl/gsl_randist.h ) if( GSL_INCLUDE_DIRS ) # look for gsl library find_library( GSL_LIBRARY NAMES gsl ) if( GSL_LIBRARY ) set( GSL_INCLUDE_DIRS ${GSL_INCLUDE_DIR} ) get_filename_component( GSL_LIBRARY_DIRS ${GSL_LIBRARY} PATH ) set( GSL_FOUND ON ) endif( GSL_LIBRARY ) # look for gsl cblas library find_library( GSL_CBLAS_LIBRARY NAMES gslcblas cblas ) if( GSL_CBLAS_LIBRARY ) set( GSL_CBLAS_FOUND ON ) endif( GSL_CBLAS_LIBRARY ) set( GSL_LIBRARIES ${GSL_LIBRARY} ${GSL_CBLAS_LIBRARY} ) set( GSL_LDFLAGS ${GSL_LIBRARIES} ) endif( GSL_INCLUDE_DIRS ) mark_as_advanced( GSL_INCLUDE_DIRS GSL_LIBRARIES GSL_CBLAS_LIBRARIES ) else( WIN32 AND NOT CYGWIN AND NOT MSYS ) if( UNIX OR MSYS ) find_program( GSL_CONFIG_EXECUTABLE gsl-config /usr/bin/ /usr/local/bin ) if( GSL_CONFIG_EXECUTABLE ) set( GSL_FOUND ON ) # run the gsl-config program to get cxxflags execute_process( COMMAND sh "${GSL_CONFIG_EXECUTABLE}" --cflags OUTPUT_VARIABLE GSL_CFLAGS RESULT_VARIABLE RET ERROR_QUIET ) if( RET EQUAL 0 ) string( STRIP "${GSL_CFLAGS}" GSL_CFLAGS ) separate_arguments( GSL_CFLAGS ) # parse definitions from cflags; drop -D* from CFLAGS string( REGEX MATCHALL "-D[^;]+" GSL_DEFINITIONS "${GSL_CFLAGS}" ) string( REGEX REPLACE "-D[^;]+;" "" GSL_CFLAGS "${GSL_CFLAGS}" ) # parse include dirs from cflags; drop -I prefix string( REGEX MATCHALL "-I[^;]+" GSL_INCLUDE_DIRS "${GSL_CFLAGS}" ) string( REPLACE "-I" "" GSL_INCLUDE_DIRS "${GSL_INCLUDE_DIRS}") string( REGEX REPLACE "-I[^;]+;" "" GSL_CFLAGS "${GSL_CFLAGS}") message("GSL_DEFINITIONS=${GSL_DEFINITIONS}") message("GSL_INCLUDE_DIRS=${GSL_INCLUDE_DIRS}") message("GSL_CFLAGS=${GSL_CFLAGS}") else( RET EQUAL 0 ) set( GSL_FOUND FALSE ) endif( RET EQUAL 0 ) # run the gsl-config program to get the libs execute_process( COMMAND sh "${GSL_CONFIG_EXECUTABLE}" --libs OUTPUT_VARIABLE GSL_LIBRARIES RESULT_VARIABLE RET ERROR_QUIET ) if( RET EQUAL 0 ) string(STRIP "${GSL_LIBRARIES}" GSL_LIBRARIES ) separate_arguments( GSL_LIBRARIES ) # extract linkdirs (-L) for rpath (i.e., LINK_DIRECTORIES) string( REGEX MATCHALL "-L[^;]+" GSL_LIBRARY_DIRS "${GSL_LIBRARIES}" ) string( REPLACE "-L" "" GSL_LIBRARY_DIRS "${GSL_LIBRARY_DIRS}" ) else( RET EQUAL 0 ) set( GSL_FOUND FALSE ) endif( RET EQUAL 0 ) MARK_AS_ADVANCED( GSL_CFLAGS ) message( STATUS "Using GSL from ${GSL_PREFIX}" ) else( GSL_CONFIG_EXECUTABLE ) message( STATUS "FindGSL: gsl-config not found.") endif( GSL_CONFIG_EXECUTABLE ) endif( UNIX OR MSYS ) endif( WIN32 AND NOT CYGWIN AND NOT MSYS ) if( GSL_FOUND ) if( NOT GSL_FIND_QUIETLY ) message( STATUS "FindGSL: Found both GSL headers and library" ) endif( NOT GSL_FIND_QUIETLY ) else( GSL_FOUND ) if( GSL_FIND_REQUIRED ) message( FATAL_ERROR "FindGSL: Could not find GSL headers or library" ) endif( GSL_FIND_REQUIRED ) endif( GSL_FOUND ) #needed for gsl windows port but safe to always define LIST(APPEND GSL_DEFINITIONS "-DGSL_DLL") ENDIF(GSL_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(GSL DEFAULT_MSG GSL_LIBRARIES GSL_INCLUDE_DIRS GSL_LIBRARY_DIRS)
gpl-3.0
cctsao1008/deviation
src/gui/128x64x1/_textsel.c
1979
/* This project 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. Deviation 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 Deviation. If not, see <http://www.gnu.org/licenses/>. */ #define KEY_ADJUST_Y 1 /* ensure cooridnate is within button */ #define KEY_ADJUST_X 1 void _DrawTextSelectHelper(struct guiTextSelect *select, const char *str) { struct guiBox *box = &select->header.box; // plate text select for devo 10, copy most behavior from label.c GUI_DrawBackground(box->x, box->y, box->width, box->height); u8 arrow_width = ARROW_WIDTH - 1; if (select->enable & 0x01) { u16 y = box->y + box->height / 2; // Bug fix: since the logic view is introduce, a coordinate could be greater than 10000 u16 x1 = box->x + arrow_width -1; LCD_DrawLine(box->x, y, x1, y - 2, 0xffff); LCD_DrawLine(box->x, y, x1, y + 2, 0xffff); //"<" x1 = box->x + box->width - arrow_width; u16 x2 = box->x + box->width -1; LCD_DrawLine(x1, y - 2, x2, y, 0xffff); LCD_DrawLine(x1, y + 2, x2, y, 0xffff); //">" } else if (select->enable == 2) { // ENBALBE == 2 means the textsel can be pressed but not be selected select->desc.style = LABEL_BOX; } else { if (!select->enable) // avoid drawing button box when it is disable select->desc.style = LABEL_CENTER; } GUI_DrawLabelHelper(box->x + arrow_width , box->y, box->width - 2 * arrow_width , box->height, str, &select->desc, (guiObject_t *)select == objSELECTED); }
gpl-3.0
sailfish-sdk/sailfish-qtcreator
src/libs/clangsupport/dynamicastmatcherdiagnosticmessagecontainer.h
3410
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #pragma once #include "dynamicmatcherdiagnostics.h" #include "sourcerangecontainerv2.h" #include <utils/smallstringio.h> namespace ClangBackEnd { class DynamicASTMatcherDiagnosticMessageContainer { public: DynamicASTMatcherDiagnosticMessageContainer() = default; DynamicASTMatcherDiagnosticMessageContainer(V2::SourceRangeContainer &&sourceRange, ClangQueryDiagnosticErrorType errorType, Utils::SmallStringVector &&arguments) : sourceRange(sourceRange), errorType(errorType), arguments(std::move(arguments)) { } CLANGSUPPORT_EXPORT Utils::SmallString errorTypeText() const; friend QDataStream &operator<<(QDataStream &out, const DynamicASTMatcherDiagnosticMessageContainer &container) { out << container.sourceRange; out << quint32(container.errorType); out << container.arguments; return out; } friend QDataStream &operator>>(QDataStream &in, DynamicASTMatcherDiagnosticMessageContainer &container) { quint32 errorType; in >> container.sourceRange; in >> errorType; in >> container.arguments; container.errorType = static_cast<ClangQueryDiagnosticErrorType>(errorType); return in; } friend bool operator==(const DynamicASTMatcherDiagnosticMessageContainer &first, const DynamicASTMatcherDiagnosticMessageContainer &second) { return first.errorType == second.errorType && first.sourceRange == second.sourceRange && first.arguments == second.arguments; } DynamicASTMatcherDiagnosticMessageContainer clone() const { return *this; } public: V2::SourceRangeContainer sourceRange; ClangQueryDiagnosticErrorType errorType = ClangQueryDiagnosticErrorType::None; Utils::SmallStringVector arguments; }; using DynamicASTMatcherDiagnosticMessageContainers = std::vector<DynamicASTMatcherDiagnosticMessageContainer>; CLANGSUPPORT_EXPORT QDebug operator<<(QDebug debug, const DynamicASTMatcherDiagnosticMessageContainer &container); } // namespace ClangBackEnd
gpl-3.0
jqs7/telegram-chinese-groups
vendor/github.com/jqs7/bb/message.go
1264
package bb import "github.com/Syfaro/telegram-bot-api" type message struct { Err error bot *tgbotapi.BotAPI config tgbotapi.MessageConfig Ret tgbotapi.Message } func (b *Base) NewMessage(chatID int, text string) *message { return &message{ bot: b.Bot, config: tgbotapi.NewMessage(chatID, text), } } func (m *message) DisableWebPagePreview() *message { m.config.DisableWebPagePreview = true return m } func (m *message) MarkdownMode() *message { m.config.ParseMode = tgbotapi.ModeMarkdown return m } func (m *message) ReplyToMessageID(ID int) *message { m.config.ReplyToMessageID = ID return m } func (m *message) ReplyMarkup(markup interface{}) *message { m.config.ReplyMarkup = markup return m } func (m *message) Send() *message { msg, err := m.bot.SendMessage(m.config) m.Ret = msg m.Err = err return m } type forward struct { Err error bot *tgbotapi.BotAPI config tgbotapi.ForwardConfig Ret tgbotapi.Message } func (b *Base) NewForward(chatID, fromChatID, messageID int) *forward { return &forward{ bot: b.Bot, config: tgbotapi.NewForward(chatID, fromChatID, messageID), } } func (f *forward) Send() *forward { msg, err := f.bot.ForwardMessage(f.config) f.Ret = msg f.Err = err return f }
gpl-3.0
jds2001/ocp-checkbox
checkbox/lib/safe.py
2778
# # This file is part of Checkbox. # # Copyright 2008 Canonical Ltd. # # Checkbox 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. # # Checkbox 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 Checkbox. If not, see <http://www.gnu.org/licenses/>. # import os import hashlib import shutil from stat import ST_MODE, S_IMODE, S_ISFIFO def safe_change_mode(path, mode): if not os.path.exists(path): raise Exception("Path does not exist: %s" % path) old_mode = os.stat(path)[ST_MODE] if mode != S_IMODE(old_mode): os.chmod(path, mode) def safe_make_directory(path, mode=0o755): if os.path.exists(path): if not os.path.isdir(path): raise Exception("Path is not a directory: %s" % path) else: os.makedirs(path, mode) def safe_make_fifo(path, mode=0o666): if os.path.exists(path): mode = os.stat(path)[ST_MODE] if not S_ISFIFO(mode): raise Exception("Path is not a FIFO: %s" % path) else: os.mkfifo(path, mode) def safe_remove_directory(path): if os.path.exists(path): if not os.path.isdir(path): raise Exception("Path is not a directory: %s" % path) shutil.rmtree(path) def safe_remove_file(path): if os.path.exists(path): if not os.path.isfile(path): raise Exception("Path is not a file: %s" % path) os.remove(path) def safe_rename(old, new): if old != new: if not os.path.exists(old): raise Exception("Old path does not exist: %s" % old) if os.path.exists(new): raise Exception("New path exists already: %s" % new) os.rename(old, new) class safe_md5sum: def __init__(self): self.digest = hashlib.md5() self.hexdigest = self.digest.hexdigest def update(self, string): self.digest.update(string.encode("utf-8")) def safe_md5sum_file(name): md5sum = None if os.path.exists(name): file = open(name) digest = safe_md5sum() while 1: buf = file.read(4096) if buf == "": break digest.update(buf) file.close() md5sum = digest.hexdigest() return md5sum def safe_close(file, safe=True): if safe: file.flush() os.fsync(file.fileno()) file.close()
gpl-3.0
TimKaechele/Working-Class
lib/working_class.rb
680
require 'working_class/version' require 'working_class/parser' require 'working_class/task' require 'working_class/tasklist' # WorkingClass Module # module WorkingClass # Loads the file from the path and returns a Tasklist # # @param path [String] the filepath # @return [WorkingClass::Tasklist] the parsed Tasklist # def self.load_file(path) string = File.open(path, 'r').read() self.load(string) end # Parses the given string and returns a Tasklist # # @param string [String] the WorkingClass tasklist syntax string # @return [WorkingClass::Tasklist] the parsed Tasklist # def self.load(string) Parser.new(string).to_tasklist end end
gpl-3.0
clevernet/CleverNIM
saiku-ui/js/ga.js
1366
/* * Copyright 2012 OSBI Ltd * * 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. */ var account = 'UA-16172251-17'; if (window.location.hostname && window.location.hostname == "dev.analytical-labs.com" ) { account = 'UA-16172251-12'; } else if (window.location.hostname && window.location.hostname == "demo.analytical-labs.com" ) { account = 'UA-16172251-5'; } var _gaq = _gaq || []; _gaq.push(['_setAccount', account]); _gaq.push(['_setAllowLinker', true]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
gpl-3.0
TomasVaskevicius/bouncy-particle-sampler
third_party/stan_math/stan/math/prim/scal/prob/student_t_rng.hpp
1700
#ifndef STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP #define STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP #include <boost/random/student_t_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/fun/lbeta.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/meta/length.hpp> #include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp> #include <stan/math/prim/scal/fun/inc_beta.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/VectorBuilder.hpp> namespace stan { namespace math { template <class RNG> inline double student_t_rng(double nu, double mu, double sigma, RNG& rng) { using boost::variate_generator; using boost::random::student_t_distribution; static const char* function("student_t_rng"); check_positive_finite(function, "Degrees of freedom parameter", nu); check_finite(function, "Location parameter", mu); check_positive_finite(function, "Scale parameter", sigma); variate_generator<RNG&, student_t_distribution<> > rng_unit_student_t(rng, student_t_distribution<>(nu)); return mu + sigma * rng_unit_student_t(); } } } #endif
gpl-3.0
shaneis/dbatools
functions/configuration/Register-DbatoolsConfig.ps1
9846
function Register-DbatoolsConfig { <# .SYNOPSIS Registers an existing configuration object in registry. .DESCRIPTION Registers an existing configuration object in registry. This allows simple persisting of settings across powershell consoles. It also can be used to generate a registry template, which can then be used to create policies. .PARAMETER Config The configuration object to write to registry. Can be retrieved using Get-DbatoolsConfig. .PARAMETER FullName The full name of the setting to be written to registry. .PARAMETER Module The name of the module, whose settings should be written to registry. .PARAMETER Name Default: "*" Used in conjunction with the -Module parameter to restrict the number of configuration items written to registry. .PARAMETER Scope Default: UserDefault Who will be affected by this export how? Current user or all? Default setting or enforced? Legal values: UserDefault, UserMandatory, SystemDefault, SystemMandatory .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Get-DbatoolsConfig message.style.* | Register-DbatoolsConfig Retrieves all configuration items that that start with message.style. and registers them in registry for the current user. .EXAMPLE PS C:\> Register-DbatoolsConfig -FullName "message.consoleoutput.disable" -Scope SystemDefault Retrieves the configuration item "message.consoleoutput.disable" and registers it in registry as the default setting for all users on this machine. .EXAMPLE PS C:\> Register-DbatoolsConfig -Module Message -Scope SystemMandatory Retrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system. #> [CmdletBinding(DefaultParameterSetName = "Default")] Param ( [Parameter(ParameterSetName = "Default", ValueFromPipeline = $true)] [Sqlcollaborative.Dbatools.Configuration.Config[]] $Config, [Parameter(ParameterSetName = "Default", ValueFromPipeline = $true)] [string[]] $FullName, [Parameter(Mandatory = $true, ParameterSetName = "Name", Position = 0)] [string] $Module, [Parameter(ParameterSetName = "Name", Position = 1)] [string] $Name = "*", [Sqlcollaborative.Dbatools.Configuration.ConfigScope] $Scope = "UserDefault", [switch]$EnableException ) begin { if ($script:NoRegistry -and ($Scope -band 14)) { Stop-Function -Message "Cannot register configurations on non-windows machines to registry. Please specify a file-based scope" -Tag 'NotSupported' -Category NotImplemented return } # Linux and MAC default to local user store file if ($script:NoRegistry -and ($Scope -eq "UserDefault")) { $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileUserLocal } # Linux and MAC get redirection for SystemDefault to FileSystem if ($script:NoRegistry -and ($Scope -eq "SystemDefault")) { $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileSystem } $parSet = $PSCmdlet.ParameterSetName function Write-Config { [CmdletBinding()] Param ( [Sqlcollaborative.Dbatools.Configuration.Config] $Config, [Sqlcollaborative.Dbatools.Configuration.ConfigScope] $Scope, [bool] $EnableException, [string] $FunctionName = (Get-PSCallStack)[0].Command ) if (-not $Config -or ($Config.RegistryData -eq "<type not supported>")) { Stop-Function -Message "Invalid Input, cannot export $($Config.FullName), type not supported" -EnableException $EnableException -Category InvalidArgument -Tag "config", "fail" -Target $Config -FunctionName $FunctionName return } try { Write-Message -Level Verbose -Message "Registering $($Config.FullName) for $Scope" -Tag "Config" -Target $Config -FunctionName $FunctionName #region User Default if (1 -band $Scope) { Ensure-RegistryPath -Path $script:path_RegistryUserDefault -ErrorAction Stop Set-ItemProperty -Path $script:path_RegistryUserDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop } #endregion User Default #region User Mandatory if (2 -band $Scope) { Ensure-RegistryPath -Path $script:path_RegistryUserEnforced -ErrorAction Stop Set-ItemProperty -Path $script:path_RegistryUserEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop } #endregion User Mandatory #region System Default if (4 -band $Scope) { Ensure-RegistryPath -Path $script:path_RegistryMachineDefault -ErrorAction Stop Set-ItemProperty -Path $script:path_RegistryMachineDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop } #endregion System Default #region System Mandatory if (8 -band $Scope) { Ensure-RegistryPath -Path $script:path_RegistryMachineEnforced -ErrorAction Stop Set-ItemProperty -Path $script:path_RegistryMachineEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop } #endregion System Mandatory } catch { Stop-Function -Message "Failed to export $($Config.FullName), to scope $Scope" -EnableException $EnableException -Tag "config", "fail" -Target $Config -ErrorRecord $_ -FunctionName $FunctionName return } } function Ensure-RegistryPath { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")] [CmdletBinding()] Param ( [string] $Path ) if (-not (Test-Path $Path)) { $null = New-Item $Path -Force } } # For file based persistence $configurationItems = @() } process { if (Test-FunctionInterrupt) { return } #region Registry Based if ($Scope -band 15) { switch ($parSet) { "Default" { foreach ($item in $Config) { Write-Config -Config $item -Scope $Scope -EnableException $EnableException } foreach ($item in $FullName) { if ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLowerInvariant())) { Write-Config -Config ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLowerInvariant()]) -Scope $Scope -EnableException $EnableException } } } "Name" { foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name)) { Write-Config -Config $item -Scope $Scope -EnableException $EnableException } } } } #endregion Registry Based #region File Based else { switch ($parSet) { "Default" { foreach ($item in $Config) { if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item } } foreach ($item in $FullName) { if (($configurationItems.FullName -notcontains $item) -and ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLowerInvariant()))) { $configurationItems += [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLowerInvariant()] } } } "Name" { foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name)) { if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item } } } } } #endregion File Based } end { if (Test-FunctionInterrupt) { return } #region Finish File Based Persistence if ($Scope -band 16) { Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserLocal "psf_config.json") } if ($Scope -band 32) { Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserShared "psf_config.json") } if ($Scope -band 64) { Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileSystem "psf_config.json") } #endregion Finish File Based Persistence } }
gpl-3.0
mrphrazer/bjoern
python-bjoern/bjoern/all.py
2645
from py2neo import Graph from py2neo.ext.gremlin import Gremlin import os DEFAULT_GRAPHDB_URL = "http://localhost:7474/db/data/" DEFAULT_STEP_DIR = os.path.dirname(__file__) + '/bjoernsteps/' class BjoernSteps: def __init__(self): self._initJoernSteps() self.initCommandSent = False def setGraphDbURL(self, url): """ Sets the graph database URL. By default, http://localhost:7474/db/data/ is used.""" self.graphDbURL = url def addStepsDir(self, stepsDir): """Add an additional directory containing steps to be injected into the server""" self.stepsDirs.append(stepsDir) def connectToDatabase(self): """ Connects to the database server.""" self.graphDb = Graph(self.graphDbURL) self.gremlin = Gremlin(self.graphDb) def runGremlinQuery(self, query): """ Runs the specified gremlin query on the database. It is assumed that a connection to the database has been established. To allow the user-defined steps located in the joernsteps directory to be used in the query, these step definitions are prepended to the query.""" if not self.initCommandSent: self.gremlin.execute(self._createInitCommand()) self.initCommandSent = True return self.gremlin.execute(query) def runCypherQuery(self, cmd): """ Runs the specified cypher query on the graph database.""" return cypher.execute(self.graphDb, cmd) def getGraphDbURL(self): return self.graphDbURL """ Create chunks from a list of ids. This method is useful when you want to execute many independent traversals on a large set of start nodes. In that case, you can retrieve the set of start node ids first, then use 'chunks' to obtain disjoint subsets that can be passed to idListToNodes. """ def chunks(self, idList, chunkSize): for i in xrange(0, len(idList), chunkSize): yield idList[i:i+chunkSize] def _initJoernSteps(self): self.graphDbURL = DEFAULT_GRAPHDB_URL self.stepsDirs = [DEFAULT_STEP_DIR] def _createInitCommand(self): initCommand = "" for stepsDir in self.stepsDirs: for (root, dirs, files) in os.walk(stepsDir, followlinks=True): files.sort() for f in files: filename = os.path.join(root, f) if not filename.endswith('.groovy'): continue initCommand += file(filename).read() + "\n" return initCommand
gpl-3.0
will-bainbridge/OpenFOAM-dev
src/OpenFOAM/fields/pointPatchFields/derived/slip/slipPointPatchFields.C
1689
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2018 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 "slipPointPatchFields.H" #include "pointPatchFields.H" #include "addToRunTimeSelectionTable.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // makePointPatchFields(slip); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // ************************************************************************* //
gpl-3.0
osroca/gvnix
addon-web-mvc-geo/addon/src/main/java/org/gvnix/addon/geo/addon/GvNIXMapViewerMetadataProvider.java
10078
/* * gvNIX is an open source tool for rapid application development (RAD). * Copyright (C) 2010 Generalitat Valenciana * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gvnix.addon.geo.addon; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.gvnix.addon.geo.annotations.GvNIXMapViewer; import org.gvnix.support.WebProjectUtils; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; import org.springframework.roo.addon.propfiles.PropFileOperations; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue; import org.springframework.roo.classpath.details.annotations.ClassAttributeValue; import org.springframework.roo.classpath.itd.AbstractItdMetadataProvider; import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.SpringJavaType; import org.springframework.roo.project.LogicalPath; import org.springframework.roo.project.ProjectOperations; import org.springframework.roo.support.logging.HandlerUtils; /** * Provides {@link GvNIXMapViewerMetadata}. * * @author <a href="http://www.disid.com">DISID Corporation S.L.</a> made for <a * href="http://www.dgti.gva.es">General Directorate for Information * Technologies (DGTI)</a> * @since 1.4 */ @Component @Service public final class GvNIXMapViewerMetadataProvider extends AbstractItdMetadataProvider { private static final Logger LOGGER = HandlerUtils .getLogger(GvNIXMapViewerMetadataProvider.class); private ProjectOperations projectOperations; private PropFileOperations propFileOperations; private WebProjectUtils webProjectUtils; /** * Register itself into metadataDependencyRegister and add metadata trigger * * @param context the component context */ protected void activate(ComponentContext cContext) { context = cContext.getBundleContext(); getMetadataDependencyRegistry().registerDependency( PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); addMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName())); } /** * Unregister this provider * * @param context the component context */ protected void deactivate(ComponentContext context) { getMetadataDependencyRegistry().deregisterDependency( PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType()); removeMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName())); } /** * Return an instance of the Metadata offered by this add-on */ protected ItdTypeDetailsProvidingMetadataItem getMetadata( String metadataIdentificationString, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, String itdFilename) { JavaType javaType = GvNIXMapViewerMetadata .getJavaType(metadataIdentificationString); ClassOrInterfaceTypeDetails controller = getTypeLocationService() .getTypeDetails(javaType); // Getting @RequestMapping annotation AnnotationMetadata requestMappingAnnotation = controller .getAnnotation(SpringJavaType.REQUEST_MAPPING); // Getting @GvNIXMapViewer annotation AnnotationMetadata mapViewerAnnotation = controller .getAnnotation(new JavaType(GvNIXMapViewer.class.getName())); // Getting path value AnnotationAttributeValue<Object> value = requestMappingAnnotation .getAttribute("value"); String path = value.getValue().toString(); // Getting mapId String mapId = String.format("ps_%s_%s", javaType.getPackage() .getFullyQualifiedPackageName().replaceAll("[.]", "_"), new JavaSymbolName(path.replaceAll("/", "")) .getSymbolNameCapitalisedFirstLetter()); // Getting entityLayers List<JavaType> entitiesToVisualize = new ArrayList<JavaType>(); @SuppressWarnings({ "unchecked", "rawtypes" }) ArrayAttributeValue<ClassAttributeValue> mapViewerAttributes = (ArrayAttributeValue) mapViewerAnnotation .getAttribute("entityLayers"); if (mapViewerAttributes != null) { List<ClassAttributeValue> entityLayers = mapViewerAttributes .getValue(); for (ClassAttributeValue entity : entityLayers) { entitiesToVisualize.add(entity.getValue()); } } // Getting projection String projection = ""; AnnotationAttributeValue<Object> projectionAttr = mapViewerAnnotation .getAttribute("projection"); if (projectionAttr != null) { projection = projectionAttr.getValue().toString(); } return new GvNIXMapViewerMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, getProjectOperations(), getPropFileOperations(), getTypeLocationService(), getFileManager(), entitiesToVisualize, path, mapId, projection, getWebProjectUtils()); } /** * Define the unique ITD file name extension, here the resulting file name * will be **_ROO_GvNIXMapViewer.aj */ public String getItdUniquenessFilenameSuffix() { return "GvNIXMapViewer"; } protected String getGovernorPhysicalTypeIdentifier( String metadataIdentificationString) { JavaType javaType = GvNIXMapViewerMetadata .getJavaType(metadataIdentificationString); LogicalPath path = GvNIXMapViewerMetadata .getPath(metadataIdentificationString); return PhysicalTypeIdentifier.createIdentifier(javaType, path); } protected String createLocalIdentifier(JavaType javaType, LogicalPath path) { return GvNIXMapViewerMetadata.createIdentifier(javaType, path); } public String getProvidesType() { return GvNIXMapViewerMetadata.getMetadataIdentiferType(); } public ProjectOperations getProjectOperations() { if (projectOperations == null) { // Get all Services implement ProjectOperations interface try { ServiceReference<?>[] references = this.context .getAllServiceReferences( ProjectOperations.class.getName(), null); for (ServiceReference<?> ref : references) { return (ProjectOperations) this.context.getService(ref); } return null; } catch (InvalidSyntaxException e) { LOGGER.warning("Cannot load ProjectOperations on GvNIXWebEntityMapLayerMetadataProvider."); return null; } } else { return projectOperations; } } public PropFileOperations getPropFileOperations() { if (propFileOperations == null) { // Get all Services implement PropFileOperations interface try { ServiceReference<?>[] references = this.context .getAllServiceReferences( PropFileOperations.class.getName(), null); for (ServiceReference<?> ref : references) { return (PropFileOperations) this.context.getService(ref); } return null; } catch (InvalidSyntaxException e) { LOGGER.warning("Cannot load PropFileOperations on GvNIXWebEntityMapLayerMetadataProvider."); return null; } } else { return propFileOperations; } } public WebProjectUtils getWebProjectUtils() { if (webProjectUtils == null) { // Get all Services implement WebProjectUtils interface try { ServiceReference<?>[] references = this.context .getAllServiceReferences( WebProjectUtils.class.getName(), null); for (ServiceReference<?> ref : references) { webProjectUtils = (WebProjectUtils) this.context .getService(ref); return webProjectUtils; } return null; } catch (InvalidSyntaxException e) { LOGGER.warning("Cannot load WebProjectUtils on GvNIXWebEntityMapLayerMetadataProvider."); return null; } } else { return webProjectUtils; } } }
gpl-3.0
xlsuite/reach.network
player-socialweedia/app/js/player/dc_page.js
985
// Copyright � 2010 - May 2014 Rise Vision Incorporated. // Use of this software is governed by the GPLv3 license // (reproduced in the LICENSE file). function rvPlayerDCPage() { var pageHTML = ""; this.get = function (port, ports, dcStatus, onStr, offStr) { var res = pageHTML.replace("[PORT]", port); res = res.replace("[PORTS]", ports); res = res.replace("[Status]", dcStatus); res = res.replace("[onStr]", onStr); res = res.replace("[offStr]", offStr); return res; } this.init = function () { download(chrome.runtime.getURL("display_page.html")); } var download = function (fileUrl) { var xhr = new XMLHttpRequest(); xhr.responseType = "text"; //xhr.onerror = ???; xhr.onload = function (xhrProgressEvent) { pageHTML = xhrProgressEvent.target.responseText; } xhr.open('GET', fileUrl, true); //async=true xhr.send(); }; }
gpl-3.0
diogopainho/comp-ist
tests-pwn-daily-201504081911/auto-tests/K-03-74-N-ok.asm
353
extern readi extern readd extern printi extern printd extern prints extern println segment .text align 4 global f:function f: push ebp mov ebp, esp sub esp, 0 pop eax leave ret extern readi extern readd extern printi extern printd extern prints extern println segment .text align 4 global _main:function _main: push ebp mov ebp, esp sub esp, 4
gpl-3.0
jkkm/latrace
etc/latrace.d/headers/libio.h
646
/* /usr/include/libio.h UNCOMPLETE */ typedef void _IO_FILE; typedef size_t _IO_size_t; int __underflow(_IO_FILE *f); int __uflow(_IO_FILE *f); int __overflow(_IO_FILE *f, int a); int _IO_getc(_IO_FILE *fp); int _IO_putc(int c, _IO_FILE *fp); int _IO_feof(_IO_FILE *fp); int _IO_ferror(_IO_FILE *fp); int _IO_peekc_locked(_IO_FILE *fp); void _IO_flockfile(_IO_FILE *f); void _IO_funlockfile(_IO_FILE *f); int _IO_ftrylockfile(_IO_FILE *f); int _IO_vfscanf(_IO_FILE *f, char *s); int _IO_vfprintf(_IO_FILE *f, char *s); _IO_size_t _IO_padn(_IO_FILE *f, int b, _IO_size_t s); _IO_size_t _IO_sgetn(_IO_FILE *f, void *p, _IO_size_t s);
gpl-3.0
kbrebanov/ansible-modules-extras
network/a10/a10_service_group.py
13531
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to manage A10 Networks slb service-group objects (c) 2014, Mischa Peters <[email protected]>, Eric Chou <[email protected]> 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/>. """ DOCUMENTATION = ''' --- module: a10_service_group version_added: 1.8 short_description: Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups. description: - Manage SLB (Server Load Balancing) service-group objects on A10 Networks devices via aXAPIv2. author: "Eric Chou (@ericchou) 2016, Mischa Peters (@mischapeters) 2014" notes: - Requires A10 Networks aXAPI 2.1. - When a server doesn't exist and is added to the service-group the server will be created. extends_documentation_fragment: a10 options: partition: version_added: "2.3" description: - set active-partition required: false default: null service_group: description: - The SLB (Server Load Balancing) service-group name required: true default: null aliases: ['service', 'pool', 'group'] service_group_protocol: description: - The SLB service-group protocol of TCP or UDP. required: false default: tcp aliases: ['proto', 'protocol'] choices: ['tcp', 'udp'] service_group_method: description: - The SLB service-group load balancing method, such as round-robin or weighted-rr. required: false default: round-robin aliases: ['method'] choices: ['round-robin', 'weighted-rr', 'least-connection', 'weighted-least-connection', 'service-least-connection', 'service-weighted-least-connection', 'fastest-response', 'least-request', 'round-robin-strict', 'src-ip-only-hash', 'src-ip-hash'] servers: description: - A list of servers to add to the service group. Each list item should be a dictionary which specifies the C(server:) and C(port:), but can also optionally specify the C(status:). See the examples below for details. required: false default: null validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates. required: false default: 'yes' choices: ['yes', 'no'] ''' RETURN = ''' # ''' EXAMPLES = ''' # Create a new service-group - a10_service_group: host: a10.mydomain.com username: myadmin password: mypassword partition: mypartition service_group: sg-80-tcp servers: - server: foo1.mydomain.com port: 8080 - server: foo2.mydomain.com port: 8080 - server: foo3.mydomain.com port: 8080 - server: foo4.mydomain.com port: 8080 status: disabled ''' RETURN = ''' content: description: the full info regarding the slb_service_group returned: success type: string sample: "mynewservicegroup" ''' VALID_SERVICE_GROUP_FIELDS = ['name', 'protocol', 'lb_method'] VALID_SERVER_FIELDS = ['server', 'port', 'status'] def validate_servers(module, servers): for item in servers: for key in item: if key not in VALID_SERVER_FIELDS: module.fail_json(msg="invalid server field (%s), must be one of: %s" % (key, ','.join(VALID_SERVER_FIELDS))) # validate the server name is present if 'server' not in item: module.fail_json(msg="server definitions must define the server field") # validate the port number is present and an integer if 'port' in item: try: item['port'] = int(item['port']) except: module.fail_json(msg="server port definitions must be integers") else: module.fail_json(msg="server definitions must define the port field") # convert the status to the internal API integer value if 'status' in item: item['status'] = axapi_enabled_disabled(item['status']) else: item['status'] = 1 def main(): argument_spec = a10_argument_spec() argument_spec.update(url_argument_spec()) argument_spec.update( dict( state=dict(type='str', default='present', choices=['present', 'absent']), service_group=dict(type='str', aliases=['service', 'pool', 'group'], required=True), service_group_protocol=dict(type='str', default='tcp', aliases=['proto', 'protocol'], choices=['tcp', 'udp']), service_group_method=dict(type='str', default='round-robin', aliases=['method'], choices=['round-robin', 'weighted-rr', 'least-connection', 'weighted-least-connection', 'service-least-connection', 'service-weighted-least-connection', 'fastest-response', 'least-request', 'round-robin-strict', 'src-ip-only-hash', 'src-ip-hash']), servers=dict(type='list', aliases=['server', 'member'], default=[]), partition=dict(type='str', default=[]), ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False ) host = module.params['host'] username = module.params['username'] password = module.params['password'] partition = module.params['partition'] state = module.params['state'] write_config = module.params['write_config'] slb_service_group = module.params['service_group'] slb_service_group_proto = module.params['service_group_protocol'] slb_service_group_method = module.params['service_group_method'] slb_servers = module.params['servers'] if slb_service_group is None: module.fail_json(msg='service_group is required') axapi_base_url = 'https://' + host + '/services/rest/V2.1/?format=json' load_balancing_methods = {'round-robin': 0, 'weighted-rr': 1, 'least-connection': 2, 'weighted-least-connection': 3, 'service-least-connection': 4, 'service-weighted-least-connection': 5, 'fastest-response': 6, 'least-request': 7, 'round-robin-strict': 8, 'src-ip-only-hash': 14, 'src-ip-hash': 15} if not slb_service_group_proto or slb_service_group_proto.lower() == 'tcp': protocol = 2 else: protocol = 3 # validate the server data list structure validate_servers(module, slb_servers) json_post = { 'service_group': { 'name': slb_service_group, 'protocol': protocol, 'lb_method': load_balancing_methods[slb_service_group_method], } } # first we authenticate to get a session id session_url = axapi_authenticate(module, axapi_base_url, username, password) # then we select the active-partition slb_server_partition = axapi_call(module, session_url + '&method=system.partition.active', json.dumps({'name': partition})) # then we check to see if the specified group exists slb_result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group})) slb_service_group_exist = not axapi_failure(slb_result) changed = False if state == 'present': # before creating/updating we need to validate that servers # defined in the servers list exist to prevent errors checked_servers = [] for server in slb_servers: result = axapi_call(module, session_url + '&method=slb.server.search', json.dumps({'name': server['server']})) if axapi_failure(result): module.fail_json(msg="the server %s specified in the servers list does not exist" % server['server']) checked_servers.append(server['server']) if not slb_service_group_exist: result = axapi_call(module, session_url + '&method=slb.service_group.create', json.dumps(json_post)) if axapi_failure(result): module.fail_json(msg=result['response']['err']['msg']) changed = True else: # check to see if the service group definition without the # server members is different, and update that individually # if it needs it do_update = False for field in VALID_SERVICE_GROUP_FIELDS: if json_post['service_group'][field] != slb_result['service_group'][field]: do_update = True break if do_update: result = axapi_call(module, session_url + '&method=slb.service_group.update', json.dumps(json_post)) if axapi_failure(result): module.fail_json(msg=result['response']['err']['msg']) changed = True # next we pull the defined list of servers out of the returned # results to make it a bit easier to iterate over defined_servers = slb_result.get('service_group', {}).get('member_list', []) # next we add/update new member servers from the user-specified # list if they're different or not on the target device for server in slb_servers: found = False different = False for def_server in defined_servers: if server['server'] == def_server['server']: found = True for valid_field in VALID_SERVER_FIELDS: if server[valid_field] != def_server[valid_field]: different = True break if found or different: break # add or update as required server_data = { "name": slb_service_group, "member": server, } if not found: result = axapi_call(module, session_url + '&method=slb.service_group.member.create', json.dumps(server_data)) changed = True elif different: result = axapi_call(module, session_url + '&method=slb.service_group.member.update', json.dumps(server_data)) changed = True # finally, remove any servers that are on the target # device but were not specified in the list given for server in defined_servers: found = False for slb_server in slb_servers: if server['server'] == slb_server['server']: found = True break # remove if not found server_data = { "name": slb_service_group, "member": server, } if not found: result = axapi_call(module, session_url + '&method=slb.service_group.member.delete', json.dumps(server_data)) changed = True # if we changed things, get the full info regarding # the service group for the return data below if changed: result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group})) else: result = slb_result elif state == 'absent': if slb_service_group_exist: result = axapi_call(module, session_url + '&method=slb.service_group.delete', json.dumps({'name': slb_service_group})) changed = True else: result = dict(msg="the service group was not present") # if the config has changed, save the config unless otherwise requested if changed and write_config: write_result = axapi_call(module, session_url + '&method=system.action.write_memory') if axapi_failure(write_result): module.fail_json(msg="failed to save the configuration: %s" % write_result['response']['err']['msg']) # log out of the session nicely and exit axapi_call(module, session_url + '&method=session.close') module.exit_json(changed=changed, content=result) # standard ansible module imports import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import url_argument_spec from ansible.module_utils.a10 import axapi_call, a10_argument_spec, axapi_authenticate, axapi_failure, axapi_enabled_disabled if __name__ == '__main__': main()
gpl-3.0
motizuki/supplejack_manager
spec/helpers/collection_statistics_helper_spec.rb
566
# The majority of The Supplejack Manager code is Crown copyright (C) 2014, New Zealand Government, # and is licensed under the GNU General Public License, version 3. Some components are # third party components that are licensed under the MIT license or otherwise publicly available. # See https://github.com/DigitalNZ/supplejack_manager for details. # # Supplejack was created by DigitalNZ at the National Library of NZ and the Department of Internal Affairs. # http://digitalnz.org/supplejack require "spec_helper" describe CollectionStatisticsHelper do end
gpl-3.0
241180/Oryx
oryx-server-ws-gen/src/main/java/copied/com/oryx/remote/webservice/element/_enum/XmlEnumContact.java
1467
package com.oryx.remote.webservice.element._enum; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour XmlEnumContact. * <p> * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * <p> * <pre> * &lt;simpleType name="XmlEnumContact"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Phone"/> * &lt;enumeration value="Mobile"/> * &lt;enumeration value="Fax"/> * &lt;enumeration value="Web"/> * &lt;enumeration value="Email"/> * &lt;/restriction> * &lt;/simpleType> * </pre> */ @XmlType(name = "XmlEnumContact", namespace = "http://enum.element.webservice.remote.oryx.com") @XmlEnum public enum XmlEnumContact { @XmlEnumValue("Phone") PHONE("Phone"), @XmlEnumValue("Mobile") MOBILE("Mobile"), @XmlEnumValue("Fax") FAX("Fax"), @XmlEnumValue("Web") WEB("Web"), @XmlEnumValue("Email") EMAIL("Email"); private final String value; XmlEnumContact(String v) { value = v; } public static XmlEnumContact fromValue(String v) { for (XmlEnumContact c : XmlEnumContact.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } public String value() { return value; } }
gpl-3.0
fenixon/tiponpython
views/ingresarObservaciones.py
5555
# -*- coding: utf-8 -*- """ tiponpython Simulacion de ensayos de acuiferos Copyright 2012 Andres Pias This file is part of tiponpython. tiponpython 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 any later version. tiponpython 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 tiponpython. If not, see http://www.gnu.org/licenses/gpl.txt. """ # Form implementation generated from reading ui file 'ingresarCaudal.ui' # # Created: Wed Dec 14 21:03:09 2011 # by: PyQt4 UI code generator 4.8.5 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui import observacion import observacionesensayo import sys try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Dialog(QtGui.QDialog): def setupUi(self, Dialog, cont): global ContEnsayo ContEnsayo=cont self.observaciones=[] Dialog.setObjectName(_fromUtf8("ingresarobservacionesensayo")) Dialog.resize(375, 214) Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Ingresar Observaciones Ensayo", None, QtGui.QApplication.UnicodeUTF8)) self.txttiempo = QtGui.QTextEdit(Dialog) self.txttiempo.setGeometry(QtCore.QRect(170, 40, 101, 31)) self.txttiempo.setObjectName(_fromUtf8("txttiempo")) self.label = QtGui.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(100, 50, 46, 21)) self.label.setText(QtGui.QApplication.translate("Dialog", "Tiempo", None, QtGui.QApplication.UnicodeUTF8)) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(100, 100, 46, 13)) self.label_2.setText(QtGui.QApplication.translate("Dialog", "Nivel", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setObjectName(_fromUtf8("label_2")) self.txtcaudal = QtGui.QTextEdit(Dialog) self.txtcaudal.setGeometry(QtCore.QRect(170, 90, 101, 31)) self.txtcaudal.setObjectName(_fromUtf8("txtcaudal")) self.btnagregar = QtGui.QPushButton(Dialog) self.btnagregar.setGeometry(QtCore.QRect(100, 150, 71, 23)) self.btnagregar.setText(QtGui.QApplication.translate("Dialog", "Agregar", None, QtGui.QApplication.UnicodeUTF8)) self.btnagregar.setObjectName(_fromUtf8("btnagregar")) self.btnfinalizar = QtGui.QPushButton(Dialog) self.btnfinalizar.setGeometry(QtCore.QRect(200, 150, 71, 23)) self.btnfinalizar.setText(QtGui.QApplication.translate("Dialog", "Finalizar", None, QtGui.QApplication.UnicodeUTF8)) self.btnfinalizar.setObjectName(_fromUtf8("btnfinalizar")) self.dialogo=Dialog self.retranslateUi(Dialog) QtCore.QObject.connect(self.btnagregar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.agregar) QtCore.QObject.connect(self.btnfinalizar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.finalizar) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): pass def agregar(self): global ContEnsayo control=True t=float(self.txttiempo.toPlainText()) print "tiempo: "+str(t) ## Se verifica que vengas los datos con sus tiempos ordenados de manera creciente sino salta control=ContEnsayo.verificarFormato(self.observaciones, t) if (control==False): reply = QtGui.QMessageBox.critical(self, "Error", "Los datos de bombeo no fueron agregaos. Debe ingresar un valor para el tiempo mayor a los ingresados anteriormente.") else: n=float(self.txtcaudal.toPlainText()) print "caudal: "+str(n) o=observacion.observacion(t,n) self.observaciones.append(o) reply = QtGui.QMessageBox.information(None, "Información", "Se agrego la nueva observacion del ensayo. Presione finalizar para guardar las observaciones") self.txttiempo.setText('') self.txtcaudal.setText('') def finalizar(self): global ContEnsayo ####Pedir un nombre para el ensayo nombre, ok=QtGui.QInputDialog.getText(self,"Finalzar registro ", "Nombre: ", QtGui.QLineEdit.Normal) ## Se manda al controlador las observaciones y se retorna el id de las observaciones obse=ContEnsayo.agregarObservacion(self.observaciones, nombre) reply = QtGui.QMessageBox.information(self, "Información", "Se ha creado un nuevo conjunto de observaciones en el sistema. El id es: "+ str(obse.id)) if reply == QtGui.QMessageBox.Ok: print "OK" self.dialogo.close() else: print "Escape" if __name__ == "__main__": app = QtGui.QApplication(sys.argv) frmImpProyecto = QtGui.QWidget() ui = Ui_Dialog() ui.setupUi(frmImpProyecto) frmImpProyecto.show() sys.exit(app.exec_())
gpl-3.0
py-in-the-sky/ud859-python-rmw
static/index.html
1176
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Hello World Endpoints</title> <script src="/static/hello.js"></script> <!-- Load the Google APIs Javascript client library --> <!-- Then call the init function, which is defined in hello.js --> <script src="https://apis.google.com/js/client.js?onload=init"></script> </head> <body> <H1>My First Endpoints App</H1> <P><input id="input_greet_generically" type="button" value="please wait" onclick="will_be_set_after_endpoints_apis_loaded"></P> <P>What is your name?<input value ="Zebra" id="name_field"> <input id="input_greet_by_name" type="button" value="please wait" onclick="will_be_set_after_endpoints_apis_loaded"></P> <P>What time of day is it? <select id="period_select"> <option value="Day" selected>any time</option> <option value="Morning">Morning</option> <option value="Afternoon">Afternoon</option> <option value="Evening">Evening</option> <option value="Night">Night</option> </select> <input id="input_greet_by_period" type="button" value="please wait" onclick="will_be_set_after_endpoints_apis_loaded"> </P> </body> </html>
gpl-3.0
Yoast/js-text-analysis
spec/stringProcessing/relevantWordsPolishSpec.js
3204
import WordCombination from "../../src/values/WordCombination"; import relevantWords from "../../src/stringProcessing/relevantWords"; import polishFunctionWordsFactory from "../../src/researches/polish/functionWords.js"; const getRelevantWords = relevantWords.getRelevantWords; const polishFunctionWords = polishFunctionWordsFactory().all; describe( "gets Polish word combinations", function() { it( "returns word combinations", function() { const input = "W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast" + " dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy " + "natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, " + "to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce " + "piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w" + " klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś " + "odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że " + "gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas" + " wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę."; const expected = [ new WordCombination( [ "odczuwa", "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast", "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa", "ból", "w", "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "ból", "w", "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa", "ból" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast", "dzwonić" ], 8, polishFunctionWords ), new WordCombination( [ "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "wie" ], 8, polishFunctionWords ), new WordCombination( [ "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "dzwonić" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast" ], 8, polishFunctionWords ), new WordCombination( [ "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "ból" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa" ], 8, polishFunctionWords ), new WordCombination( [ "zasadzie" ], 8, polishFunctionWords ), ]; // Make sure our words aren't filtered by density. spyOn( WordCombination.prototype, "getDensity" ).and.returnValue( 0.01 ); const words = getRelevantWords( input, "pl_PL" ); words.forEach( function( word ) { delete( word._relevantWords ); } ); expect( words ).toEqual( expected ); } ); } );
gpl-3.0
lbernau/smarthome
modules/http/webif/gstatic/css/smarthomeng.css
4959
plusIconlist-group-item.py-2.node-tree.node-selected { background-color: #c3daee; } .table.table-striped.pluginList>tbody>tr:nth-child(even) { background-color:#fff; } .table.table-striped.logicsList>tbody>tr:nth-child(4n+3) { background-color:#fff; } .table-hover>tbody>tr:hover>td, .table-hover>tbody>tr:hover>th { background-color: #ecf3f8; } .minusIcon { position: relative; display: inline-block; height: 22px; width: 22px; background-image: url("/gstatic/img/minus.png"); } .plusIcon { position: relative; display: inline-block; width: 22px; height: 22px; background-image: url("/gstatic/img/plus.png"); } .navBorder { border-top: 1px solid #dee2e6; padding-top: 10px; } .cardOverlay { position: absolute; background: black; display: none; height: 100%; width: 100%; top: 0; left: 0; background: rgba(0, 0, 0, 0.2); border-bottom-right-radius: .25rem; border-bottom-left-radius: .25rem; } .CodeMirror { border: 1px solid #eee; height: auto; } .CodeMirror-scroll { overflow-x: auto; overflow-y: auto; } .python-tabs .cm-tab { background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=); background-position: right; background-repeat: no-repeat; } .item-box { float:left; border: 1px solid rgba(0,0,0,.125); background-color: rgba(0,0,0,.03); border-radius: .25rem; } .text-shng { color: #337ab7 !important; } a.text-shng:focus, a.text-shng:hover { color: #286090 !important; } .btn-shng { color: #fff; background-color: #709cc2; #border-color: #2e6da4; } .btn-shng:hover { color: #fff; background-color: #286090; border-color: #204d74; } .btn-shng-default { color: #fff; background-color: #337ab7; border-color: #2e6da4; } .btn-shng-default:hover { color: #fff; background-color: #286090; border-color: #204d74; } /* .btn-shng2 { color: #000; background-color: #609dd2; #border-color: #2e6da4; } .btn-shng2:hover { color: #fff; background-color: #286090; border-color: #204d74; } */ .btn-shng-outline-secondary { color: #868e96; background-color: transparent; background-image: none; border-color: #c8ccd0; } .btn-shng-outline-secondary:hover { color: #fff; background-color: #868e96; border-color: #868e96; } .btn-shng-outline-secondary:focus, .btn-shng-outline-secondary.focus { /* box-shadow: 0 0 0 0.2rem rgba(134, 142, 150, 0.5); */ } .btn-shng-outline-secondary.disabled, .btn-shng-outline-secondary:disabled { color: #c8ccd0; background-color: transparent; } .btn-shng-outline-secondary:not([disabled]):not(.disabled):active, .btn-shng-outline-secondary:not([disabled]):not(.disabled).active, .show > .btn-shng-outline-secondary.dropdown-toggle { color: #212529; background-color: #c8ccd0; border-color: #c8ccd0; /* box-shadow: 0 0 0 0.2rem rgba(134, 142, 150, 0.5); */ } .btn-shng-success { color: #fff; background-color: #408000; border-color: #408000; } .btn-shng-success:hover { color: #fff; background-color: #1f601f; border-color: #1f601f; } .btn-shng-success:focus, .btn-success.focus { box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.5); } /* .btn-shng-success.disabled, .btn-shng-success:disabled { background-color: #28a745; border-color: #28a745; } .btn-shng-success:not([disabled]):not(.disabled):active, .btn-shng-success:not([disabled]):not(.disabled).active, .show > .btn-shng-success.dropdown-toggle { color: #fff; background-color: #1e7e34; border-color: #1c7430; } .btn-shng-success:not([disabled]):not(.disabled):active:focus, .btn-shng-success:not([disabled]):not(.disabled).active:focus, .show > .btn-shng-success.dropdown-toggle:focus { box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.5); } */ .btn-shng-danger { color: #fff; background-color: #cc5200; border-color: #cc5200; } .btn-shng-danger:hover { color: #fff; background-color: #b34700; border-color: #b34700; } /* .btn-shng-danger:focus, .btn-shng-danger.focus { box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.5); } .btn-shng-danger.disabled, .btn-shng-danger:disabled { background-color: #dc3545; border-color: #dc3545; } .btn-shng-danger:not([disabled]):not(.disabled):active, .btn-shng-danger:not([disabled]):not(.disabled).active, .show > .btn-shng-danger.dropdown-toggle { color: #fff; background-color: #bd2130; border-color: #b21f2d; } .btn-shng-danger:not([disabled]):not(.disabled):active:focus, .btn-shng-danger:not([disabled]):not(.disabled).active:focus, .show > .btn-shng-danger.dropdown-toggle:focus { box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.5); } */ .shng_headline { color: #808080; font-size: 150%; font-weight: bold; } .shng_heading { color: #4d4d4d; font-weight: bold; }
gpl-3.0
MarmonDesigns/cloud.ky
wp-content/themes/milo/comments.php
372
<?php if( ! post_password_required() ) { if ( comments_open() or ( get_comments_number() > 0 ) ) { get_template_part('templates/onePage/blocks/comments-list/comments-list'); get_template_part('templates/onePage/blocks/comments-pagination/comments-pagination'); get_template_part('templates/onePage/blocks/comments-form/comments-form'); } }
gpl-3.0
RESISTANCEQQ/LeagueSharp.Loader-1
Class/Profile.cs
1892
#region LICENSE // Copyright 2014 LeagueSharp.Loader // Profile.cs is part of LeagueSharp.Loader. // // LeagueSharp.Loader 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. // // LeagueSharp.Loader 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 LeagueSharp.Loader. If not, see <http://www.gnu.org/licenses/>. #endregion namespace LeagueSharp.Loader.Class { #region using System.Collections.ObjectModel; using System.ComponentModel; #endregion public class Profile : INotifyPropertyChanged { private ObservableCollection<LeagueSharpAssembly> _installedAssemblies; private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public ObservableCollection<LeagueSharpAssembly> InstalledAssemblies { get { return _installedAssemblies; } set { _installedAssemblies = value; OnPropertyChanged("InstalledAssemblies"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
gpl-3.0
kaoz70/flexcms
themes/sectionalize/views/modulos/enlaces/default_view.php
584
<div class="content"> <ul> <?php foreach($enlaces as $key => $value): ?> <li class="<?=$value->enlaceClase?>"> <? if($value->enlaceImagen != ''): ?> <a href="<?=$value->enlaceLink?>"> <img src="<?=base_url()?>assets/public/images/enlaces/enlace_<?=$value->enlaceId?><?=$imageSize?>.<?=$value->enlaceImagen?>"> </a> <? endif?> <a href="<?=$value->enlaceLink?>"><?=$value->enlaceTexto?></a> </li> <?php endforeach;?> </ul> <a class="leer" href="<?=base_url($diminutivo.'/'.$paginaEnlacesUrl)?>"><?= lang('ui_view_all') ?></a> <?=$pagination?> </div>
gpl-3.0
ayepezv/GAD_ERP
addons/hr_holidays/tests/common.py
1704
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class TestHrHolidaysBase(common.TransactionCase): def setUp(self): super(TestHrHolidaysBase, self).setUp() Users = self.env['res.users'].with_context(no_reset_password=True) # Find Employee group group_employee_id = self.ref('base.group_user') # Test users to use through the various tests self.user_hruser_id = Users.create({ 'name': 'Armande HrUser', 'login': 'Armande', 'alias_name': 'armande', 'email': '[email protected]', 'groups_id': [(6, 0, [group_employee_id, self.ref('base.group_hr_user')])] }).id self.user_hrmanager_id = Users.create({ 'name': 'Bastien HrManager', 'login': 'bastien', 'alias_name': 'bastien', 'email': '[email protected]', 'groups_id': [(6, 0, [group_employee_id, self.ref('base.group_hr_manager')])] }).id self.user_employee_id = Users.create({ 'name': 'David Employee', 'login': 'david', 'alias_name': 'david', 'email': '[email protected]', 'groups_id': [(6, 0, [group_employee_id])] }).id # Hr Data self.employee_emp_id = self.env['hr.employee'].create({ 'name': 'David Employee', 'user_id': self.user_employee_id, }).id self.employee_hruser_id = self.env['hr.employee'].create({ 'name': 'Armande HrUser', 'user_id': self.user_hruser_id, }).id
gpl-3.0
rotagraziosi/archi-wiki-inpeople
includes/common.js
510
 function gestionSelectElement(elementId,msgConfirm) {field=document.getElementById(elementId);if(confirm(msgConfirm)) {selectedIndexASupprimer=field.options.selectedIndex;indice=new Array();texte=new Array();for(i=0;i<field.length;i++) {indice[i]=field.options[i].value;texte[i]=field.options[i].text;} field.innerHTML='';j=0;for(i=0;i<indice.length;i++) {if(i!=selectedIndexASupprimer) {field.options[j]=new Option(texte[i],indice[i]);j++;}}} for(i=0;i<field.length;i++) {field.options[i].selected=true;}}
gpl-3.0
FerranSalguero/db4o
Db4objects.Db4o.Tests/native/Db4objects.Db4o.Tests/CLI1/EnumTestCase.cs
1646
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ using Db4oUnit; using Db4oUnit.Extensions; namespace Db4objects.Db4o.Tests.CLI1 { public class EnumTestCase : AbstractDb4oTestCase { public enum MyEnum { A, B, C, D, F, INCOMPLETE }; protected override void Store() { var item = new Item(); item._enum = MyEnum.C; Store(item); } public void TestRetrieve() { var item = (Item) RetrieveOnlyInstance(typeof (Item)); Assert.AreEqual(MyEnum.C, item._enum); } public void TestPeekPersisted() { var item = (Item) RetrieveOnlyInstance(typeof (Item)); var peeked = (Item) Db().PeekPersisted(item, int.MaxValue, true); Assert.AreEqual(item._enum, peeked._enum); } public class Item { public MyEnum _enum; } } }
gpl-3.0
151706061/MacroMedicalSystem
ImageServer/Web/Application/Pages/WebViewer/Default.aspx.designer.cs
1105
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Macro.ImageServer.Web.Application.Pages.WebViewer { public partial class Default { /// <summary> /// Head1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlHead Head1; /// <summary> /// form2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form2; } }
gpl-3.0
ligo-cbc/pycbc
pycbc/fft/fftw.py
22427
from pycbc.types import zeros, complex64, complex128 import numpy as _np import ctypes import pycbc.scheme as _scheme from pycbc.libutils import get_ctypes_library from .core import _BaseFFT, _BaseIFFT from ..types import check_aligned # IMPORTANT NOTE TO PYCBC DEVELOPERS: # Because this module is loaded automatically when present, and because # no FFTW function should be called until the user has had the chance # to set the threading backend, it is ESSENTIAL that simply loading this # module should not actually *call* ANY functions. #FFTW constants, these are pulled from fftw3.h FFTW_FORWARD = -1 FFTW_BACKWARD = 1 FFTW_MEASURE = 0 FFTW_DESTROY_INPUT = 1 << 0 FFTW_UNALIGNED = 1 << 1 FFTW_CONSERVE_MEMORY = 1 << 2 FFTW_EXHAUSTIVE = 1 << 3 FFTW_PRESERVE_INPUT = 1 << 4 FFTW_PATIENT = 1 << 5 FFTW_ESTIMATE = 1 << 6 FFTW_WISDOM_ONLY = 1 << 21 # Load the single and double precision libraries # We need to construct them directly with CDLL so # we can give the RTLD_GLOBAL mode, which we must do # in order to use the threaded libraries as well. double_lib = get_ctypes_library('fftw3',['fftw3'],mode=ctypes.RTLD_GLOBAL) float_lib = get_ctypes_library('fftw3f',['fftw3f'],mode=ctypes.RTLD_GLOBAL) if (double_lib is None) or (float_lib is None): raise ImportError("Unable to find FFTW libraries") # Support for FFTW's two different threading backends _fftw_threaded_lib = None _fftw_threaded_set = False _double_threaded_lib = None _float_threaded_lib = None HAVE_FFTW_THREADED = False # Although we set the number of threads based on the scheme, # we need a private variable that records the last value used so # we know whether we need to call plan_with_nthreads() again. _fftw_current_nthreads = 0 # This function sets the number of threads used internally by FFTW # in planning. It just takes a number of threads, rather than itself # looking at scheme.mgr.num_threads, because it should not be called # directly, but only by functions that get the value they use from # scheme.mgr.num_threads def _fftw_plan_with_nthreads(nthreads): global _fftw_current_nthreads if not HAVE_FFTW_THREADED: if (nthreads > 1): raise ValueError("Threading is NOT enabled, but {0} > 1 threads specified".format(nthreads)) else: _pycbc_current_threads = nthreads else: dplanwthr = _double_threaded_lib.fftw_plan_with_nthreads fplanwthr = _float_threaded_lib.fftwf_plan_with_nthreads dplanwthr.restype = None fplanwthr.restype = None dplanwthr(nthreads) fplanwthr(nthreads) _fftw_current_nthreads = nthreads # This is a global dict-of-dicts used when initializing threads and # setting the threading library _fftw_threading_libnames = { 'unthreaded' : {'double' : None, 'float' : None}, 'openmp' : {'double' : 'fftw3_omp', 'float' : 'fftw3f_omp'}, 'pthreads' : {'double' : 'fftw3_threads', 'float' : 'fftw3f_threads'}} def _init_threads(backend): # This function actually sets the backend and initializes. It returns zero on # success and 1 if given a valid backend but that cannot be loaded. It raises # an exception if called after the threading backend has already been set, or # if given an invalid backend. global _fftw_threaded_set global _fftw_threaded_lib global HAVE_FFTW_THREADED global _double_threaded_lib global _float_threaded_lib if _fftw_threaded_set: raise RuntimeError( "Threading backend for FFTW already set to {0}; cannot be changed".format(_fftw_threaded_lib)) try: double_threaded_libname = _fftw_threading_libnames[backend]['double'] float_threaded_libname = _fftw_threading_libnames[backend]['float'] except KeyError: raise ValueError("Backend {0} for FFTW threading does not exist!".format(backend)) if double_threaded_libname is not None: try: # Note that the threaded libraries don't have their own pkg-config files; # we must look for them wherever we look for double or single FFTW itself _double_threaded_lib = get_ctypes_library(double_threaded_libname,['fftw3'],mode=ctypes.RTLD_GLOBAL) _float_threaded_lib = get_ctypes_library(float_threaded_libname,['fftw3f'],mode=ctypes.RTLD_GLOBAL) if (_double_threaded_lib is None) or (_float_threaded_lib is None): raise RuntimeError("Unable to load threaded libraries {0} or {1}".format(double_threaded_libname, float_threaded_libname)) dret = _double_threaded_lib.fftw_init_threads() fret = _float_threaded_lib.fftwf_init_threads() # FFTW for some reason uses *0* to indicate failure. In C. if (dret == 0) or (fret == 0): return 1 HAVE_FFTW_THREADED = True _fftw_threaded_set = True _fftw_threaded_lib = backend return 0 except: return 1 else: # We get here when we were given the 'unthreaded' backend HAVE_FFTW_THREADED = False _fftw_threaded_set = True _fftw_threaded_lib = backend return 0 def set_threads_backend(backend=None): # This is the user facing function. If given a backend it just # calls _init_threads and lets it do the work. If not (the default) # then it cycles in order through threaded backends, if backend is not None: retval = _init_threads(backend) # Since the user specified this backend raise an exception if the above failed if retval != 0: raise RuntimeError("Could not initialize FFTW threading backend {0}".format(backend)) else: # Note that we pop() from the end, so 'openmp' is the first thing tried _backend_list = ['unthreaded','pthreads','openmp'] while not _fftw_threaded_set: _next_backend = _backend_list.pop() retval = _init_threads(_next_backend) # Function to import system-wide wisdom files. def import_sys_wisdom(): if not _fftw_threaded_set: set_threads_backend() double_lib.fftw_import_system_wisdom() float_lib.fftwf_import_system_wisdom() # We provide an interface for changing the "measure level" # By default this is 0, which does no planning, # but we provide functions to read and set it _default_measurelvl = 0 def get_measure_level(): """ Get the current 'measure level' used in deciding how much effort to put into creating FFTW plans. From least effort (and shortest planning time) to most they are 0 to 3. No arguments. """ return _default_measurelvl def set_measure_level(mlvl): """ Set the current 'measure level' used in deciding how much effort to expend creating FFTW plans. Must be an integer from 0 (least effort, shortest time) to 3 (most effort and time). """ global _default_measurelvl if mlvl not in (0,1,2,3): raise ValueError("Measure level can only be one of 0, 1, 2, or 3") _default_measurelvl = mlvl _flag_dict = {0: FFTW_ESTIMATE, 1: FFTW_MEASURE, 2: FFTW_MEASURE|FFTW_PATIENT, 3: FFTW_MEASURE|FFTW_PATIENT|FFTW_EXHAUSTIVE} def get_flag(mlvl,aligned): if aligned: return _flag_dict[mlvl] else: return (_flag_dict[mlvl]|FFTW_UNALIGNED) # Add the ability to read/store wisdom to filenames def wisdom_io(filename, precision, action): """Import or export an FFTW plan for single or double precision. """ if not _fftw_threaded_set: set_threads_backend() fmap = {('float', 'import'): float_lib.fftwf_import_wisdom_from_filename, ('float', 'export'): float_lib.fftwf_export_wisdom_to_filename, ('double', 'import'): double_lib.fftw_import_wisdom_from_filename, ('double', 'export'): double_lib.fftw_export_wisdom_to_filename} f = fmap[(precision, action)] f.argtypes = [ctypes.c_char_p] retval = f(filename.encode()) if retval == 0: raise RuntimeError(('Could not {0} wisdom ' 'from file {1}').format(action, filename)) def import_single_wisdom_from_filename(filename): wisdom_io(filename, 'float', 'import') def import_double_wisdom_from_filename(filename): wisdom_io(filename, 'double', 'import') def export_single_wisdom_to_filename(filename): wisdom_io(filename, 'float', 'export') def export_double_wisdom_to_filename(filename): wisdom_io(filename, 'double', 'export') def set_planning_limit(time): if not _fftw_threaded_set: set_threads_backend() f = double_lib.fftw_set_timelimit f.argtypes = [ctypes.c_double] f(time) f = float_lib.fftwf_set_timelimit f.argtypes = [ctypes.c_double] f(time) # Create function maps for the dtypes plan_function = {'float32': {'complex64': float_lib.fftwf_plan_dft_r2c_1d}, 'float64': {'complex128': double_lib.fftw_plan_dft_r2c_1d}, 'complex64': {'float32': float_lib.fftwf_plan_dft_c2r_1d, 'complex64': float_lib.fftwf_plan_dft_1d}, 'complex128': {'float64': double_lib.fftw_plan_dft_c2r_1d, 'complex128': double_lib.fftw_plan_dft_1d} } execute_function = {'float32': {'complex64': float_lib.fftwf_execute_dft_r2c}, 'float64': {'complex128': double_lib.fftw_execute_dft_r2c}, 'complex64': {'float32': float_lib.fftwf_execute_dft_c2r, 'complex64': float_lib.fftwf_execute_dft}, 'complex128': {'float64': double_lib.fftw_execute_dft_c2r, 'complex128': double_lib.fftw_execute_dft} } def plan(size, idtype, odtype, direction, mlvl, aligned, nthreads, inplace): if not _fftw_threaded_set: set_threads_backend() if nthreads != _fftw_current_nthreads: _fftw_plan_with_nthreads(nthreads) # Convert a measure-level to flags flags = get_flag(mlvl,aligned) # We make our arrays of the necessary type and size. Things can be # tricky, especially for in-place transforms with one of input or # output real. if (idtype == odtype): # We're in the complex-to-complex case, so lengths are the same ip = zeros(size, dtype=idtype) if inplace: op = ip else: op = zeros(size, dtype=odtype) elif (idtype.kind == 'c') and (odtype.kind == 'f'): # Complex-to-real (reverse), so size is length of real array. # However the complex array may be larger (in bytes) and # should therefore be allocated first and reused for an in-place # transform ip = zeros(size/2+1, dtype=idtype) if inplace: op = ip.view(dtype=odtype)[0:size] else: op = zeros(size, dtype=odtype) else: # Real-to-complex (forward), and size is still that of real. # However it is still true that the complex array may be larger # (in bytes) and should therefore be allocated first and reused # for an in-place transform op = zeros(size/2+1, dtype=odtype) if inplace: ip = op.view(dtype=idtype)[0:size] else: ip = zeros(size, dtype=idtype) # Get the plan function idtype = _np.dtype(idtype) odtype = _np.dtype(odtype) f = plan_function[str(idtype)][str(odtype)] f.restype = ctypes.c_void_p # handle the C2C cases (forward and reverse) if idtype.kind == odtype.kind: f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int] theplan = f(size, ip.ptr, op.ptr, direction, flags) # handle the R2C and C2R case else: f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] theplan = f(size, ip.ptr, op.ptr, flags) # We don't need ip or op anymore del ip, op # Make the destructors if idtype.char in ['f', 'F']: destroy = float_lib.fftwf_destroy_plan else: destroy = double_lib.fftw_destroy_plan destroy.argtypes = [ctypes.c_void_p] return theplan, destroy # Note that we don't need to check whether we've set the threading backend # in the following functions, since execute is not called directly and # the fft and ifft will call plan first. def execute(plan, invec, outvec): f = execute_function[str(invec.dtype)][str(outvec.dtype)] f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] f(plan, invec.ptr, outvec.ptr) def fft(invec, outvec, prec, itype, otype): theplan, destroy = plan(len(invec), invec.dtype, outvec.dtype, FFTW_FORWARD, get_measure_level(),(check_aligned(invec.data) and check_aligned(outvec.data)), _scheme.mgr.state.num_threads, (invec.ptr == outvec.ptr)) execute(theplan, invec, outvec) destroy(theplan) def ifft(invec, outvec, prec, itype, otype): theplan, destroy = plan(len(outvec), invec.dtype, outvec.dtype, FFTW_BACKWARD, get_measure_level(),(check_aligned(invec.data) and check_aligned(outvec.data)), _scheme.mgr.state.num_threads, (invec.ptr == outvec.ptr)) execute(theplan, invec, outvec) destroy(theplan) # Class based API # First, set up a lot of different ctypes functions: plan_many_c2c_f = float_lib.fftwf_plan_many_dft plan_many_c2c_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_c2c_f.restype = ctypes.c_void_p plan_many_c2c_d = double_lib.fftw_plan_many_dft plan_many_c2c_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_c2c_d.restype = ctypes.c_void_p plan_many_c2r_f = float_lib.fftwf_plan_many_dft_c2r plan_many_c2r_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_c2r_f.restype = ctypes.c_void_p plan_many_c2r_d = double_lib.fftw_plan_many_dft_c2r plan_many_c2r_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_c2r_d.restype = ctypes.c_void_p plan_many_r2c_f = float_lib.fftwf_plan_many_dft_r2c plan_many_r2c_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_r2c_f.restype = ctypes.c_void_p plan_many_r2c_d = double_lib.fftw_plan_many_dft_r2c plan_many_r2c_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint] plan_many_r2c_d.restype = ctypes.c_void_p # Now set up a dictionary indexed by (str(input_dtype), str(output_dtype)) to # translate input and output dtypes into the correct planning function. _plan_funcs_dict = { ('complex64', 'complex64') : plan_many_c2c_f, ('complex64', 'float32') : plan_many_r2c_f, ('float32', 'complex64') : plan_many_c2r_f, ('complex128', 'complex128') : plan_many_c2c_d, ('complex128', 'float64') : plan_many_r2c_d, ('float64', 'complex128') : plan_many_c2r_d } # To avoid multiple-inheritance, we set up a function that returns much # of the initialization that will need to be handled in __init__ of both # classes. def _fftw_setup(fftobj): n = _np.asarray([fftobj.size], dtype=_np.int32) inembed = _np.asarray([len(fftobj.invec)], dtype=_np.int32) onembed = _np.asarray([len(fftobj.outvec)], dtype=_np.int32) nthreads = _scheme.mgr.state.num_threads if not _fftw_threaded_set: set_threads_backend() if nthreads != _fftw_current_nthreads: _fftw_plan_with_nthreads(nthreads) mlvl = get_measure_level() aligned = check_aligned(fftobj.invec.data) and check_aligned(fftobj.outvec.data) flags = get_flag(mlvl, aligned) plan_func = _plan_funcs_dict[ (str(fftobj.invec.dtype), str(fftobj.outvec.dtype)) ] tmpin = zeros(len(fftobj.invec), dtype = fftobj.invec.dtype) tmpout = zeros(len(fftobj.outvec), dtype = fftobj.outvec.dtype) # C2C, forward if fftobj.forward and (fftobj.outvec.dtype in [complex64, complex128]): plan = plan_func(1, n.ctypes.data, fftobj.nbatch, tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist, tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist, FFTW_FORWARD, flags) # C2C, backward elif not fftobj.forward and (fftobj.invec.dtype in [complex64, complex128]): plan = plan_func(1, n.ctypes.data, fftobj.nbatch, tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist, tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist, FFTW_BACKWARD, flags) # R2C or C2R (hence no direction argument for plan creation) else: plan = plan_func(1, n.ctypes.data, fftobj.nbatch, tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist, tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist, flags) del tmpin del tmpout return plan class FFT(_BaseFFT): def __init__(self, invec, outvec, nbatch=1, size=None): super(FFT, self).__init__(invec, outvec, nbatch, size) self.iptr = self.invec.ptr self.optr = self.outvec.ptr self._efunc = execute_function[str(self.invec.dtype)][str(self.outvec.dtype)] self._efunc.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.plan = _fftw_setup(self) def execute(self): self._efunc(self.plan, self.iptr, self.optr) class IFFT(_BaseIFFT): def __init__(self, invec, outvec, nbatch=1, size=None): super(IFFT, self).__init__(invec, outvec, nbatch, size) self.iptr = self.invec.ptr self.optr = self.outvec.ptr self._efunc = execute_function[str(self.invec.dtype)][str(self.outvec.dtype)] self._efunc.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.plan = _fftw_setup(self) def execute(self): self._efunc(self.plan, self.iptr, self.optr) def insert_fft_options(optgroup): """ Inserts the options that affect the behavior of this backend Parameters ---------- optgroup: fft_option OptionParser argument group whose options are extended """ optgroup.add_argument("--fftw-measure-level", help="Determines the measure level used in planning " "FFTW FFTs; allowed values are: " + str([0,1,2,3]), type=int, default=_default_measurelvl) optgroup.add_argument("--fftw-threads-backend", help="Give 'openmp', 'pthreads' or 'unthreaded' to specify which threaded FFTW to use", default=None) optgroup.add_argument("--fftw-input-float-wisdom-file", help="Filename from which to read single-precision wisdom", default=None) optgroup.add_argument("--fftw-input-double-wisdom-file", help="Filename from which to read double-precision wisdom", default=None) optgroup.add_argument("--fftw-output-float-wisdom-file", help="Filename to which to write single-precision wisdom", default=None) optgroup.add_argument("--fftw-output-double-wisdom-file", help="Filename to which to write double-precision wisdom", default=None) optgroup.add_argument("--fftw-import-system-wisdom", help = "If given, call fftw[f]_import_system_wisdom()", action = "store_true") def verify_fft_options(opt,parser): """Parses the FFT options and verifies that they are reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes. parser : object OptionParser instance. """ if opt.fftw_measure_level not in [0,1,2,3]: parser.error("{0} is not a valid FFTW measure level.".format(opt.fftw_measure_level)) if opt.fftw_import_system_wisdom and ((opt.fftw_input_float_wisdom_file is not None) or (opt.fftw_input_double_wisdom_file is not None)): parser.error("If --fftw-import-system-wisdom is given, then you cannot give" " either of --fftw-input-float-wisdom-file or --fftw-input-double-wisdom-file") if opt.fftw_threads_backend is not None: if opt.fftw_threads_backend not in ['openmp','pthreads','unthreaded']: parser.error("Invalid threads backend; must be 'openmp', 'pthreads' or 'unthreaded'") def from_cli(opt): # Since opt.fftw_threads_backend defaults to None, the following is always # appropriate: set_threads_backend(opt.fftw_threads_backend) # Set the user-provided measure level set_measure_level(opt.fftw_measure_level)
gpl-3.0
rutaihwa/SMSSecure
src/org/smssecure/smssecure/preferences/AppearancePreferenceFragment.java
2545
package org.smssecure.smssecure.preferences; import android.content.Context; import android.os.Bundle; import android.preference.ListPreference; import org.smssecure.smssecure.ApplicationPreferencesActivity; import org.smssecure.smssecure.R; import org.smssecure.smssecure.util.SMSSecurePreferences; import java.util.Arrays; public class AppearancePreferenceFragment extends ListSummaryPreferenceFragment { @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_appearance); this.findPreference(SMSSecurePreferences.THEME_PREF).setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(SMSSecurePreferences.LANGUAGE_PREF).setOnPreferenceChangeListener(new ListSummaryListener()); initializeListSummary((ListPreference)findPreference(SMSSecurePreferences.THEME_PREF)); initializeListSummary((ListPreference)findPreference(SMSSecurePreferences.LANGUAGE_PREF)); } @Override public void onStart() { super.onStart(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener((ApplicationPreferencesActivity)getActivity()); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__appearance); } @Override public void onStop() { super.onStop(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener((ApplicationPreferencesActivity) getActivity()); } public static CharSequence getSummary(Context context) { String[] languageEntries = context.getResources().getStringArray(R.array.language_entries); String[] languageEntryValues = context.getResources().getStringArray(R.array.language_values); String[] themeEntries = context.getResources().getStringArray(R.array.pref_theme_entries); String[] themeEntryValues = context.getResources().getStringArray(R.array.pref_theme_values); int langIndex = Arrays.asList(languageEntryValues).indexOf(SMSSecurePreferences.getLanguage(context)); int themeIndex = Arrays.asList(themeEntryValues).indexOf(SMSSecurePreferences.getTheme(context)); if (langIndex == -1) langIndex = 0; if (themeIndex == -1) themeIndex = 0; return context.getString(R.string.ApplicationPreferencesActivity_appearance_summary, themeEntries[themeIndex], languageEntries[langIndex]); } }
gpl-3.0
andre-hub/Tiny-Tiny-RSS
vendor/chillerlan/php-qrcode/src/Data/QRDataAbstract.php
7849
<?php /** * Class QRDataAbstract * * @filesource QRDataAbstract.php * @created 25.11.2015 * @package chillerlan\QRCode\Data * @author Smiley <[email protected]> * @copyright 2015 Smiley * @license MIT */ namespace chillerlan\QRCode\Data; use chillerlan\QRCode\{QRCode, QRCodeException}; use chillerlan\QRCode\Helpers\{BitBuffer, Polynomial}; use chillerlan\Settings\SettingsContainerInterface; use function array_fill, array_merge, count, max, mb_convert_encoding, mb_detect_encoding, range, sprintf, strlen; /** * Processes the binary data and maps it on a matrix which is then being returned */ abstract class QRDataAbstract implements QRDataInterface{ /** * the string byte count * * @var int */ protected $strlen; /** * the current data mode: Num, Alphanum, Kanji, Byte * * @var int */ protected $datamode; /** * mode length bits for the version breakpoints 1-9, 10-26 and 27-40 * * @var array */ protected $lengthBits = [0, 0, 0]; /** * current QR Code version * * @var int */ protected $version; /** * the raw data that's being passed to QRMatrix::mapData() * * @var array */ protected $matrixdata; /** * ECC temp data * * @var array */ protected $ecdata; /** * ECC temp data * * @var array */ protected $dcdata; /** * @var \chillerlan\QRCode\QROptions */ protected $options; /** * @var \chillerlan\QRCode\Helpers\BitBuffer */ protected $bitBuffer; /** * QRDataInterface constructor. * * @param \chillerlan\Settings\SettingsContainerInterface $options * @param string|null $data */ public function __construct(SettingsContainerInterface $options, string $data = null){ $this->options = $options; if($data !== null){ $this->setData($data); } } /** * @inheritDoc */ public function setData(string $data):QRDataInterface{ if($this->datamode === QRCode::DATA_KANJI){ $data = mb_convert_encoding($data, 'SJIS', mb_detect_encoding($data)); } $this->strlen = $this->getLength($data); $this->version = $this->options->version === QRCode::VERSION_AUTO ? $this->getMinimumVersion() : $this->options->version; $this->matrixdata = $this ->writeBitBuffer($data) ->maskECC() ; return $this; } /** * @inheritDoc */ public function initMatrix(int $maskPattern, bool $test = null):QRMatrix{ return (new QRMatrix($this->version, $this->options->eccLevel)) ->setFinderPattern() ->setSeparators() ->setAlignmentPattern() ->setTimingPattern() ->setVersionNumber($test) ->setFormatInfo($maskPattern, $test) ->setDarkModule() ->mapData($this->matrixdata, $maskPattern) ; } /** * returns the length bits for the version breakpoints 1-9, 10-26 and 27-40 * * @return int * @throws \chillerlan\QRCode\Data\QRCodeDataException * @codeCoverageIgnore */ protected function getLengthBits():int{ foreach([9, 26, 40] as $key => $breakpoint){ if($this->version <= $breakpoint){ return $this->lengthBits[$key]; } } throw new QRCodeDataException(sprintf('invalid version number: %d', $this->version)); } /** * returns the byte count of the $data string * * @param string $data * * @return int */ protected function getLength(string $data):int{ return strlen($data); } /** * returns the minimum version number for the given string * * @return int * @throws \chillerlan\QRCode\Data\QRCodeDataException */ protected function getMinimumVersion():int{ $maxlength = 0; // guess the version number within the given range foreach(range($this->options->versionMin, $this->options->versionMax) as $version){ $maxlength = $this::MAX_LENGTH[$version][QRCode::DATA_MODES[$this->datamode]][QRCode::ECC_MODES[$this->options->eccLevel]]; if($this->strlen <= $maxlength){ return $version; } } throw new QRCodeDataException(sprintf('data exceeds %d characters', $maxlength)); } /** * writes the actual data string to the BitBuffer * * @see \chillerlan\QRCode\Data\QRDataAbstract::writeBitBuffer() * * @param string $data * * @return void */ abstract protected function write(string $data):void; /** * creates a BitBuffer and writes the string data to it * * @param string $data * * @return \chillerlan\QRCode\Data\QRDataAbstract * @throws \chillerlan\QRCode\QRCodeException */ protected function writeBitBuffer(string $data):QRDataInterface{ $this->bitBuffer = new BitBuffer; $MAX_BITS = $this::MAX_BITS[$this->version][QRCode::ECC_MODES[$this->options->eccLevel]]; $this->bitBuffer ->clear() ->put($this->datamode, 4) ->put($this->strlen, $this->getLengthBits()) ; $this->write($data); // there was an error writing the BitBuffer data, which is... unlikely. if($this->bitBuffer->length > $MAX_BITS){ throw new QRCodeException(sprintf('code length overflow. (%d > %d bit)', $this->bitBuffer->length, $MAX_BITS)); // @codeCoverageIgnore } // end code. if($this->bitBuffer->length + 4 <= $MAX_BITS){ $this->bitBuffer->put(0, 4); } // padding while($this->bitBuffer->length % 8 !== 0){ $this->bitBuffer->putBit(false); } // padding while(true){ if($this->bitBuffer->length >= $MAX_BITS){ break; } $this->bitBuffer->put(0xEC, 8); if($this->bitBuffer->length >= $MAX_BITS){ break; } $this->bitBuffer->put(0x11, 8); } return $this; } /** * ECC masking * * @link http://www.thonky.com/qr-code-tutorial/error-correction-coding * * @return array */ protected function maskECC():array{ [$l1, $l2, $b1, $b2] = $this::RSBLOCKS[$this->version][QRCode::ECC_MODES[$this->options->eccLevel]]; $rsBlocks = array_fill(0, $l1, [$b1, $b2]); $rsCount = $l1 + $l2; $this->ecdata = array_fill(0, $rsCount, null); $this->dcdata = $this->ecdata; if($l2 > 0){ $rsBlocks = array_merge($rsBlocks, array_fill(0, $l2, [$b1 + 1, $b2 + 1])); } $totalCodeCount = 0; $maxDcCount = 0; $maxEcCount = 0; $offset = 0; foreach($rsBlocks as $key => $block){ [$rsBlockTotal, $dcCount] = $block; $ecCount = $rsBlockTotal - $dcCount; $maxDcCount = max($maxDcCount, $dcCount); $maxEcCount = max($maxEcCount, $ecCount); $this->dcdata[$key] = array_fill(0, $dcCount, null); foreach($this->dcdata[$key] as $a => $_z){ $this->dcdata[$key][$a] = 0xff & $this->bitBuffer->buffer[$a + $offset]; } [$num, $add] = $this->poly($key, $ecCount); foreach($this->ecdata[$key] as $c => $_z){ $modIndex = $c + $add; $this->ecdata[$key][$c] = $modIndex >= 0 ? $num[$modIndex] : 0; } $offset += $dcCount; $totalCodeCount += $rsBlockTotal; } $data = array_fill(0, $totalCodeCount, null); $index = 0; $mask = function($arr, $count) use (&$data, &$index, $rsCount){ for($x = 0; $x < $count; $x++){ for($y = 0; $y < $rsCount; $y++){ if($x < count($arr[$y])){ $data[$index] = $arr[$y][$x]; $index++; } } } }; $mask($this->dcdata, $maxDcCount); $mask($this->ecdata, $maxEcCount); return $data; } /** * @param int $key * @param int $count * * @return int[] */ protected function poly(int $key, int $count):array{ $rsPoly = new Polynomial; $modPoly = new Polynomial; for($i = 0; $i < $count; $i++){ $modPoly->setNum([1, $modPoly->gexp($i)]); $rsPoly->multiply($modPoly->getNum()); } $rsPolyCount = count($rsPoly->getNum()); $modPoly ->setNum($this->dcdata[$key], $rsPolyCount - 1) ->mod($rsPoly->getNum()) ; $this->ecdata[$key] = array_fill(0, $rsPolyCount - 1, null); $num = $modPoly->getNum(); return [ $num, count($num) - count($this->ecdata[$key]), ]; } }
gpl-3.0
randy1/conky
src/exec.cc
7376
/* -*- mode: c++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*- * vim: ts=4 sw=4 noet ai cindent syntax=cpp * * Conky, a system monitor, based on torsmo * * Any original torsmo code is licensed under the BSD license * * All code written since the fork of torsmo is licensed under the GPL * * Please see COPYING for details * * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen * Copyright (c) 2005-2012 Brenden Matthews, Philip Kovacs, et. al. * (see AUTHORS) * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "conky.h" #include "core.h" #include "logging.h" #include "specials.h" #include "text_object.h" #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <cmath> #include <mutex> #include "update-cb.hh" namespace { class exec_cb: public conky::callback<std::string, std::string> { typedef conky::callback<std::string, std::string> Base; protected: virtual void work(); public: exec_cb(uint32_t period, bool wait, const std::string &cmd) : Base(period, wait, Base::Tuple(cmd)) {} }; } struct execi_data { float interval; char *cmd; execi_data() : interval(0), cmd(0) {} }; //our own implementation of popen, the difference : the value of 'childpid' will be filled with //the pid of the running 'command'. This is useful if want to kill it when it hangs while reading //or writing to it. We have to kill it because pclose will wait until the process dies by itself static FILE* pid_popen(const char *command, const char *mode, pid_t *child) { int ends[2]; int parentend, childend; //by running pipe after the strcmp's we make sure that we don't have to create a pipe //and close the ends if mode is something illegal if(strcmp(mode, "r") == 0) { if(pipe(ends) != 0) { return NULL; } parentend = ends[0]; childend = ends[1]; } else if(strcmp(mode, "w") == 0) { if(pipe(ends) != 0) { return NULL; } parentend = ends[1]; childend = ends[0]; } else { return NULL; } *child = fork(); if(*child == -1) { close(parentend); close(childend); return NULL; } else if(*child > 0) { close(childend); waitpid(*child, NULL, 0); } else { //don't read from both stdin and pipe or write to both stdout and pipe if(childend == ends[0]) { close(0); } else { close(1); } close(parentend); //by dupping childend, the returned fd will have close-on-exec turned off if (dup(childend) == -1) perror("dup()"); close(childend); execl("/bin/sh", "sh", "-c", command, (char *) NULL); _exit(EXIT_FAILURE); //child should die here, (normally execl will take care of this but it can fail) } return fdopen(parentend, mode); } void exec_cb::work() { pid_t childpid; std::string buf; std::shared_ptr<FILE> fp; char b[0x1000]; if(FILE *t = pid_popen(std::get<0>(tuple).c_str(), "r", &childpid)) fp.reset(t, fclose); else return; while(!feof(fp.get()) && !ferror(fp.get())) { int length = fread(b, 1, sizeof b, fp.get()); buf.append(b, length); } if(*buf.rbegin() == '\n') buf.resize(buf.size()-1); std::lock_guard<std::mutex> l(result_mutex); result = buf; } //remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat" //string has to end with \0 and it's length should fit in a int #define BACKSPACE 8 static void remove_deleted_chars(char *string){ int i = 0; while(string[i] != 0){ if(string[i] == BACKSPACE){ if(i != 0){ strcpy( &(string[i-1]), &(string[i+1]) ); i--; }else strcpy( &(string[i]), &(string[i+1]) ); //necessary for ^H's at the start of a string }else i++; } } static inline double get_barnum(const char *buf) { double barnum; if (sscanf(buf, "%lf", &barnum) != 1) { NORM_ERR("reading exec value failed (perhaps it's not the " "correct format?)"); return 0.0; } if (barnum > 100.0 || barnum < 0.0) { NORM_ERR("your exec value is not between 0 and 100, " "therefore it will be ignored"); return 0.0; } return barnum; } void scan_exec_arg(struct text_object *obj, const char *arg) { /* XXX: do real bar parsing here */ scan_bar(obj, "", 100); obj->data.s = strndup(arg ? arg : "", text_buffer_size.get(*state)); } void scan_execi_arg(struct text_object *obj, const char *arg) { struct execi_data *ed; int n; ed = new execi_data; if (sscanf(arg, "%f %n", &ed->interval, &n) <= 0) { NORM_ERR("${execi* <interval> command}"); delete ed; return; } ed->cmd = strndup(arg + n, text_buffer_size.get(*state)); obj->data.opaque = ed; } void scan_execi_bar_arg(struct text_object *obj, const char *arg) { /* XXX: do real bar parsing here */ scan_bar(obj, "", 100); scan_execi_arg(obj, arg); } #ifdef BUILD_X11 void scan_execi_gauge_arg(struct text_object *obj, const char *arg) { /* XXX: do real gauge parsing here */ scan_gauge(obj, "", 100); scan_execi_arg(obj, arg); } void scan_execgraph_arg(struct text_object *obj, const char *arg) { struct execi_data *ed; char *buf; ed = new execi_data; memset(ed, 0, sizeof(struct execi_data)); buf = scan_graph(obj, arg, 100); if (!buf) { NORM_ERR("missing command argument to execgraph object"); return; } ed->cmd = buf; obj->data.opaque = ed; } #endif /* BUILD_X11 */ void fill_p(const char *buffer, struct text_object *obj, char *p, int p_max_size) { if(obj->parse == true) { evaluate(buffer, p, p_max_size); } else snprintf(p, p_max_size, "%s", buffer); remove_deleted_chars(p); } void print_exec(struct text_object *obj, char *p, int p_max_size) { auto cb = conky::register_cb<exec_cb>(1, true, obj->data.s); fill_p(cb->get_result_copy().c_str(), obj, p, p_max_size); } void print_execi(struct text_object *obj, char *p, int p_max_size) { struct execi_data *ed = (struct execi_data *)obj->data.opaque; if (!ed) return; uint32_t period = std::max(lround(ed->interval/active_update_interval()), 1l); auto cb = conky::register_cb<exec_cb>(period, !obj->thread, ed->cmd); fill_p(cb->get_result_copy().c_str(), obj, p, p_max_size); } double execbarval(struct text_object *obj) { auto cb = conky::register_cb<exec_cb>(1, true, obj->data.s); return get_barnum(cb->get_result_copy().c_str()); } double execi_barval(struct text_object *obj) { struct execi_data *ed = (struct execi_data *)obj->data.opaque; if (!ed) return 0; uint32_t period = std::max(lround(ed->interval/active_update_interval()), 1l); auto cb = conky::register_cb<exec_cb>(period, !obj->thread, ed->cmd); return get_barnum(cb->get_result_copy().c_str()); } void free_exec(struct text_object *obj) { free_and_zero(obj->data.s); } void free_execi(struct text_object *obj) { struct execi_data *ed = (struct execi_data *)obj->data.opaque; if (!ed) return; free_and_zero(ed->cmd); delete ed; obj->data.opaque = NULL; }
gpl-3.0
cuihantao/cvxopt
src/C/SuiteSparse/UMFPACK/Source/umf_kernel.c
9625
/* ========================================================================== */ /* === UMF_kernel =========================================================== */ /* ========================================================================== */ /* -------------------------------------------------------------------------- */ /* Copyright (c) 2005-2012 by Timothy A. Davis, http://www.suitesparse.com. */ /* All Rights Reserved. See ../Doc/License.txt for License. */ /* -------------------------------------------------------------------------- */ /* Primary factorization routine. Called by UMFPACK_numeric. Returns: UMFPACK_OK if successful, UMFPACK_ERROR_out_of_memory if out of memory, or UMFPACK_ERROR_different_pattern if pattern of matrix (Ap and/or Ai) has changed since the call to UMFPACK_*symbolic. */ #include "umf_internal.h" #include "umf_kernel.h" #include "umf_kernel_init.h" #include "umf_init_front.h" #include "umf_start_front.h" #include "umf_assemble.h" #include "umf_scale_column.h" #include "umf_local_search.h" #include "umf_create_element.h" #include "umf_extend_front.h" #include "umf_blas3_update.h" #include "umf_store_lu.h" #include "umf_kernel_wrapup.h" /* perform an action, and return if out of memory */ #define DO(action) { if (! (action)) { return (UMFPACK_ERROR_out_of_memory) ; }} GLOBAL Int UMF_kernel ( const Int Ap [ ], const Int Ai [ ], const double Ax [ ], #ifdef COMPLEX const double Az [ ], #endif NumericType *Numeric, WorkType *Work, SymbolicType *Symbolic ) { /* ---------------------------------------------------------------------- */ /* local variables */ /* ---------------------------------------------------------------------- */ Int j, f1, f2, chain, nchains, *Chain_start, status, fixQ, evaporate, *Front_npivcol, jmax, nb, drop ; /* ---------------------------------------------------------------------- */ /* initialize memory space and load the matrix. Optionally scale. */ /* ---------------------------------------------------------------------- */ if (!UMF_kernel_init (Ap, Ai, Ax, #ifdef COMPLEX Az, #endif Numeric, Work, Symbolic)) { /* UMF_kernel_init is guaranteed to succeed, since UMFPACK_numeric */ /* either allocates enough space or if not, UMF_kernel does not get */ /* called. So running out of memory here is a fatal error, and means */ /* that the user changed Ap and/or Ai since the call to */ /* UMFPACK_*symbolic. */ DEBUGm4 (("kernel init failed\n")) ; return (UMFPACK_ERROR_different_pattern) ; } /* ---------------------------------------------------------------------- */ /* get the symbolic factorization */ /* ---------------------------------------------------------------------- */ nchains = Symbolic->nchains ; Chain_start = Symbolic->Chain_start ; Front_npivcol = Symbolic->Front_npivcol ; nb = Symbolic->nb ; fixQ = Symbolic->fixQ ; drop = Numeric->droptol > 0.0 ; #ifndef NDEBUG for (chain = 0 ; chain < nchains ; chain++) { Int i ; f1 = Chain_start [chain] ; f2 = Chain_start [chain+1] - 1 ; DEBUG1 (("\nCHain: "ID" start "ID" end "ID"\n", chain, f1, f2)) ; for (i = f1 ; i <= f2 ; i++) { DEBUG1 (("Front "ID", npivcol "ID"\n", i, Front_npivcol [i])) ; } } #endif /* ---------------------------------------------------------------------- */ /* factorize each chain of frontal matrices */ /* ---------------------------------------------------------------------- */ for (chain = 0 ; chain < nchains ; chain++) { f1 = Chain_start [chain] ; f2 = Chain_start [chain+1] - 1 ; /* ------------------------------------------------------------------ */ /* get the initial frontal matrix size for this chain */ /* ------------------------------------------------------------------ */ DO (UMF_start_front (chain, Numeric, Work, Symbolic)) ; /* ------------------------------------------------------------------ */ /* factorize each front in the chain */ /* ------------------------------------------------------------------ */ for (Work->frontid = f1 ; Work->frontid <= f2 ; Work->frontid++) { /* -------------------------------------------------------------- */ /* Initialize the pivot column candidate set */ /* -------------------------------------------------------------- */ Work->ncand = Front_npivcol [Work->frontid] ; Work->lo = Work->nextcand ; Work->hi = Work->nextcand + Work->ncand - 1 ; jmax = MIN (MAX_CANDIDATES, Work->ncand) ; DEBUGm1 ((">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Starting front " ID", npivcol: "ID"\n", Work->frontid, Work->ncand)) ; if (fixQ) { /* do not modify the column order */ jmax = 1 ; } DEBUGm1 (("Initial candidates: ")) ; for (j = 0 ; j < jmax ; j++) { DEBUGm1 ((" "ID, Work->nextcand)) ; ASSERT (Work->nextcand <= Work->hi) ; Work->Candidates [j] = Work->nextcand++ ; } Work->nCandidates = jmax ; DEBUGm1 (("\n")) ; /* -------------------------------------------------------------- */ /* Assemble and factorize the current frontal matrix */ /* -------------------------------------------------------------- */ while (Work->ncand > 0) { /* ---------------------------------------------------------- */ /* get the pivot row and column */ /* ---------------------------------------------------------- */ status = UMF_local_search (Numeric, Work, Symbolic) ; if (status == UMFPACK_ERROR_different_pattern) { /* :: pattern change detected in umf_local_search :: */ /* input matrix has changed since umfpack_*symbolic */ DEBUGm4 (("local search failed\n")) ; return (UMFPACK_ERROR_different_pattern) ; } if (status == UMFPACK_WARNING_singular_matrix) { /* no pivot found, discard and try again */ continue ; } /* ---------------------------------------------------------- */ /* update if front not extended or too many zeros in L,U */ /* ---------------------------------------------------------- */ if (Work->do_update) { UMF_blas3_update (Work) ; if (drop) { DO (UMF_store_lu_drop (Numeric, Work)) ; } else { DO (UMF_store_lu (Numeric, Work)) ; } } /* ---------------------------------------------------------- */ /* extend the frontal matrix, or start a new one */ /* ---------------------------------------------------------- */ if (Work->do_extend) { /* extend the current front */ DO (UMF_extend_front (Numeric, Work)) ; } else { /* finish the current front (if any) and start a new one */ DO (UMF_create_element (Numeric, Work, Symbolic)) ; DO (UMF_init_front (Numeric, Work)) ; } /* ---------------------------------------------------------- */ /* Numerical & symbolic assembly into current frontal matrix */ /* ---------------------------------------------------------- */ if (fixQ) { UMF_assemble_fixq (Numeric, Work) ; } else { UMF_assemble (Numeric, Work) ; } /* ---------------------------------------------------------- */ /* scale the pivot column */ /* ---------------------------------------------------------- */ UMF_scale_column (Numeric, Work) ; /* ---------------------------------------------------------- */ /* Numerical update if enough pivots accumulated */ /* ---------------------------------------------------------- */ evaporate = Work->fnrows == 0 || Work->fncols == 0 ; if (Work->fnpiv >= nb || evaporate) { UMF_blas3_update (Work) ; if (drop) { DO (UMF_store_lu_drop (Numeric, Work)) ; } else { DO (UMF_store_lu (Numeric, Work)) ; } } Work->pivrow_in_front = FALSE ; Work->pivcol_in_front = FALSE ; /* ---------------------------------------------------------- */ /* If front is empty, evaporate it */ /* ---------------------------------------------------------- */ if (evaporate) { /* This does not create an element, just evaporates it. * It ensures that a front is not 0-by-c or r-by-0. No * memory is allocated, so it is guaranteed to succeed. */ (void) UMF_create_element (Numeric, Work, Symbolic) ; Work->fnrows = 0 ; Work->fncols = 0 ; } } } /* ------------------------------------------------------------------ * Wrapup the current frontal matrix. This is the last in a chain * in the column elimination tree. The next frontal matrix * cannot overlap with the current one, which will be its sibling * in the column etree. * ------------------------------------------------------------------ */ UMF_blas3_update (Work) ; if (drop) { DO (UMF_store_lu_drop (Numeric, Work)) ; } else { DO (UMF_store_lu (Numeric, Work)) ; } Work->fnrows_new = Work->fnrows ; Work->fncols_new = Work->fncols ; DO (UMF_create_element (Numeric, Work, Symbolic)) ; /* ------------------------------------------------------------------ */ /* current front is now empty */ /* ------------------------------------------------------------------ */ Work->fnrows = 0 ; Work->fncols = 0 ; } /* ---------------------------------------------------------------------- */ /* end the last Lchain and Uchain and finalize the LU factors */ /* ---------------------------------------------------------------------- */ UMF_kernel_wrapup (Numeric, Symbolic, Work) ; /* note that the matrix may be singular (this is OK) */ return (UMFPACK_OK) ; }
gpl-3.0
pointhi/kicad-footprint-generator
KicadModTree/nodes/Node.py
6713
# KicadModTree 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. # # KicadModTree 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 kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >. # # (C) 2016 by Thomas Pointhuber, <[email protected]> from copy import copy, deepcopy from KicadModTree.Vector import * class MultipleParentsError(RuntimeError): def __init__(self, message): # Call the base class constructor with the parameters it needs super(MultipleParentsError, self).__init__(message) class RecursionDetectedError(RuntimeError): def __init__(self, message): # Call the base class constructor with the parameters it needs super(RecursionDetectedError, self).__init__(message) class Node(object): def __init__(self): self._parent = None self._childs = [] def append(self, node): ''' add node to child ''' if not isinstance(node, Node): raise TypeError('invalid object, has to be based on Node') if node._parent: raise MultipleParentsError('muliple parents are not allowed!') self._childs.append(node) node._parent = self def extend(self, nodes): ''' add list of nodes to child ''' new_nodes = [] for node in nodes: if not isinstance(node, Node): raise TypeError('invalid object, has to be based on Node') if node._parent or node in new_nodes: raise MultipleParentsError('muliple parents are not allowed!') new_nodes.append(node) # when all went smooth by now, we can set the parent nodes to ourself for node in new_nodes: node._parent = self self._childs.extend(new_nodes) def remove(self, node): ''' remove child from node ''' if not isinstance(node, Node): raise TypeError('invalid object, has to be based on Node') while node in self._childs: self._childs.remove(node) node._parent = None def insert(self, node): ''' moving all childs into the node, and using the node as new parent of those childs ''' if not isinstance(node, Node): raise TypeError('invalid object, has to be based on Node') for child in copy(self._childs): self.remove(child) node.append(child) self.append(node) def copy(self): copy = deepcopy(self) copy._parent = None return copy def serialize(self): nodes = [self] for child in self.getAllChilds(): nodes += child.serialize() return nodes def getNormalChilds(self): ''' Get all normal childs of this node ''' return self._childs def getVirtualChilds(self): ''' Get virtual childs of this node ''' return [] def getAllChilds(self): ''' Get virtual and normal childs of this node ''' return self.getNormalChilds() + self.getVirtualChilds() def getParent(self): ''' get Parent Node of this Node ''' return self._parent def getRootNode(self): ''' get Root Node of this Node ''' # TODO: recursion detection if not self.getParent(): return self return self.getParent().getRootNode() def getRealPosition(self, coordinate, rotation=None): ''' return position of point after applying all transformation and rotation operations ''' if not self._parent: if rotation is None: # TODO: most of the points are 2D Nodes return Vector3D(coordinate) else: return Vector3D(coordinate), rotation return self._parent.getRealPosition(coordinate, rotation) def calculateBoundingBox(self, outline=None): min_x, min_y = 0, 0 max_x, max_y = 0, 0 if outline: min_x = outline['min']['x'] min_y = outline['min']['y'] max_x = outline['max']['x'] max_y = outline['max']['y'] for child in self.getAllChilds(): child_outline = child.calculateBoundingBox() min_x = min([min_x, child_outline['min']['x']]) min_y = min([min_y, child_outline['min']['y']]) max_x = max([max_x, child_outline['max']['x']]) max_y = max([max_y, child_outline['max']['y']]) return {'min': Vector2D(min_x, min_y), 'max': Vector2D(max_x, max_y)} def _getRenderTreeText(self): ''' Text which is displayed when generating a render tree ''' return type(self).__name__ def _getRenderTreeSymbol(self): ''' Symbol which is displayed when generating a render tree ''' if self._parent is None: return "+" return "*" def getRenderTree(self, rendered_nodes=None): ''' print render tree ''' if rendered_nodes is None: rendered_nodes = set() if self in rendered_nodes: raise RecursionDetectedError('recursive definition of render tree!') rendered_nodes.add(self) tree_str = "{0} {1}".format(self._getRenderTreeSymbol(), self._getRenderTreeText()) for child in self.getNormalChilds(): tree_str += '\n ' tree_str += ' '.join(child.getRenderTree(rendered_nodes).splitlines(True)) return tree_str def getCompleteRenderTree(self, rendered_nodes=None): ''' print virtual render tree ''' if rendered_nodes is None: rendered_nodes = set() if self in rendered_nodes: raise RecursionDetectedError('recursive definition of render tree!') rendered_nodes.add(self) tree_str = "{0} {1}".format(self._getRenderTreeSymbol(), self._getRenderTreeText()) for child in self.getAllChilds(): tree_str += '\n ' tree_str += ' '.join(child.getCompleteRenderTree(rendered_nodes).splitlines(True)) return tree_str
gpl-3.0
Behzadkhosravifar/Alloy-DiagramBuilder-MVC
src/AlloyDiagram/Scripts/AlloyUi/calendar-base/lang/calendar-base_es.js
188
YUI.add("lang/calendar-base_es",function(e){e.Intl.add("calendar-base","es",{very_short_weekdays:["Do","Lu","Ma","Mi","Ju","Vi","Sa"],first_weekday:1,weekends:[0,6]})},"patched-v3.18.1");
gpl-3.0
rubenswagner/L2J-Global
dist/game/data/scripts/quests/Q10795_LettersFromTheQueenWallOfAgros/31279-01.html
250
<html><body>High Priest Gregory:<br> Aren't you an Ertheia? What brings you here?<br> <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h Quest Q10795_LettersFromTheQueenWallOfAgros 31279-02.html">"I got Queen Navari's letter."</button> </body></html>
gpl-3.0
brittybaby/3DModelfitting
dependencies/include/cinder/blocks/OpenCV/docs/html/structcv_1_1gpu_1_1device_1_1type__traits__detail_1_1_is_vec_3_01float8_01_4-members.html
2777
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Cinder</title> <link rel="stylesheet" href="cinder_doxygen.css" type="text/css" media="screen" /> </head> <body> <div class="wrapper"> <div id="header"> <h1><a href="http://libcinder.org">Cinder</a></h1> </div> <!-- Generated by Doxygen 1.8.7 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacecv.html">cv</a></li><li class="navelem"><a class="el" href="namespacecv_1_1gpu.html">gpu</a></li><li class="navelem"><a class="el" href="namespacecv_1_1gpu_1_1device.html">device</a></li><li class="navelem"><a class="el" href="namespacecv_1_1gpu_1_1device_1_1type__traits__detail.html">type_traits_detail</a></li><li class="navelem"><a class="el" href="structcv_1_1gpu_1_1device_1_1type__traits__detail_1_1_is_vec_3_01float8_01_4.html">IsVec< float8 ></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">cv::gpu::device::type_traits_detail::IsVec&lt; float8 &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structcv_1_1gpu_1_1device_1_1type__traits__detail_1_1_is_vec_3_01float8_01_4.html">cv::gpu::device::type_traits_detail::IsVec&lt; float8 &gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structcv_1_1gpu_1_1device_1_1type__traits__detail_1_1_is_vec_3_01float8_01_4.html#aa2656108a5e9db22c9fa8bb098cf59beab54407364f77fa1907791a09578b64b7">value</a> enum value</td><td class="entry"><a class="el" href="structcv_1_1gpu_1_1device_1_1type__traits__detail_1_1_is_vec_3_01float8_01_4.html">cv::gpu::device::type_traits_detail::IsVec&lt; float8 &gt;</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <div class="footer"> <p> </p> </div> </div> </body> </html>
gpl-3.0
waterlgndx/darkstar
scripts/globals/items/fish_mithkabob.lua
1252
----------------------------------------- -- ID: 4398 -- Item: fish_mithkabob -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 1 -- Vitality 2 -- Mind -1 -- Defense % 25 -- Defense Cap 90 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(dsp.effect.FOOD) == true or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4398); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, 1); target:addMod(dsp.mod.VIT, 2); target:addMod(dsp.mod.MND, -1); target:addMod(dsp.mod.FOOD_DEFP, 25); target:addMod(dsp.mod.FOOD_DEF_CAP, 90); end; function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 1); target:delMod(dsp.mod.VIT, 2); target:delMod(dsp.mod.MND, -1); target:delMod(dsp.mod.FOOD_DEFP, 25); target:delMod(dsp.mod.FOOD_DEF_CAP, 90); end;
gpl-3.0
lizardfs/lizardfs
src/admin/metadataserver_status_command.h
1232
/* Copyright 2013-2014 EditShare, 2013-2015 Skytechnology sp. z o.o. This file is part of LizardFS. LizardFS 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, version 3. LizardFS 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 LizardFS. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "common/platform.h" #include "common/server_connection.h" #include "admin/lizardfs_admin_command.h" struct MetadataserverStatus { std::string personality; std::string serverStatus; uint64_t metadataVersion; }; class MetadataserverStatusCommand : public LizardFsProbeCommand { public: std::string name() const override; void usage() const override; SupportedOptions supportedOptions() const override; void run(const Options& options) const override; static MetadataserverStatus getStatus(ServerConnection& connection); };
gpl-3.0
salamader/ffxi-a
src/map/entities/automatonentity.h
2179
/* =========================================================================== Copyright (c) 2010-2012 Darkstar Dev Teams This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ This file is part of DarkStar-server source code. =========================================================================== */ #ifndef _CAUTOMATONENTITY_H #define _CAUTOMATONENTITY_H #include "petentity.h" enum AUTOFRAMETYPE { FRAME_HARLEQUIN = 0x20, FRAME_VALOREDGE = 0x21, FRAME_SHARPSHOT = 0x22, FRAME_STORMWAKER = 0x23 }; enum AUTOHEADTYPE { HEAD_HARLEQUIN = 0x01, HEAD_VALOREDGE = 0x02, HEAD_SHARPSHOT = 0x03, HEAD_STORMWAKER = 0x04, HEAD_SOULSOOTHER = 0x05, HEAD_SPIRITREAVER = 0x06 }; struct automaton_equip_t { uint8 Frame; uint8 Head; uint8 Attachments[12]; }; class CCharEntity; class CAutomatonEntity : public CPetEntity { public: CAutomatonEntity(); ~CAutomatonEntity(); automaton_equip_t m_Equip; uint8 m_ElementMax[8]; uint8 m_ElementEquip[8]; void setFrame(AUTOFRAMETYPE frame); void setHead(AUTOHEADTYPE head); void setAttachment(uint8 slot, uint8 id); void setElementMax(uint8 element, uint8 max); void addElementCapacity(uint8 element, int8 value); AUTOFRAMETYPE getFrame(); AUTOHEADTYPE getHead(); uint8 getAttachment(uint8 slot); uint8 getElementMax(uint8 element); uint8 getElementCapacity(uint8 element); private: uint16 m_Burden[8]; }; #endif
gpl-3.0
FreeDao/getintouchmaps
OsmAnd/src/net/osmand/plus/resources/ResourceManager.java
35554
package net.osmand.plus.resources; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.text.Collator; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import net.osmand.AndroidUtils; import net.osmand.GeoidAltitudeCorrection; import net.osmand.IProgress; import net.osmand.IndexConstants; import net.osmand.Location; import net.osmand.PlatformUtil; import net.osmand.ResultMatcher; import net.osmand.binary.BinaryMapIndexReader; import net.osmand.binary.BinaryMapIndexReader.SearchPoiTypeFilter; import net.osmand.binary.CachedOsmandIndexes; import net.osmand.data.Amenity; import net.osmand.data.RotatedTileBox; import net.osmand.data.TransportStop; import net.osmand.map.ITileSource; import net.osmand.map.MapTileDownloader; import net.osmand.map.MapTileDownloader.DownloadRequest; import net.osmand.map.OsmandRegions; import net.osmand.osm.MapPoiTypes; import net.osmand.osm.PoiCategory; import net.osmand.plus.AppInitializer; import net.osmand.plus.AppInitializer.InitEvents; import net.osmand.plus.BusyIndicator; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; import net.osmand.plus.Version; import net.osmand.plus.render.MapRenderRepositories; import net.osmand.plus.render.NativeOsmandLibrary; import net.osmand.plus.resources.AsyncLoadingThread.MapLoadRequest; import net.osmand.plus.resources.AsyncLoadingThread.TileLoadDownloadRequest; import net.osmand.plus.resources.AsyncLoadingThread.TransportLoadRequest; import net.osmand.plus.srtmplugin.SRTMPlugin; import net.osmand.plus.views.OsmandMapLayer.DrawSettings; import net.osmand.util.Algorithms; import net.osmand.util.MapUtils; import org.apache.commons.logging.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.content.res.AssetManager; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.HandlerThread; import android.text.format.DateFormat; import android.util.DisplayMetrics; import android.view.WindowManager; /** * Resource manager is responsible to work with all resources * that could consume memory (especially with file resources). * Such as indexes, tiles. * Also it is responsible to create cache for that resources if they * can't be loaded fully into memory & clear them on request. */ public class ResourceManager { public static final String VECTOR_MAP = "#vector_map"; //$NON-NLS-1$ private static final String INDEXES_CACHE = "ind.cache"; private static final Log log = PlatformUtil.getLog(ResourceManager.class); protected static ResourceManager manager = null; // it is not good investigated but no more than 64 (satellite images) // Only 8 MB (from 16 Mb whole mem) available for images : image 64K * 128 = 8 MB (8 bit), 64 - 16 bit, 32 - 32 bit // at least 3*9? protected int maxImgCacheSize = 28; protected Map<String, Bitmap> cacheOfImages = new LinkedHashMap<String, Bitmap>(); protected Map<String, Boolean> imagesOnFS = new LinkedHashMap<String, Boolean>() ; protected File dirWithTiles ; private final OsmandApplication context; private BusyIndicator busyIndicator; public interface ResourceWatcher { public boolean indexResource(File f); public List<String> getWatchWorkspaceFolder(); } // Indexes private final Map<String, RegionAddressRepository> addressMap = new TreeMap<String, RegionAddressRepository>(Collator.getInstance()); protected final List<AmenityIndexRepository> amenityRepositories = new ArrayList<AmenityIndexRepository>(); protected final List<TransportIndexRepository> transportRepositories = new ArrayList<TransportIndexRepository>(); protected final Map<String, String> indexFileNames = new ConcurrentHashMap<String, String>(); protected final Map<String, String> basemapFileNames = new ConcurrentHashMap<String, String>(); protected final Map<String, BinaryMapIndexReader> routingMapFiles = new ConcurrentHashMap<String, BinaryMapIndexReader>(); protected final MapRenderRepositories renderer; protected final MapTileDownloader tileDownloader; public final AsyncLoadingThread asyncLoadingThread = new AsyncLoadingThread(this); private HandlerThread renderingBufferImageThread; protected boolean internetIsNotAccessible = false; private java.text.DateFormat dateFormat; public ResourceManager(OsmandApplication context) { this.context = context; this.renderer = new MapRenderRepositories(context); asyncLoadingThread.start(); renderingBufferImageThread = new HandlerThread("RenderingBaseImage"); renderingBufferImageThread.start(); tileDownloader = MapTileDownloader.getInstance(Version.getFullVersion(context)); dateFormat = DateFormat.getDateFormat(context); resetStoreDirectory(); WindowManager mgr = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); mgr.getDefaultDisplay().getMetrics(dm); // Only 8 MB (from 16 Mb whole mem) available for images : image 64K * 128 = 8 MB (8 bit), 64 - 16 bit, 32 - 32 bit // at least 3*9? float tiles = (dm.widthPixels / 256 + 2) * (dm.heightPixels / 256 + 2) * 3; log.info("Tiles to load in memory : " + tiles); maxImgCacheSize = (int) (tiles) ; } public MapTileDownloader getMapTileDownloader() { return tileDownloader; } public HandlerThread getRenderingBufferImageThread() { return renderingBufferImageThread; } public void resetStoreDirectory() { dirWithTiles = context.getAppPath(IndexConstants.TILES_INDEX_DIR); dirWithTiles.mkdirs(); // ".nomedia" indicates there are no pictures and no music to list in this dir for the Gallery app try { context.getAppPath(".nomedia").createNewFile(); //$NON-NLS-1$ } catch( Exception e ) { } } public java.text.DateFormat getDateFormat() { return dateFormat; } public OsmandApplication getContext() { return context; } ////////////////////////////////////////////// Working with tiles //////////////////////////////////////////////// public Bitmap getTileImageForMapAsync(String file, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded) { return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, false, true); } public synchronized Bitmap getTileImageFromCache(String file){ return cacheOfImages.get(file); } public synchronized void putTileInTheCache(String file, Bitmap bmp) { cacheOfImages.put(file, bmp); } public Bitmap getTileImageForMapSync(String file, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded) { return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, true, true); } public synchronized void tileDownloaded(DownloadRequest request){ if(request instanceof TileLoadDownloadRequest){ TileLoadDownloadRequest req = ((TileLoadDownloadRequest) request); imagesOnFS.put(req.tileId, Boolean.TRUE); /* if(req.fileToSave != null && req.tileSource instanceof SQLiteTileSource){ try { ((SQLiteTileSource) req.tileSource).insertImage(req.xTile, req.yTile, req.zoom, req.fileToSave); } catch (IOException e) { log.warn("File "+req.fileToSave.getName() + " couldn't be read", e); //$NON-NLS-1$//$NON-NLS-2$ } req.fileToSave.delete(); String[] l = req.fileToSave.getParentFile().list(); if(l == null || l.length == 0){ req.fileToSave.getParentFile().delete(); l = req.fileToSave.getParentFile().getParentFile().list(); if(l == null || l.length == 0){ req.fileToSave.getParentFile().getParentFile().delete(); } } }*/ } } public synchronized boolean tileExistOnFileSystem(String file, ITileSource map, int x, int y, int zoom){ if(!imagesOnFS.containsKey(file)){ boolean ex = false; if(map instanceof SQLiteTileSource){ if(((SQLiteTileSource) map).isLocked()){ return false; } ex = ((SQLiteTileSource) map).exists(x, y, zoom); } else { if(file == null){ file = calculateTileId(map, x, y, zoom); } ex = new File(dirWithTiles, file).exists(); } if (ex) { imagesOnFS.put(file, Boolean.TRUE); } else { imagesOnFS.put(file, null); } } return imagesOnFS.get(file) != null || cacheOfImages.get(file) != null; } public void clearTileImageForMap(String file, ITileSource map, int x, int y, int zoom){ getTileImageForMap(file, map, x, y, zoom, true, false, true, true); } /** * @param file - null could be passed if you do not call very often with that param */ protected Bitmap getTileImageForMap(String file, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded, boolean sync, boolean loadFromFs) { return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, sync, loadFromFs, false); } // introduce cache in order save memory protected StringBuilder builder = new StringBuilder(40); protected char[] tileId = new char[120]; private GeoidAltitudeCorrection geoidAltitudeCorrection; private boolean searchAmenitiesInProgress; public synchronized String calculateTileId(ITileSource map, int x, int y, int zoom) { builder.setLength(0); if (map == null) { builder.append(IndexConstants.TEMP_SOURCE_TO_LOAD); } else { builder.append(map.getName()); } if (map instanceof SQLiteTileSource) { builder.append('@'); } else { builder.append('/'); } builder.append(zoom).append('/').append(x).append('/').append(y). append(map == null ? ".jpg" : map.getTileFormat()).append(".tile"); //$NON-NLS-1$ //$NON-NLS-2$ return builder.toString(); } protected synchronized Bitmap getTileImageForMap(String tileId, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded, boolean sync, boolean loadFromFs, boolean deleteBefore) { if (tileId == null) { tileId = calculateTileId(map, x, y, zoom); if(tileId == null){ return null; } } if(deleteBefore){ cacheOfImages.remove(tileId); if (map instanceof SQLiteTileSource) { ((SQLiteTileSource) map).deleteImage(x, y, zoom); } else { File f = new File(dirWithTiles, tileId); if (f.exists()) { f.delete(); } } imagesOnFS.put(tileId, null); } if (loadFromFs && cacheOfImages.get(tileId) == null && map != null) { boolean locked = map instanceof SQLiteTileSource && ((SQLiteTileSource) map).isLocked(); if(!loadFromInternetIfNeeded && !locked && !tileExistOnFileSystem(tileId, map, x, y, zoom)){ return null; } String url = loadFromInternetIfNeeded ? map.getUrlToLoad(x, y, zoom) : null; File toSave = null; if (url != null) { if (map instanceof SQLiteTileSource) { toSave = new File(dirWithTiles, calculateTileId(((SQLiteTileSource) map).getBase(), x, y, zoom)); } else { toSave = new File(dirWithTiles, tileId); } } TileLoadDownloadRequest req = new TileLoadDownloadRequest(dirWithTiles, url, toSave, tileId, map, x, y, zoom); if(sync){ return getRequestedImageTile(req); } else { asyncLoadingThread.requestToLoadImage(req); } } return cacheOfImages.get(tileId); } protected Bitmap getRequestedImageTile(TileLoadDownloadRequest req){ if(req.tileId == null || req.dirWithTiles == null){ return null; } Bitmap cacheBmp = cacheOfImages.get(req.tileId); if (cacheBmp != null) { return cacheBmp; } if (cacheOfImages.size() > maxImgCacheSize) { clearTiles(); } if (req.dirWithTiles.canRead() && !asyncLoadingThread.isFileCurrentlyDownloaded(req.fileToSave) && !asyncLoadingThread.isFilePendingToDownload(req.fileToSave)) { long time = System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Start loaded file : " + req.tileId + " " + Thread.currentThread().getName()); //$NON-NLS-1$ //$NON-NLS-2$ } Bitmap bmp = null; if (req.tileSource instanceof SQLiteTileSource) { try { long[] tm = new long[1]; bmp = ((SQLiteTileSource) req.tileSource).getImage(req.xTile, req.yTile, req.zoom, tm); if (tm[0] != 0) { int ts = req.tileSource.getExpirationTimeMillis(); if (ts != -1 && req.url != null && time - tm[0] > ts) { asyncLoadingThread.requestToDownload(req); } } } catch (OutOfMemoryError e) { log.error("Out of memory error", e); //$NON-NLS-1$ clearTiles(); } } else { File en = new File(req.dirWithTiles, req.tileId); if (en.exists()) { try { bmp = BitmapFactory.decodeFile(en.getAbsolutePath()); int ts = req.tileSource.getExpirationTimeMillis(); if(ts != -1 && req.url != null && time - en.lastModified() > ts) { asyncLoadingThread.requestToDownload(req); } } catch (OutOfMemoryError e) { log.error("Out of memory error", e); //$NON-NLS-1$ clearTiles(); } } } if (bmp != null) { cacheOfImages.put(req.tileId, bmp); if (log.isDebugEnabled()) { log.debug("Loaded file : " + req.tileId + " " + -(time - System.currentTimeMillis()) + " ms " + cacheOfImages.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } if (cacheOfImages.get(req.tileId) == null && req.url != null) { asyncLoadingThread.requestToDownload(req); } } return cacheOfImages.get(req.tileId); } ////////////////////////////////////////////// Working with indexes //////////////////////////////////////////////// public List<String> reloadIndexesOnStart(AppInitializer progress, List<String> warnings){ close(); // check we have some assets to copy to sdcard warnings.addAll(checkAssets(progress)); progress.notifyEvent(InitEvents.ASSETS_COPIED); reloadIndexes(progress, warnings); progress.notifyEvent(InitEvents.MAPS_INITIALIZED); return warnings; } public List<String> reloadIndexes(IProgress progress, List<String> warnings) { geoidAltitudeCorrection = new GeoidAltitudeCorrection(context.getAppPath(null)); // do it lazy // indexingImageTiles(progress); warnings.addAll(indexingMaps(progress)); warnings.addAll(indexVoiceFiles(progress)); warnings.addAll(OsmandPlugin.onIndexingFiles(progress)); warnings.addAll(indexAdditionalMaps(progress)); return warnings; } public List<String> indexAdditionalMaps(IProgress progress) { return context.getAppCustomization().onIndexingFiles(progress, indexFileNames); } public List<String> indexVoiceFiles(IProgress progress){ File file = context.getAppPath(IndexConstants.VOICE_INDEX_DIR); file.mkdirs(); List<String> warnings = new ArrayList<String>(); if (file.exists() && file.canRead()) { File[] lf = file.listFiles(); if (lf != null) { for (File f : lf) { if (f.isDirectory()) { File conf = new File(f, "_config.p"); if (!conf.exists()) { conf = new File(f, "_ttsconfig.p"); } if (conf.exists()) { indexFileNames.put(f.getName(), dateFormat.format(conf.lastModified())); //$NON-NLS-1$ } } } } } return warnings; } private List<String> checkAssets(IProgress progress) { String fv = Version.getFullVersion(context); if (!fv.equalsIgnoreCase(context.getSettings().PREVIOUS_INSTALLED_VERSION.get())) { File applicationDataDir = context.getAppPath(null); applicationDataDir.mkdirs(); if (applicationDataDir.canWrite()) { try { progress.startTask(context.getString(R.string.installing_new_resources), -1); AssetManager assetManager = context.getAssets(); boolean isFirstInstall = context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals(""); unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall); context.getSettings().PREVIOUS_INSTALLED_VERSION.set(fv); copyRegionsBoundaries(); copyPoiTypes(); for (String internalStyle : context.getRendererRegistry().getInternalRenderers().keySet()) { File fl = context.getRendererRegistry().getFileForInternalStyle(internalStyle); if (fl.exists()) { context.getRendererRegistry().copyFileForInternalStyle(internalStyle); } } } catch (SQLiteException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } catch (XmlPullParserException e) { log.error(e.getMessage(), e); } } } return Collections.emptyList(); } private void copyRegionsBoundaries() { try { File file = context.getAppPath("regions.ocbf"); if (file != null) { FileOutputStream fout = new FileOutputStream(file); Algorithms.streamCopy(OsmandRegions.class.getResourceAsStream("regions.ocbf"), fout); fout.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } private void copyPoiTypes() { try { File file = context.getAppPath("poi_types.xml"); if (file != null) { FileOutputStream fout = new FileOutputStream(file); Algorithms.streamCopy(MapPoiTypes.class.getResourceAsStream("poi_types.xml"), fout); fout.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } private final static String ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall = "alwaysCopyOnFirstInstall"; private final static String ASSET_COPY_MODE__overwriteOnlyIfExists = "overwriteOnlyIfExists"; private final static String ASSET_COPY_MODE__alwaysOverwriteOrCopy = "alwaysOverwriteOrCopy"; private final static String ASSET_COPY_MODE__copyOnlyIfDoesNotExist = "copyOnlyIfDoesNotExist"; private void unpackBundledAssets(AssetManager assetManager, File appDataDir, IProgress progress, boolean isFirstInstall) throws IOException, XmlPullParserException { XmlPullParser xmlParser = XmlPullParserFactory.newInstance().newPullParser(); InputStream isBundledAssetsXml = assetManager.open("bundled_assets.xml"); xmlParser.setInput(isBundledAssetsXml, "UTF-8"); int next = 0; while ((next = xmlParser.next()) != XmlPullParser.END_DOCUMENT) { if (next == XmlPullParser.START_TAG && xmlParser.getName().equals("asset")) { final String source = xmlParser.getAttributeValue(null, "source"); final String destination = xmlParser.getAttributeValue(null, "destination"); final String combinedMode = xmlParser.getAttributeValue(null, "mode"); final String[] modes = combinedMode.split("\\|"); if(modes.length == 0) { log.error("Mode '" + combinedMode + "' is not valid"); continue; } String installMode = null; String copyMode = null; for(String mode : modes) { if(ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall.equals(mode)) installMode = mode; else if(ASSET_COPY_MODE__overwriteOnlyIfExists.equals(mode) || ASSET_COPY_MODE__alwaysOverwriteOrCopy.equals(mode) || ASSET_COPY_MODE__copyOnlyIfDoesNotExist.equals(mode)) copyMode = mode; else log.error("Mode '" + mode + "' is unknown"); } final File destinationFile = new File(appDataDir, destination); boolean unconditional = false; if(installMode != null) unconditional = unconditional || (ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall.equals(installMode) && isFirstInstall); if(copyMode == null) log.error("No copy mode was defined for " + source); unconditional = unconditional || ASSET_COPY_MODE__alwaysOverwriteOrCopy.equals(copyMode); boolean shouldCopy = unconditional; shouldCopy = shouldCopy || (ASSET_COPY_MODE__overwriteOnlyIfExists.equals(copyMode) && destinationFile.exists()); shouldCopy = shouldCopy || (ASSET_COPY_MODE__copyOnlyIfDoesNotExist.equals(copyMode) && !destinationFile.exists()); if(shouldCopy) copyAssets(assetManager, source, destinationFile); } } isBundledAssetsXml.close(); } public static void copyAssets(AssetManager assetManager, String assetName, File file) throws IOException { if(file.exists()){ Algorithms.removeAllFiles(file); } file.getParentFile().mkdirs(); InputStream is = assetManager.open(assetName, AssetManager.ACCESS_STREAMING); FileOutputStream out = new FileOutputStream(file); Algorithms.streamCopy(is, out); Algorithms.closeStream(out); Algorithms.closeStream(is); } private List<File> collectFiles(File dir, String ext, List<File> files) { if(dir.exists() && dir.canRead()) { File[] lf = dir.listFiles(); if(lf == null) { lf = new File[0]; } for (File f : lf) { if (f.getName().endsWith(ext)) { files.add(f); } } } return files; } public List<String> indexingMaps(final IProgress progress) { long val = System.currentTimeMillis(); ArrayList<File> files = new ArrayList<File>(); File appPath = context.getAppPath(null); collectFiles(appPath, IndexConstants.BINARY_MAP_INDEX_EXT, files); if(OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) != null) { collectFiles(context.getAppPath(IndexConstants.SRTM_INDEX_DIR), IndexConstants.BINARY_MAP_INDEX_EXT, files); } List<String> warnings = new ArrayList<String>(); renderer.clearAllResources(); CachedOsmandIndexes cachedOsmandIndexes = new CachedOsmandIndexes(); File indCache = context.getAppPath(INDEXES_CACHE); if (indCache.exists()) { try { cachedOsmandIndexes.readFromFile(indCache, CachedOsmandIndexes.VERSION); } catch (Exception e) { log.error(e.getMessage(), e); } } for (File f : files) { progress.startTask(context.getString(R.string.indexing_map) + " " + f.getName(), -1); //$NON-NLS-1$ try { BinaryMapIndexReader index = null; try { index = cachedOsmandIndexes.getReader(f); if (index.getVersion() != IndexConstants.BINARY_MAP_VERSION) { index = null; } if (index != null) { renderer.initializeNewResource(progress, f, index); } } catch (IOException e) { log.error(String.format("File %s could not be read", f.getName()), e); } if (index == null || (Version.isFreeVersion(context) && f.getName().contains("_wiki"))) { warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$ } else { if (index.isBasemap()) { basemapFileNames.put(f.getName(), f.getName()); } long dateCreated = index.getDateCreated(); if (dateCreated == 0) { dateCreated = f.lastModified(); } indexFileNames.put(f.getName(), dateFormat.format(dateCreated)); //$NON-NLS-1$ for (String rName : index.getRegionNames()) { // skip duplicate names (don't make collision between getName() and name in the map) // it can be dangerous to use one file to different indexes if it is multithreaded RegionAddressRepositoryBinary rarb = new RegionAddressRepositoryBinary(index, rName); addressMap.put(rName, rarb); } if (index.hasTransportData()) { try { RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$ transportRepositories.add(new TransportIndexRepositoryBinary(new BinaryMapIndexReader(raf, index))); } catch (IOException e) { log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$ warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$ } } if (index.containsRouteData()) { try { RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$ routingMapFiles.put(f.getAbsolutePath(), new BinaryMapIndexReader(raf, index)); } catch (IOException e) { log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$ warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$ } } if (index.containsPoiData()) { try { RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$ amenityRepositories.add(new AmenityIndexRepositoryBinary(new BinaryMapIndexReader(raf, index))); } catch (IOException e) { log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$ warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$ } } } } catch (SQLiteException e) { log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$ warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$ } catch (OutOfMemoryError oome) { log.error("Exception reading " + f.getAbsolutePath(), oome); //$NON-NLS-1$ warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_big_for_memory), f.getName())); } } log.debug("All map files initialized " + (System.currentTimeMillis() - val) + " ms"); if (files.size() > 0 && (!indCache.exists() || indCache.canWrite())) { try { cachedOsmandIndexes.writeToFile(indCache); } catch (Exception e) { log.error("Index file could not be written", e); } } return warnings; } public void initMapBoundariesCacheNative() { File indCache = context.getAppPath(INDEXES_CACHE); if (indCache.exists()) { NativeOsmandLibrary nativeLib = NativeOsmandLibrary.getLoadedLibrary(); if (nativeLib != null) { nativeLib.initCacheMapFile(indCache.getAbsolutePath()); } } } ////////////////////////////////////////////// Working with amenities //////////////////////////////////////////////// public List<Amenity> searchAmenities(SearchPoiTypeFilter filter, double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude, int zoom, final ResultMatcher<Amenity> matcher) { final List<Amenity> amenities = new ArrayList<Amenity>(); searchAmenitiesInProgress = true; try { if (!filter.isEmpty()) { for (AmenityIndexRepository index : amenityRepositories) { if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) { List<Amenity> r = index.searchAmenities(MapUtils.get31TileNumberY(topLatitude), MapUtils.get31TileNumberX(leftLongitude), MapUtils.get31TileNumberY(bottomLatitude), MapUtils.get31TileNumberX(rightLongitude), zoom, filter, matcher); if(r != null) { amenities.addAll(r); } } } } } finally { searchAmenitiesInProgress = false; } return amenities; } public List<Amenity> searchAmenitiesOnThePath(List<Location> locations, double radius, SearchPoiTypeFilter filter, ResultMatcher<Amenity> matcher) { searchAmenitiesInProgress = true; final List<Amenity> amenities = new ArrayList<Amenity>(); try { if (locations != null && locations.size() > 0) { List<AmenityIndexRepository> repos = new ArrayList<AmenityIndexRepository>(); double topLatitude = locations.get(0).getLatitude(); double bottomLatitude = locations.get(0).getLatitude(); double leftLongitude = locations.get(0).getLongitude(); double rightLongitude = locations.get(0).getLongitude(); for (Location l : locations) { topLatitude = Math.max(topLatitude, l.getLatitude()); bottomLatitude = Math.min(bottomLatitude, l.getLatitude()); leftLongitude = Math.min(leftLongitude, l.getLongitude()); rightLongitude = Math.max(rightLongitude, l.getLongitude()); } if (!filter.isEmpty()) { for (AmenityIndexRepository index : amenityRepositories) { if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) { repos.add(index); } } if (!repos.isEmpty()) { for (AmenityIndexRepository r : repos) { List<Amenity> res = r.searchAmenitiesOnThePath(locations, radius, filter, matcher); if(res != null) { amenities.addAll(res); } } } } } } finally { searchAmenitiesInProgress = false; } return amenities; } public boolean containsAmenityRepositoryToSearch(boolean searchByName){ for (AmenityIndexRepository index : amenityRepositories) { if(searchByName){ if(index instanceof AmenityIndexRepositoryBinary){ return true; } } else { return true; } } return false; } public List<Amenity> searchAmenitiesByName(String searchQuery, double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude, double lat, double lon, ResultMatcher<Amenity> matcher) { List<Amenity> amenities = new ArrayList<Amenity>(); List<AmenityIndexRepositoryBinary> list = new ArrayList<AmenityIndexRepositoryBinary>(); for (AmenityIndexRepository index : amenityRepositories) { if (index instanceof AmenityIndexRepositoryBinary) { if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) { if(index.checkContains(lat, lon)){ list.add(0, (AmenityIndexRepositoryBinary) index); } else { list.add((AmenityIndexRepositoryBinary) index); } } } } for (AmenityIndexRepositoryBinary index : list) { if (matcher != null && matcher.isCancelled()) { break; } List<Amenity> result = index.searchAmenitiesByName(MapUtils.get31TileNumberX(lon), MapUtils.get31TileNumberY(lat), MapUtils.get31TileNumberX(leftLongitude), MapUtils.get31TileNumberY(topLatitude), MapUtils.get31TileNumberX(rightLongitude), MapUtils.get31TileNumberY(bottomLatitude), searchQuery, matcher); amenities.addAll(result); } return amenities; } public Map<PoiCategory, List<String>> searchAmenityCategoriesByName(String searchQuery, double lat, double lon) { Map<PoiCategory, List<String>> map = new LinkedHashMap<PoiCategory, List<String>>(); for (AmenityIndexRepository index : amenityRepositories) { if (index instanceof AmenityIndexRepositoryBinary) { if (index.checkContains(lat, lon)) { ((AmenityIndexRepositoryBinary) index).searchAmenityCategoriesByName(searchQuery, map); } } } return map; } ////////////////////////////////////////////// Working with address /////////////////////////////////////////// public RegionAddressRepository getRegionRepository(String name){ return addressMap.get(name); } public Collection<RegionAddressRepository> getAddressRepositories(){ return addressMap.values(); } ////////////////////////////////////////////// Working with transport //////////////////////////////////////////////// public List<TransportIndexRepository> searchTransportRepositories(double latitude, double longitude) { List<TransportIndexRepository> repos = new ArrayList<TransportIndexRepository>(); for (TransportIndexRepository index : transportRepositories) { if (index.checkContains(latitude,longitude)) { repos.add(index); } } return repos; } public void searchTransportAsync(double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude, int zoom, List<TransportStop> toFill){ List<TransportIndexRepository> repos = new ArrayList<TransportIndexRepository>(); for (TransportIndexRepository index : transportRepositories) { if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) { if (!index.checkCachedObjects(topLatitude, leftLongitude, bottomLatitude, rightLongitude, zoom, toFill, true)) { repos.add(index); } } } if(!repos.isEmpty()){ TransportLoadRequest req = asyncLoadingThread.new TransportLoadRequest(repos, zoom); req.setBoundaries(topLatitude, leftLongitude, bottomLatitude, rightLongitude); asyncLoadingThread.requestToLoadTransport(req); } } ////////////////////////////////////////////// Working with map //////////////////////////////////////////////// public boolean updateRenderedMapNeeded(RotatedTileBox rotatedTileBox, DrawSettings drawSettings) { return renderer.updateMapIsNeeded(rotatedTileBox, drawSettings); } public void updateRendererMap(RotatedTileBox rotatedTileBox){ renderer.interruptLoadingMap(); asyncLoadingThread.requestToLoadMap(new MapLoadRequest(rotatedTileBox)); } public void interruptRendering(){ renderer.interruptLoadingMap(); } public boolean isSearchAmenitiesInProgress() { return searchAmenitiesInProgress; } public MapRenderRepositories getRenderer() { return renderer; } ////////////////////////////////////////////// Closing methods //////////////////////////////////////////////// public void closeAmenities(){ for(AmenityIndexRepository r : amenityRepositories){ r.close(); } amenityRepositories.clear(); } public void closeAddresses(){ for(RegionAddressRepository r : addressMap.values()){ r.close(); } addressMap.clear(); } public void closeTransport(){ for(TransportIndexRepository r : transportRepositories){ r.close(); } transportRepositories.clear(); } public BusyIndicator getBusyIndicator() { return busyIndicator; } public synchronized void setBusyIndicator(BusyIndicator busyIndicator) { this.busyIndicator = busyIndicator; } public synchronized void close(){ imagesOnFS.clear(); indexFileNames.clear(); basemapFileNames.clear(); renderer.clearAllResources(); closeAmenities(); closeRouteFiles(); closeAddresses(); closeTransport(); } public BinaryMapIndexReader[] getRoutingMapFiles() { return routingMapFiles.values().toArray(new BinaryMapIndexReader[routingMapFiles.size()]); } public void closeRouteFiles() { List<String> map = new ArrayList<String>(routingMapFiles.keySet()); for(String m : map){ try { BinaryMapIndexReader ind = routingMapFiles.remove(m); if(ind != null){ ind.getRaf().close(); } } catch(IOException e){ log.error("Error closing resource " + m, e); } } } public Map<String, String> getIndexFileNames() { return new LinkedHashMap<String, String>(indexFileNames); } public boolean containsBasemap(){ return !basemapFileNames.isEmpty(); } public Map<String, String> getBackupIndexes(Map<String, String> map) { File file = context.getAppPath(IndexConstants.BACKUP_INDEX_DIR); if (file != null && file.isDirectory()) { File[] lf = file.listFiles(); if (lf != null) { for (File f : lf) { if (f != null && f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { map.put(f.getName(), AndroidUtils.formatDate(context, f.lastModified())); //$NON-NLS-1$ } } } } return map; } public synchronized void reloadTilesFromFS(){ imagesOnFS.clear(); } /// On low memory method /// public void onLowMemory() { log.info("On low memory : cleaning tiles - size = " + cacheOfImages.size()); //$NON-NLS-1$ clearTiles(); for(RegionAddressRepository r : addressMap.values()){ r.clearCache(); } renderer.clearCache(); System.gc(); } public GeoidAltitudeCorrection getGeoidAltitudeCorrection() { return geoidAltitudeCorrection; } public OsmandRegions getOsmandRegions() { return context.getRegions(); } protected synchronized void clearTiles() { log.info("Cleaning tiles - size = " + cacheOfImages.size()); //$NON-NLS-1$ ArrayList<String> list = new ArrayList<String>(cacheOfImages.keySet()); // remove first images (as we think they are older) for (int i = 0; i < list.size() / 2; i++) { cacheOfImages.remove(list.get(i)); } } }
gpl-3.0
IceExchange/ice-headless-client
src/main/resources/db/migration/sqlite/V1__Initial_model.sql
1758
CREATE TABLE IF NOT EXISTS bot_sessions ( eth_address TEXT, data JSON, PRIMARY KEY(eth_address) ); CREATE TABLE IF NOT EXISTS key_value_store ( key TEXT, value TEXT, type TEXT, PRIMARY KEY(key) ); CREATE TABLE IF NOT EXISTS local_identities ( eth_address TEXT, device_id INTEGER DEFAULT 0, password TEXT, identity_key BLOB, registration_id INTEGER, signaling_key BLOB, prekey_id_offset INTEGER DEFAULT 0, next_signed_prekey_id INTEGER DEFAULT 0, registered BOOLEAN DEFAULT FALSE, PRIMARY KEY (eth_address) ); -- signal protocol store CREATE TABLE IF NOT EXISTS signal_identity_store ( name TEXT, device_id INTEGER, identity_key BLOB, updated BOOLEAN DEFAULT FALSE, PRIMARY KEY (name, device_id) ); CREATE TABLE IF NOT EXISTS signal_prekey_store ( prekey_id INTEGER, record BLOB, PRIMARY KEY (prekey_id) ); CREATE TABLE IF NOT EXISTS signal_session_store ( name TEXT, device_id INTEGER, record BLOB, PRIMARY KEY (name, device_id) ); CREATE TABLE IF NOT EXISTS signal_signed_prekey_store ( signed_prekey_id INTEGER, record BLOB, PRIMARY KEY (signed_prekey_id) ); -- contacts CREATE TABLE IF NOT EXISTS contacts_store ( number TEXT, name TEXT, color TEXT, PRIMARY KEY (number) ); CREATE TABLE IF NOT EXISTS thread_store ( thread_id TEXT, message_expiration_time INT, PRIMARY KEY (thread_id) ); CREATE TABLE IF NOT EXISTS group_store ( user_id SERIAL, group_id BLOB, name TEXT, avatar_id BIGINT, active BOOLEAN, PRIMARY KEY (group_id) ); CREATE TABLE IF NOT EXISTS group_members_store ( group_id BLOB, number TEXT, PRIMARY KEY (group_id, number) );
gpl-3.0
joaquinaimar/wizard
99 backup/02 source-20131113/wizard-web-esm/src/main/java/com/wizard/web/application/manage/permission/service/PermissionManageService.java
503
package com.wizard.web.application.manage.permission.service; import java.util.List; import java.util.Map; import com.wizard.web.application.manage.permission.bean.Menu; import com.wizard.web.basic.io.PageResponse; import com.wizard.web.basic.io.extjs.ExtPageRequest; public interface PermissionManageService { public PageResponse<Menu> searchMenu(ExtPageRequest request); public Map<String, List<String>> getAuthority(); public void doSaveAuthority(Map<String, List<String>> map); }
gpl-3.0
tchoulihan/referendum
src/main/java/com/referendum/voting/results/MultipleWinnerElectionResults.java
480
package com.referendum.voting.results; import java.util.List; import com.referendum.voting.ballot.RankedBallot; import com.referendum.voting.election.ElectionRound; public interface MultipleWinnerElectionResults extends ElectionResults { List<ElectionRound> getRounds(); List<RankedBallot> getBallots(); Integer getThreshold(Integer votes, Integer seats); default ElectionResultsType getElectionResultsType() { return ElectionResultsType.MULTIPLE_WINNER; } }
gpl-3.0
jwiegley/ghc-release
libraries/time/test/TestEaster.hs
1090
{-# OPTIONS -Wall -Werror #-} module Test.TestEaster where import Data.Time.Calendar.Easter import Data.Time.Calendar import Data.Time.Format import System.Locale import Test.TestUtil import Test.TestEasterRef -- days :: [Day] days = [ModifiedJulianDay 53000 .. ModifiedJulianDay 53014] showWithWDay :: Day -> String showWithWDay = formatTime defaultTimeLocale "%F %A" testEaster :: Test testEaster = pureTest "testEaster" $ let ds = unlines $ map (\day -> unwords [ showWithWDay day, "->" , showWithWDay (sundayAfter day)]) days f y = unwords [ show y ++ ", Gregorian: moon," , show (gregorianPaschalMoon y) ++ ": Easter," , showWithWDay (gregorianEaster y)] ++ "\n" g y = unwords [ show y ++ ", Orthodox : moon," , show (orthodoxPaschalMoon y) ++ ": Easter," , showWithWDay (orthodoxEaster y)] ++ "\n" in diff testEasterRef $ ds ++ concatMap (\y -> f y ++ g y) [2000..2020]
gpl-3.0
laszlodaniel/ChryslerCCDSCIScanner
GUI/ChryslerCCDSCIScanner/DB/Converters/BinaryStateConverter.cs
2440
/* * DRBDBReader * Copyright (C) 2016-2017, Kyle Repinski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using DRBDBReader.DB.Records; namespace DRBDBReader.DB.Converters { public class BinaryStateConverter : StateConverter { public BDSRecord bdsRecord; public BinaryStateConverter( Database db, byte[] record, ushort cfid, ushort dsid ) : base( db, record, cfid, dsid ) { } protected override void buildStateList() { Table bdsTable = this.db.tables[Database.TABLE_BINARY_DATA_SPECIFIER]; this.dsRecord = bdsTable.getRecord( this.dsid ); this.bdsRecord = (BDSRecord)this.dsRecord; this.entries.Add( 0, bdsRecord.falseString ); this.entries.Add( 1, bdsRecord.trueString ); } protected override ushort getEntryID( ushort val ) { switch( this.scRecord.op ) { case Operator.GREATER: return (ushort)( val > this.scRecord.mask ? 1 : 0 ); case Operator.LESS: return (ushort)( val < this.scRecord.mask ? 1 : 0 ); case Operator.MASK_ZERO: return (ushort)( ( val & this.scRecord.mask ) == 0 ? 1 : 0 ); case Operator.MASK_NOT_ZERO: return (ushort)( ( val & this.scRecord.mask ) != 0 ? 1 : 0 ); case Operator.NOT_EQUAL: return (ushort)( val != this.scRecord.mask ? 1 : 0 ); case Operator.EQUAL: default: return (ushort)( val == this.scRecord.mask ? 1 : 0 ); } } public override string ToString() { string ret = base.ToString() + Environment.NewLine; ret = ret.Replace( Environment.NewLine + "0x00: ", Environment.NewLine + "FALSE: " ); ret = ret.Replace( Environment.NewLine + "0x01: ", Environment.NewLine + "TRUE: " ); ret += Environment.NewLine + "MASK: 0x" + this.scRecord.mask.ToString( "X2" ); ret += Environment.NewLine + "OP: " + this.scRecord.op.ToString(); return ret; } } }
gpl-3.0
bixuanzju/full-version
src/Translation.hs
5168
module Translation where import Control.Monad (unless, mapAndUnzipM) import Control.Monad.Except (throwError) import Control.Arrow (second) -- import Parser -- import Debug.Trace import Expr import Syntax import TypeCheck import Utils -- | Elaboration trans :: Env -> Expr -> TC (Type, Expr) trans _ (Kind Star) = return (Kind Star, Kind Star) trans env (Var s) = findVar env s >>= \t -> return (t, Var s) trans env (App f a) = do (tf, f') <- trans env f case tf of Pi x at rt -> do (ta, a') <- trans env a unless (alphaEq ta at) $ throwError "Bad function argument type" return (subst x a rt, App f' a') _ -> throwError "Non-function in application" trans env (Lam s t e) = do let env' = extend s t env (te, e') <- trans env' e let lt = Pi s t te (_, Pi _ t' _) <- trans env lt return (lt, Lam s t' e') trans env (Pi x a b) = do (s, a') <- trans env a let env' = extend x a env (t, b') <- trans env' b unless (alphaEq t (Kind Star) && alphaEq s (Kind Star)) $ throwError "Bad abstraction" return (t, Pi x a' b') trans env (Mu i t e) = do let env' = extend i t env (te, e') <- trans env' e unless (alphaEq t te) $ throwError "Bad recursive type" (_, t') <- trans env t return (t, Mu i t' e') -- Note that in the surface language, casts should not appear. -- Here we return as it is trans _ (F n t1 e) = do return (t1, F n t1 e) trans env (U n e) = do (t1, _) <- trans env e t2 <- reductN n t1 return (t2, U n e) -- TODO: Lack 1) exhaustive test 2) overlap test trans env (Case e alts) = do (dv, e') <- trans env e actualTypes <- fmap reverse (getActualTypes dv) let arity = length actualTypes (altTypeList, e2List) <- mapAndUnzipM (transPattern dv actualTypes) alts unless (all (alphaEq . head $ altTypeList) (tail altTypeList)) $ throwError "Bad pattern expressions" let (Pi "" _ t) = head . filter (\(Pi "" _ t') -> t' /= Error) $ altTypeList let genExpr = foldl App (App (U (arity + 1) e') t) e2List return (t, genExpr) where transPattern :: Type -> [Type] -> Alt -> TC (Type, Expr) transPattern dv tys (Alt (PConstr constr params) body) = do let k = constrName constr (kt, _) <- trans env (Var k) -- check patterns, quite hacky let tcApp = foldl App (Var "dummy$") (tys ++ map (Var . fst) params) (typ, _) <- trans (("dummy$", kt) : params ++ env) tcApp unless (alphaEq typ dv) $ throwError "Bad patterns" (bodyType, body') <- trans (params ++ env) body return (arr dv bodyType, genLambdas params body') trans env (Data db@(DB tc tca constrs) e) = do env' <- tcdatatypes env db let nenv = env' ++ env (t, e') <- trans nenv e let tct = mkProdType (Kind Star) tca let du = foldl App (Var tc) (map (Var . fst) tca) let dcArgs = map constrParams constrs let dcArgChains = map (mkProdType (Var "B0")) dcArgs let transTC' = map (mkProdType (Var "B0") . map (second (substVar tc "X"))) dcArgs let transTC = (tc, (tct, Mu "X" tct (genLambdas tca (Pi "B0" (Kind Star) (chainType (Var "B0") transTC'))))) let tduList = map (mkProdType du . constrParams) constrs let dctList = map (`mkProdType` tca) tduList let arity = length tca let transDC = zip (map constrName constrs) (zip dctList (map (\(i, taus) -> let cs = genVarsAndTypes 'c' dcArgChains in genLambdas tca (genLambdas taus (F (arity + 1) du (Lam "B0" (Kind Star) (genLambdas cs (foldl App (Var ('c' : show i)) (map (Var . fst) taus))))))) (zip [0 :: Int ..] dcArgs))) return (t, foldr (\(n, (kt, ke)) body -> Let n kt ke body) e' (transTC : transDC)) trans _ Nat = return (Kind Star, Nat) trans _ n@(Lit _) = return (Nat, n) trans env (Add e1 e2) = do (t1, e1') <- trans env e1 (t2, e2') <- trans env e2 unless (t1 == Nat && t2 == Nat) $ throwError "Addition is only allowed for numbers!" return (Nat, Add e1' e2') trans _ Error = return (Error, Error) trans _ e = throwError $ "Trans: Impossible happened, trying to translate: " ++ show e -- | type check datatype tcdatatypes :: Env -> DataBind -> TC Env tcdatatypes env (DB tc tca constrs) = do -- check type constructor let tct = mkProdType (Kind Star) tca tcs <- tcheck env tct unless (tcs == Kind Star) $ throwError "Bad type constructor arguments" -- check data constructors let du = foldl App (Var tc) (map (Var . fst) tca) let tduList = map (mkProdType du . constrParams) constrs dcts <- mapM (tcheck (reverse tca ++ ((tc, tct) : env))) tduList -- Note: reverse type parameters list (tca) unless (all (== Kind Star) dcts) $ throwError "Bad data constructor arguments" -- return environment containing type constructor and data constructors let dctList = map (\tdu -> foldr (\(u, k) t -> Pi u k t) tdu tca) tduList return ((tc, tct) : zip (map constrName constrs) dctList)
gpl-3.0
SrNativee/BotDeUmBot
node_modules/cleverbot-node/lib/cleverbot.js
2085
var http = require('https') , qs = require('querystring') , Cleverbot = function (options) { this.configure(options); }; Cleverbot.prepare = function(cb){ // noop for backwards compatibility cb(); }; Cleverbot.prototype = { configure: function (options){ if(options && options.constructor !== Object){ throw new TypeError("Cleverbot must be configured with an Object"); } this.options = options || {}; }, path: function(message){ var path = '/getreply' , query = { input: JSON.stringify(message), key: this.options.botapi || "CHANGEME" }; if(this.state) { query.cs = this.state; } return [path, qs.stringify(query)].join("?"); }, write: function (message, callback, errorCallback) { var clever = this; var body = this.params; var options = { host: 'www.cleverbot.com', port: 443, path: this.path(message), method: 'GET', headers: { 'Content-Type': 'text/javascript' } }; var cb = callback || function() { }; var err = errorCallback || function() {}; var req = http.request(options, function (res) { var chunks = []; res.on("data", function(data) { chunks.push(data); }); res.on("end", function(i) { var body = Buffer.concat(chunks).toString(); var responseBody; try{ responseBody = JSON.parse(body); } catch(e) { try{ eval("responseBody = " + body); } catch(e) { err(e, message, body); return; } } responseBody.message = responseBody.output; //for backwards compatibility this.state = responseBody.cs; cb(responseBody); }.bind(this)); }.bind(this)); req.end(); } }; module.exports = Cleverbot;
gpl-3.0
tbrooks8/quasar
quasar-core/src/main/java/co/paralleluniverse/strands/CheckedSuspendableCallable.java
1178
/* * Quasar: lightweight threads and actors for the JVM. * Copyright (c) 2013-2015, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 3.0 * as published by the Free Software Foundation. */ package co.paralleluniverse.strands; import co.paralleluniverse.fibers.SuspendExecution; /** * This interface can represent any operation that may suspend the currently executing {@link Strand} (i.e. thread or fiber). * Unlike {@link SuspendableRunnable}, the operation represented by this interface returns a result. * This is just like a {@link java.util.concurrent.Callable}, only suspendable. * * @author circlespainter * * @param <V> The value being returned. * @param <E> The user exception type being thrown. */ public interface CheckedSuspendableCallable<V, E extends Exception> extends java.io.Serializable { V call() throws SuspendExecution, InterruptedException, E; }
gpl-3.0
Adriqun/Assassin-s-Genesis
states/editor/eatools.h
1552
#pragma once #include "circlebutton.h" #include "eakind.h" #include "eadetails.h" class EATools final : public EAKind { int screen_w; int screen_h; enum TYPES { DELETEKEY = 0, HOTKEY, WHOLECOLLISIONKEY, COUNT }; std::vector<CircleButton*> buttons; std::vector<cmm::Text*> texts; std::vector<bool> pressed; std::vector<int> states; std::vector<int> keys; // mark the chosen entity's element sf::RectangleShape shape; cmm::Sprite checkedIcon; // ctrl + z bool ctrl_key; bool z_key; float undoKeyCounter; float undoKeyState; // support bool change; bool redBack; // hot key float hotKeyCounter; float hotKeyState; public: EADetails details; EATools(); ~EATools(); void free(); void reset(); void load(const float& screen_w, const float& screen_h); void handle(const sf::Event &event, const int &amount); void draw(sf::RenderWindow* &window); void thumbnail(sf::RenderWindow* &window, std::vector<cmm::Sprite*> &factory, const int& chosen); void mechanics(const float &elapsedTime); bool isDeleteKeyPressed() const { return pressed[DELETEKEY]; } bool isHotKeyPressed() const { return pressed[HOTKEY] || (states[HOTKEY] && pressed[DELETEKEY]); } bool isWholeCollisionKeyPressed() const { return pressed[WHOLECOLLISIONKEY]; } bool isHotKeyElapsed(); bool isUndoKeyElapsed(); bool isDeleteMode() const { return states[DELETEKEY] != 0; } bool isChange(); bool& isRedBack() { return redBack; } const int& getType() const { return type; } const int& getChosen() const { return chosen; } };
gpl-3.0
tomahawk-player/tomahawk
src/libtomahawk/resolvers/JSResolverHelper.h
4863
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2010-2014, Christian Muehlhaeuser <[email protected]> * Copyright 2010-2011, Leo Franchi <[email protected]> * Copyright 2013, Teo Mrnjavac <[email protected]> * Copyright 2013, Uwe L. Korn <[email protected]> * * Tomahawk 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. * * Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ #ifndef JSRESOLVERHELPER_H #define JSRESOLVERHELPER_H #include "DllMacro.h" #include "Typedefs.h" #include "UrlHandler.h" #include "database/fuzzyindex/FuzzyIndex.h" #include "utils/NetworkReply.h" #include <QObject> #include <QVariantMap> #include <functional> Q_DECLARE_METATYPE( std::function< void( QSharedPointer< QIODevice >& ) > ) namespace Tomahawk { class JSResolver; class DLLEXPORT JSResolverHelper : public QObject { Q_OBJECT public: JSResolverHelper( const QString& scriptPath, JSResolver* parent ); /** * INTERNAL USE ONLY! */ void setResolverConfig( const QVariantMap& config ); void start(); void stop(); /** * Get the instance unique account id for this resolver. * * INTERNAL USE ONLY! */ Q_INVOKABLE QString accountId(); /** * Make Tomahawk assert the assertion is true, probably not to be used by resolvers directly */ Q_INVOKABLE void nativeAssert( bool assertion, const QString& message = QString() ); /** * Retrieve metadata for a media stream. * * Current suported transport protocols are: * * HTTP * * HTTPS * * This method is asynchronous and will call * Tomahawk.retrievedMetadata(metadataId, metadata, error) * on completion. This method is an internal variant, JavaScript resolvers * are advised to use Tomahawk.retrieveMetadata(url, options, callback). * * INTERNAL USE ONLY! */ Q_INVOKABLE void nativeRetrieveMetadata( int metadataId, const QString& url, const QString& mimetype, int sizehint, const QVariantMap& options ); Q_INVOKABLE void invokeNativeScriptJob( int requestId, const QString& methodName, const QVariantMap& params ); /** * Lucene++ indices for JS resolvers **/ Q_INVOKABLE bool hasFuzzyIndex(); Q_INVOKABLE void createFuzzyIndex( const QVariantList& list ); Q_INVOKABLE void addToFuzzyIndex( const QVariantList& list ); Q_INVOKABLE QVariantList searchFuzzyIndex( const QString& query ); Q_INVOKABLE QVariantList resolveFromFuzzyIndex( const QString& artist, const QString& album, const QString& tracks ); Q_INVOKABLE void deleteFuzzyIndex(); /** * This is horrible, we can use it to invalidate resolver results when the config changes * TODO: register the resolver through registerPlugin and remove it through standard methods */ Q_INVOKABLE void readdResolver(); public slots: QByteArray readRaw( const QString& fileName ); QString readBase64( const QString& fileName ); QString readCompressed( const QString& fileName ); QString uuid() const; int currentCountry() const; QString compress( const QString& data ); QVariantMap resolverData(); void log( const QString& message ); bool fakeEnv() { return false; } void nativeReportCapabilities( const QVariant& capabilities ); void reportScriptJobResults( const QVariantMap& result ); void registerScriptPlugin( const QString& type, const QString& objectId ); void unregisterScriptPlugin( const QString& type, const QString& objectId ); private slots: void nativeAsyncRequestDone( int requestId, NetworkReply* reply ); private: bool indexDataFromVariant( const QVariantMap& map, struct Tomahawk::IndexData& indexData ); QVariantList searchInFuzzyIndex( const Tomahawk::query_ptr& query ); // native script jobs void nativeAsyncRequest( int requestId, const QVariantMap& options ); QVariantMap m_resolverConfig; JSResolver* m_resolver; QString m_scriptPath; bool m_stopped; }; } // ns: Tomahawk #endif // JSRESOLVERHELPER_H
gpl-3.0
jiachenning/fibjs
vender/src/v8/src/bignum-dtoa.cc
26817
// Copyright 2011 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cmath> #include "../include/v8stdint.h" #include "checks.h" #include "utils.h" #include "bignum-dtoa.h" #include "bignum.h" #include "double.h" namespace v8 { namespace internal { static int NormalizedExponent(uint64_t significand, int exponent) { ASSERT(significand != 0); while ((significand & Double::kHiddenBit) == 0) { significand = significand << 1; exponent = exponent - 1; } return exponent; } // Forward declarations: // Returns an estimation of k such that 10^(k-1) <= v < 10^k. static int EstimatePower(int exponent); // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator // and denominator. static void InitialScaledStartValues(double v, int estimated_power, bool need_boundary_deltas, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus); // Multiplies numerator/denominator so that its values lies in the range 1-10. // Returns decimal_point s.t. // v = numerator'/denominator' * 10^(decimal_point-1) // where numerator' and denominator' are the values of numerator and // denominator after the call to this function. static void FixupMultiply10(int estimated_power, bool is_even, int* decimal_point, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus); // Generates digits from the left to the right and stops when the generated // digits yield the shortest decimal representation of v. static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus, bool is_even, Vector<char> buffer, int* length); // Generates 'requested_digits' after the decimal point. static void BignumToFixed(int requested_digits, int* decimal_point, Bignum* numerator, Bignum* denominator, Vector<char>(buffer), int* length); // Generates 'count' digits of numerator/denominator. // Once 'count' digits have been produced rounds the result depending on the // remainder (remainders of exactly .5 round upwards). Might update the // decimal_point when rounding up (for example for 0.9999). static void GenerateCountedDigits(int count, int* decimal_point, Bignum* numerator, Bignum* denominator, Vector<char>(buffer), int* length); void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits, Vector<char> buffer, int* length, int* decimal_point) { ASSERT(v > 0); ASSERT(!Double(v).IsSpecial()); uint64_t significand = Double(v).Significand(); bool is_even = (significand & 1) == 0; int exponent = Double(v).Exponent(); int normalized_exponent = NormalizedExponent(significand, exponent); // estimated_power might be too low by 1. int estimated_power = EstimatePower(normalized_exponent); // Shortcut for Fixed. // The requested digits correspond to the digits after the point. If the // number is much too small, then there is no need in trying to get any // digits. if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) { buffer[0] = '\0'; *length = 0; // Set decimal-point to -requested_digits. This is what Gay does. // Note that it should not have any effect anyways since the string is // empty. *decimal_point = -requested_digits; return; } Bignum numerator; Bignum denominator; Bignum delta_minus; Bignum delta_plus; // Make sure the bignum can grow large enough. The smallest double equals // 4e-324. In this case the denominator needs fewer than 324*4 binary digits. // The maximum double is 1.7976931348623157e308 which needs fewer than // 308*4 binary digits. ASSERT(Bignum::kMaxSignificantBits >= 324*4); bool need_boundary_deltas = (mode == BIGNUM_DTOA_SHORTEST); InitialScaledStartValues(v, estimated_power, need_boundary_deltas, &numerator, &denominator, &delta_minus, &delta_plus); // We now have v = (numerator / denominator) * 10^estimated_power. FixupMultiply10(estimated_power, is_even, decimal_point, &numerator, &denominator, &delta_minus, &delta_plus); // We now have v = (numerator / denominator) * 10^(decimal_point-1), and // 1 <= (numerator + delta_plus) / denominator < 10 switch (mode) { case BIGNUM_DTOA_SHORTEST: GenerateShortestDigits(&numerator, &denominator, &delta_minus, &delta_plus, is_even, buffer, length); break; case BIGNUM_DTOA_FIXED: BignumToFixed(requested_digits, decimal_point, &numerator, &denominator, buffer, length); break; case BIGNUM_DTOA_PRECISION: GenerateCountedDigits(requested_digits, decimal_point, &numerator, &denominator, buffer, length); break; default: UNREACHABLE(); } buffer[*length] = '\0'; } // The procedure starts generating digits from the left to the right and stops // when the generated digits yield the shortest decimal representation of v. A // decimal representation of v is a number lying closer to v than to any other // double, so it converts to v when read. // // This is true if d, the decimal representation, is between m- and m+, the // upper and lower boundaries. d must be strictly between them if !is_even. // m- := (numerator - delta_minus) / denominator // m+ := (numerator + delta_plus) / denominator // // Precondition: 0 <= (numerator+delta_plus) / denominator < 10. // If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit // will be produced. This should be the standard precondition. static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus, bool is_even, Vector<char> buffer, int* length) { // Small optimization: if delta_minus and delta_plus are the same just reuse // one of the two bignums. if (Bignum::Equal(*delta_minus, *delta_plus)) { delta_plus = delta_minus; } *length = 0; while (true) { uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. buffer[(*length)++] = digit + '0'; // Can we stop already? // If the remainder of the division is less than the distance to the lower // boundary we can stop. In this case we simply round down (discarding the // remainder). // Similarly we test if we can round up (using the upper boundary). bool in_delta_room_minus; bool in_delta_room_plus; if (is_even) { in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus); } else { in_delta_room_minus = Bignum::Less(*numerator, *delta_minus); } if (is_even) { in_delta_room_plus = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0; } else { in_delta_room_plus = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0; } if (!in_delta_room_minus && !in_delta_room_plus) { // Prepare for next iteration. numerator->Times10(); delta_minus->Times10(); // We optimized delta_plus to be equal to delta_minus (if they share the // same value). So don't multiply delta_plus if they point to the same // object. if (delta_minus != delta_plus) { delta_plus->Times10(); } } else if (in_delta_room_minus && in_delta_room_plus) { // Let's see if 2*numerator < denominator. // If yes, then the next digit would be < 5 and we can round down. int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator); if (compare < 0) { // Remaining digits are less than .5. -> Round down (== do nothing). } else if (compare > 0) { // Remaining digits are more than .5 of denominator. -> Round up. // Note that the last digit could not be a '9' as otherwise the whole // loop would have stopped earlier. // We still have an assert here in case the preconditions were not // satisfied. ASSERT(buffer[(*length) - 1] != '9'); buffer[(*length) - 1]++; } else { // Halfway case. // TODO(floitsch): need a way to solve half-way cases. // For now let's round towards even (since this is what Gay seems to // do). if ((buffer[(*length) - 1] - '0') % 2 == 0) { // Round down => Do nothing. } else { ASSERT(buffer[(*length) - 1] != '9'); buffer[(*length) - 1]++; } } return; } else if (in_delta_room_minus) { // Round down (== do nothing). return; } else { // in_delta_room_plus // Round up. // Note again that the last digit could not be '9' since this would have // stopped the loop earlier. // We still have an ASSERT here, in case the preconditions were not // satisfied. ASSERT(buffer[(*length) -1] != '9'); buffer[(*length) - 1]++; return; } } } // Let v = numerator / denominator < 10. // Then we generate 'count' digits of d = x.xxxxx... (without the decimal point) // from left to right. Once 'count' digits have been produced we decide wether // to round up or down. Remainders of exactly .5 round upwards. Numbers such // as 9.999999 propagate a carry all the way, and change the // exponent (decimal_point), when rounding upwards. static void GenerateCountedDigits(int count, int* decimal_point, Bignum* numerator, Bignum* denominator, Vector<char>(buffer), int* length) { ASSERT(count >= 0); for (int i = 0; i < count - 1; ++i) { uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. buffer[i] = digit + '0'; // Prepare for next iteration. numerator->Times10(); } // Generate the last digit. uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) { digit++; } buffer[count - 1] = digit + '0'; // Correct bad digits (in case we had a sequence of '9's). Propagate the // carry until we hat a non-'9' or til we reach the first digit. for (int i = count - 1; i > 0; --i) { if (buffer[i] != '0' + 10) break; buffer[i] = '0'; buffer[i - 1]++; } if (buffer[0] == '0' + 10) { // Propagate a carry past the top place. buffer[0] = '1'; (*decimal_point)++; } *length = count; } // Generates 'requested_digits' after the decimal point. It might omit // trailing '0's. If the input number is too small then no digits at all are // generated (ex.: 2 fixed digits for 0.00001). // // Input verifies: 1 <= (numerator + delta) / denominator < 10. static void BignumToFixed(int requested_digits, int* decimal_point, Bignum* numerator, Bignum* denominator, Vector<char>(buffer), int* length) { // Note that we have to look at more than just the requested_digits, since // a number could be rounded up. Example: v=0.5 with requested_digits=0. // Even though the power of v equals 0 we can't just stop here. if (-(*decimal_point) > requested_digits) { // The number is definitively too small. // Ex: 0.001 with requested_digits == 1. // Set decimal-point to -requested_digits. This is what Gay does. // Note that it should not have any effect anyways since the string is // empty. *decimal_point = -requested_digits; *length = 0; return; } else if (-(*decimal_point) == requested_digits) { // We only need to verify if the number rounds down or up. // Ex: 0.04 and 0.06 with requested_digits == 1. ASSERT(*decimal_point == -requested_digits); // Initially the fraction lies in range (1, 10]. Multiply the denominator // by 10 so that we can compare more easily. denominator->Times10(); if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) { // If the fraction is >= 0.5 then we have to include the rounded // digit. buffer[0] = '1'; *length = 1; (*decimal_point)++; } else { // Note that we caught most of similar cases earlier. *length = 0; } return; } else { // The requested digits correspond to the digits after the point. // The variable 'needed_digits' includes the digits before the point. int needed_digits = (*decimal_point) + requested_digits; GenerateCountedDigits(needed_digits, decimal_point, numerator, denominator, buffer, length); } } // Returns an estimation of k such that 10^(k-1) <= v < 10^k where // v = f * 2^exponent and 2^52 <= f < 2^53. // v is hence a normalized double with the given exponent. The output is an // approximation for the exponent of the decimal approimation .digits * 10^k. // // The result might undershoot by 1 in which case 10^k <= v < 10^k+1. // Note: this property holds for v's upper boundary m+ too. // 10^k <= m+ < 10^k+1. // (see explanation below). // // Examples: // EstimatePower(0) => 16 // EstimatePower(-52) => 0 // // Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0. static int EstimatePower(int exponent) { // This function estimates log10 of v where v = f*2^e (with e == exponent). // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)). // Note that f is bounded by its container size. Let p = 53 (the double's // significand size). Then 2^(p-1) <= f < 2^p. // // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)). // The computed number undershoots by less than 0.631 (when we compute log3 // and not log10). // // Optimization: since we only need an approximated result this computation // can be performed on 64 bit integers. On x86/x64 architecture the speedup is // not really measurable, though. // // Since we want to avoid overshooting we decrement by 1e10 so that // floating-point imprecisions don't affect us. // // Explanation for v's boundary m+: the computation takes advantage of // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement // (even for denormals where the delta can be much more important). const double k1Log10 = 0.30102999566398114; // 1/lg(10) // For doubles len(f) == 53 (don't forget the hidden bit). const int kSignificandSize = 53; double estimate = std::ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10); return static_cast<int>(estimate); } // See comments for InitialScaledStartValues. static void InitialScaledStartValuesPositiveExponent( double v, int estimated_power, bool need_boundary_deltas, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { // A positive exponent implies a positive power. ASSERT(estimated_power >= 0); // Since the estimated_power is positive we simply multiply the denominator // by 10^estimated_power. // numerator = v. numerator->AssignUInt64(Double(v).Significand()); numerator->ShiftLeft(Double(v).Exponent()); // denominator = 10^estimated_power. denominator->AssignPowerUInt16(10, estimated_power); if (need_boundary_deltas) { // Introduce a common denominator so that the deltas to the boundaries are // integers. denominator->ShiftLeft(1); numerator->ShiftLeft(1); // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common // denominator (of 2) delta_plus equals 2^e. delta_plus->AssignUInt16(1); delta_plus->ShiftLeft(Double(v).Exponent()); // Same for delta_minus (with adjustments below if f == 2^p-1). delta_minus->AssignUInt16(1); delta_minus->ShiftLeft(Double(v).Exponent()); // If the significand (without the hidden bit) is 0, then the lower // boundary is closer than just half a ulp (unit in the last place). // There is only one exception: if the next lower number is a denormal then // the distance is 1 ulp. This cannot be the case for exponent >= 0 (but we // have to test it in the other function where exponent < 0). uint64_t v_bits = Double(v).AsUint64(); if ((v_bits & Double::kSignificandMask) == 0) { // The lower boundary is closer at half the distance of "normal" numbers. // Increase the common denominator and adapt all but the delta_minus. denominator->ShiftLeft(1); // *2 numerator->ShiftLeft(1); // *2 delta_plus->ShiftLeft(1); // *2 } } } // See comments for InitialScaledStartValues static void InitialScaledStartValuesNegativeExponentPositivePower( double v, int estimated_power, bool need_boundary_deltas, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { uint64_t significand = Double(v).Significand(); int exponent = Double(v).Exponent(); // v = f * 2^e with e < 0, and with estimated_power >= 0. // This means that e is close to 0 (have a look at how estimated_power is // computed). // numerator = significand // since v = significand * 2^exponent this is equivalent to // numerator = v * / 2^-exponent numerator->AssignUInt64(significand); // denominator = 10^estimated_power * 2^-exponent (with exponent < 0) denominator->AssignPowerUInt16(10, estimated_power); denominator->ShiftLeft(-exponent); if (need_boundary_deltas) { // Introduce a common denominator so that the deltas to the boundaries are // integers. denominator->ShiftLeft(1); numerator->ShiftLeft(1); // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common // denominator (of 2) delta_plus equals 2^e. // Given that the denominator already includes v's exponent the distance // to the boundaries is simply 1. delta_plus->AssignUInt16(1); // Same for delta_minus (with adjustments below if f == 2^p-1). delta_minus->AssignUInt16(1); // If the significand (without the hidden bit) is 0, then the lower // boundary is closer than just one ulp (unit in the last place). // There is only one exception: if the next lower number is a denormal // then the distance is 1 ulp. Since the exponent is close to zero // (otherwise estimated_power would have been negative) this cannot happen // here either. uint64_t v_bits = Double(v).AsUint64(); if ((v_bits & Double::kSignificandMask) == 0) { // The lower boundary is closer at half the distance of "normal" numbers. // Increase the denominator and adapt all but the delta_minus. denominator->ShiftLeft(1); // *2 numerator->ShiftLeft(1); // *2 delta_plus->ShiftLeft(1); // *2 } } } // See comments for InitialScaledStartValues static void InitialScaledStartValuesNegativeExponentNegativePower( double v, int estimated_power, bool need_boundary_deltas, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { const uint64_t kMinimalNormalizedExponent = V8_2PART_UINT64_C(0x00100000, 00000000); uint64_t significand = Double(v).Significand(); int exponent = Double(v).Exponent(); // Instead of multiplying the denominator with 10^estimated_power we // multiply all values (numerator and deltas) by 10^-estimated_power. // Use numerator as temporary container for power_ten. Bignum* power_ten = numerator; power_ten->AssignPowerUInt16(10, -estimated_power); if (need_boundary_deltas) { // Since power_ten == numerator we must make a copy of 10^estimated_power // before we complete the computation of the numerator. // delta_plus = delta_minus = 10^estimated_power delta_plus->AssignBignum(*power_ten); delta_minus->AssignBignum(*power_ten); } // numerator = significand * 2 * 10^-estimated_power // since v = significand * 2^exponent this is equivalent to // numerator = v * 10^-estimated_power * 2 * 2^-exponent. // Remember: numerator has been abused as power_ten. So no need to assign it // to itself. ASSERT(numerator == power_ten); numerator->MultiplyByUInt64(significand); // denominator = 2 * 2^-exponent with exponent < 0. denominator->AssignUInt16(1); denominator->ShiftLeft(-exponent); if (need_boundary_deltas) { // Introduce a common denominator so that the deltas to the boundaries are // integers. numerator->ShiftLeft(1); denominator->ShiftLeft(1); // With this shift the boundaries have their correct value, since // delta_plus = 10^-estimated_power, and // delta_minus = 10^-estimated_power. // These assignments have been done earlier. // The special case where the lower boundary is twice as close. // This time we have to look out for the exception too. uint64_t v_bits = Double(v).AsUint64(); if ((v_bits & Double::kSignificandMask) == 0 && // The only exception where a significand == 0 has its boundaries at // "normal" distances: (v_bits & Double::kExponentMask) != kMinimalNormalizedExponent) { numerator->ShiftLeft(1); // *2 denominator->ShiftLeft(1); // *2 delta_plus->ShiftLeft(1); // *2 } } } // Let v = significand * 2^exponent. // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator // and denominator. The functions GenerateShortestDigits and // GenerateCountedDigits will then convert this ratio to its decimal // representation d, with the required accuracy. // Then d * 10^estimated_power is the representation of v. // (Note: the fraction and the estimated_power might get adjusted before // generating the decimal representation.) // // The initial start values consist of: // - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power. // - a scaled (common) denominator. // optionally (used by GenerateShortestDigits to decide if it has the shortest // decimal converting back to v): // - v - m-: the distance to the lower boundary. // - m+ - v: the distance to the upper boundary. // // v, m+, m-, and therefore v - m- and m+ - v all share the same denominator. // // Let ep == estimated_power, then the returned values will satisfy: // v / 10^ep = numerator / denominator. // v's boundarys m- and m+: // m- / 10^ep == v / 10^ep - delta_minus / denominator // m+ / 10^ep == v / 10^ep + delta_plus / denominator // Or in other words: // m- == v - delta_minus * 10^ep / denominator; // m+ == v + delta_plus * 10^ep / denominator; // // Since 10^(k-1) <= v < 10^k (with k == estimated_power) // or 10^k <= v < 10^(k+1) // we then have 0.1 <= numerator/denominator < 1 // or 1 <= numerator/denominator < 10 // // It is then easy to kickstart the digit-generation routine. // // The boundary-deltas are only filled if need_boundary_deltas is set. static void InitialScaledStartValues(double v, int estimated_power, bool need_boundary_deltas, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { if (Double(v).Exponent() >= 0) { InitialScaledStartValuesPositiveExponent( v, estimated_power, need_boundary_deltas, numerator, denominator, delta_minus, delta_plus); } else if (estimated_power >= 0) { InitialScaledStartValuesNegativeExponentPositivePower( v, estimated_power, need_boundary_deltas, numerator, denominator, delta_minus, delta_plus); } else { InitialScaledStartValuesNegativeExponentNegativePower( v, estimated_power, need_boundary_deltas, numerator, denominator, delta_minus, delta_plus); } } // This routine multiplies numerator/denominator so that its values lies in the // range 1-10. That is after a call to this function we have: // 1 <= (numerator + delta_plus) /denominator < 10. // Let numerator the input before modification and numerator' the argument // after modification, then the output-parameter decimal_point is such that // numerator / denominator * 10^estimated_power == // numerator' / denominator' * 10^(decimal_point - 1) // In some cases estimated_power was too low, and this is already the case. We // then simply adjust the power so that 10^(k-1) <= v < 10^k (with k == // estimated_power) but do not touch the numerator or denominator. // Otherwise the routine multiplies the numerator and the deltas by 10. static void FixupMultiply10(int estimated_power, bool is_even, int* decimal_point, Bignum* numerator, Bignum* denominator, Bignum* delta_minus, Bignum* delta_plus) { bool in_range; if (is_even) { // For IEEE doubles half-way cases (in decimal system numbers ending with 5) // are rounded to the closest floating-point number with even significand. in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0; } else { in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0; } if (in_range) { // Since numerator + delta_plus >= denominator we already have // 1 <= numerator/denominator < 10. Simply update the estimated_power. *decimal_point = estimated_power + 1; } else { *decimal_point = estimated_power; numerator->Times10(); if (Bignum::Equal(*delta_minus, *delta_plus)) { delta_minus->Times10(); delta_plus->AssignBignum(*delta_minus); } else { delta_minus->Times10(); delta_plus->Times10(); } } } } } // namespace v8::internal
gpl-3.0
wisehead/Leetcode
24.DFS_1/0100.Same_Tree.Tree_DepthFirstSearch.Easy/same_tree.recursive.cpp
1331
/******************************************************************************* * file name: same_tree.cpp * author: hui chen. (c) 17 * mail: [email protected] * created time: 17/11/07-11:11 * modified time: 17/11/07-11:11 *******************************************************************************/ #include <iostream> #include <stack> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p==NULL || q==NULL) return p==q; if (p->val == q->val) return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); else return false; /* stack<TreeNode*> mystack; TreeNode *p_left = NULL; TreeNode *p_right = NULL; if (p->val == q->val) { if(p->left) { re } } */ } }; int main() { }
gpl-3.0
keera-studios/pang-a-lambda
Experiments/splitballs/Debug.hs
142
module Debug where import Control.Monad (when, void) import Constants debug :: Bool -> String -> IO () debug b msg = when b $ putStrLn msg
gpl-3.0
Radarr/Radarr
src/NzbDrone.Core/Queue/Queue.cs
1362
using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Queue { public class Queue : ModelBase { public Movie Movie { get; set; } public List<Language> Languages { get; set; } public QualityModel Quality { get; set; } public decimal Size { get; set; } public string Title { get; set; } public decimal Sizeleft { get; set; } public TimeSpan? Timeleft { get; set; } public DateTime? EstimatedCompletionTime { get; set; } public string Status { get; set; } public TrackedDownloadStatus? TrackedDownloadStatus { get; set; } public TrackedDownloadState? TrackedDownloadState { get; set; } public List<TrackedDownloadStatusMessage> StatusMessages { get; set; } public string DownloadId { get; set; } public RemoteMovie RemoteMovie { get; set; } public DownloadProtocol Protocol { get; set; } public string DownloadClient { get; set; } public string Indexer { get; set; } public string OutputPath { get; set; } public string ErrorMessage { get; set; } } }
gpl-3.0
mpdeimos/git-repo-zipper
test-data/unlink.sh
119
#!/bin/bash for r in */ do if [[ -d "$r/dot_git" && -L "$r/.git" ]] then echo "unlink $r" rm "$r/.git" fi done
gpl-3.0
yordan-karadzhov/equipmentlist-mice
src/devel/eventbuild.cc
3452
#include "equipmentList_common.hh" #include "MiceDAQMessanger.hh" #include "DAQManager.hh" #include "EventBuildManager.hh" #include "MDprocessor.h" #include "MDfragmentDBB.h" #include "MDpartEventV1731.h" #include "MDprocessManager.h" #include "DBBDataProcessor.hh" #include "V1731DataProcessor.hh" #include "DBBSpillData.hh" #include "EMRDaq.hh" #include "DAQData.hh" #include "Spill.hh" #include "TFile.h" #include "TTree.h" using namespace std; MAUS::Spill *spill; MAUS::DAQData *data; // MAUS::EMRDaq *emr; MAUS::DBBArray *dbb; MAUS::V1731PartEventArray *v1731spill; DBBDataProcessor *dbbProc; V1731DataProcessor *v1731Proc; TFile *dataFile; TTree *dataTree; DAQManager *myDAQ; EventBuildManager *eventBuilder; MiceDAQMessanger *messanger; void start_of_run(int i) { *(messanger->getStream()) << "-----> \nThis is Start of Run " << i << endl; messanger->sendMessage(MDE_DEBUGGING); stringstream ss_rf; ss_rf << "../data_tmp/EMRdata_" << i << ".root"; // cout << ss_rf.str() << endl; dataFile = new TFile(ss_rf.str().c_str(),"RECREATE","EMR Cosmoc data"); dataTree = new TTree("EMRCosmicData", "EMR Cosmic test Data"); // spill = new MAUS::Spill(); data = new MAUS::DAQData; // emr = new MAUS::EMRDaq; dbb = new MAUS::DBBArray; v1731spill = new MAUS::V1731PartEventArray; dbbProc->set_spill(dbb); v1731Proc->set_spill(v1731spill); dataTree->Branch("Spill", &data); } void end_of_run(int i) { *(messanger->getStream()) << "-----> \nThis is End of Run " << i; messanger->sendMessage(MDE_DEBUGGING); dataTree->Write(); dataFile->Close(); } void start_of_spill(int i) { *(messanger->getStream()) << "-----> \nThis is Start of Spill " << i << endl; messanger->sendMessage(MDE_DEBUGGING); // dbb->resize(0); // v1731spill->resize(0); } void end_of_spill(int i) { *(messanger->getStream()) << "-----> \nThis is End of Spill " << i << endl; messanger->sendMessage(MDE_DEBUGGING); dbb->resize(0); v1731spill->resize(0); myDAQ->Process(); // if (dbb->size()==2) { // (*dbb)[0].print(); // (*dbb)[1].print(); // } MAUS::EMRDaq emr; emr.SetDBBArray(*dbb); emr.SetV1731PartEventArray(*v1731spill); data->SetEMRDaq(emr); dataTree->Fill(); } int main(int argc, char** argv) { int run_count(0); if (argc==2) { stringstream ss; ss << argv[1]; ss >> run_count; } MDprocessManager proc_manager; messanger = MiceDAQMessanger::Instance(); messanger->setVerbosity(1); myDAQ = new DAQManager(); eventBuilder = new EventBuildManager(); dbbProc = new DBBDataProcessor(); dbbProc->SetProcessManager(&proc_manager); // dbbProc->set_debug_mode(true); v1731Proc = new V1731DataProcessor(); v1731Proc->SetProcessManager(&proc_manager); // MDequipMap::Dump(); myDAQ->SetFragmentProc("DBB", dbbProc); myDAQ->SetPartEventProc("V1731", v1731Proc); myDAQ->DumpProcessors(); myDAQ->MemBankInit(1024*1024); eventBuilder->SetDataPtr(myDAQ->getDataPtr()); eventBuilder->SetRunCount(run_count); eventBuilder->SetOnStartOfRunDo(&start_of_run); eventBuilder->SetOnEndOfRunDo(&end_of_run); // eventBuilder->SetOnStartOfSpillDo(&start_of_spill); eventBuilder->SetOnEndOfSpillDo(&end_of_spill); eventBuilder->Go(); delete myDAQ; delete eventBuilder; delete dbbProc; delete v1731Proc; return 1; }
gpl-3.0
AllaMaevskaya/AliceO2
GPU/GPUTracking/gpucf/src/gpucf/common/log.cpp
4052
// Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See http://alice-o2.web.cern.ch/license for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #include "log.h" #include <CL/cl.h> #include <unordered_map> namespace gpucf { namespace log { #define ERR_STR_PAIR(err) \ { \ err, #err \ } std::string clErrToStr(cl_int errcode) { static const std::unordered_map<int, std::string> mapErrToStr = { ERR_STR_PAIR(CL_SUCCESS), ERR_STR_PAIR(CL_DEVICE_NOT_FOUND), ERR_STR_PAIR(CL_DEVICE_NOT_AVAILABLE), ERR_STR_PAIR(CL_COMPILER_NOT_AVAILABLE), ERR_STR_PAIR(CL_MEM_OBJECT_ALLOCATION_FAILURE), ERR_STR_PAIR(CL_OUT_OF_RESOURCES), ERR_STR_PAIR(CL_OUT_OF_HOST_MEMORY), ERR_STR_PAIR(CL_PROFILING_INFO_NOT_AVAILABLE), ERR_STR_PAIR(CL_MEM_COPY_OVERLAP), ERR_STR_PAIR(CL_IMAGE_FORMAT_MISMATCH), ERR_STR_PAIR(CL_IMAGE_FORMAT_NOT_SUPPORTED), ERR_STR_PAIR(CL_BUILD_PROGRAM_FAILURE), ERR_STR_PAIR(CL_MAP_FAILURE), ERR_STR_PAIR(CL_MISALIGNED_SUB_BUFFER_OFFSET), ERR_STR_PAIR(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST), ERR_STR_PAIR(CL_COMPILE_PROGRAM_FAILURE), ERR_STR_PAIR(CL_LINKER_NOT_AVAILABLE), ERR_STR_PAIR(CL_LINK_PROGRAM_FAILURE), ERR_STR_PAIR(CL_DEVICE_PARTITION_FAILED), ERR_STR_PAIR(CL_KERNEL_ARG_INFO_NOT_AVAILABLE), ERR_STR_PAIR(CL_INVALID_VALUE), ERR_STR_PAIR(CL_INVALID_DEVICE_TYPE), ERR_STR_PAIR(CL_INVALID_PLATFORM), ERR_STR_PAIR(CL_INVALID_DEVICE), ERR_STR_PAIR(CL_INVALID_CONTEXT), ERR_STR_PAIR(CL_INVALID_QUEUE_PROPERTIES), ERR_STR_PAIR(CL_INVALID_COMMAND_QUEUE), ERR_STR_PAIR(CL_INVALID_HOST_PTR), ERR_STR_PAIR(CL_INVALID_MEM_OBJECT), ERR_STR_PAIR(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR), ERR_STR_PAIR(CL_INVALID_IMAGE_SIZE), ERR_STR_PAIR(CL_INVALID_SAMPLER), ERR_STR_PAIR(CL_INVALID_BINARY), ERR_STR_PAIR(CL_INVALID_BUILD_OPTIONS), ERR_STR_PAIR(CL_INVALID_PROGRAM), ERR_STR_PAIR(CL_INVALID_PROGRAM_EXECUTABLE), ERR_STR_PAIR(CL_INVALID_KERNEL_NAME), ERR_STR_PAIR(CL_INVALID_KERNEL_DEFINITION), ERR_STR_PAIR(CL_INVALID_KERNEL), ERR_STR_PAIR(CL_INVALID_ARG_INDEX), ERR_STR_PAIR(CL_INVALID_ARG_VALUE), ERR_STR_PAIR(CL_INVALID_ARG_SIZE), ERR_STR_PAIR(CL_INVALID_KERNEL_ARGS), ERR_STR_PAIR(CL_INVALID_WORK_DIMENSION), ERR_STR_PAIR(CL_INVALID_WORK_GROUP_SIZE), ERR_STR_PAIR(CL_INVALID_WORK_ITEM_SIZE), ERR_STR_PAIR(CL_INVALID_GLOBAL_OFFSET), ERR_STR_PAIR(CL_INVALID_EVENT_WAIT_LIST), ERR_STR_PAIR(CL_INVALID_EVENT), ERR_STR_PAIR(CL_INVALID_OPERATION), ERR_STR_PAIR(CL_INVALID_GL_OBJECT), ERR_STR_PAIR(CL_INVALID_BUFFER_SIZE), ERR_STR_PAIR(CL_INVALID_MIP_LEVEL), ERR_STR_PAIR(CL_INVALID_GLOBAL_WORK_SIZE), ERR_STR_PAIR(CL_INVALID_PROPERTY), ERR_STR_PAIR(CL_INVALID_IMAGE_DESCRIPTOR), ERR_STR_PAIR(CL_INVALID_COMPILER_OPTIONS), ERR_STR_PAIR(CL_INVALID_LINKER_OPTIONS), ERR_STR_PAIR(CL_INVALID_DEVICE_PARTITION_COUNT), ERR_STR_PAIR(CL_INVALID_PIPE_SIZE), ERR_STR_PAIR(CL_INVALID_DEVICE_QUEUE), }; auto got = mapErrToStr.find(errcode); if (got == mapErrToStr.end()) { return "UNKNOWN_ERROR"; } return got->second; } const char* levelToStr(Level lvl) { switch (lvl) { case Level::Debug: return "[Debug]"; case Level::Info: return "[Info ]"; case Level::Error: return "[Error]"; } return ""; } std::ostream& operator<<(std::ostream& o, Level lvl) { return o << levelToStr(lvl); } } // namespace log } // namespace gpucf // vim: set ts=4 sw=4 sts=4 expandtab:
gpl-3.0
Lytjepole/Lytjepole-Beheer
LPB/app.js
1604
/* * This file is generated and updated by Sencha Cmd. You can edit this file as * needed for your application, but these edits will have to be merged by * Sencha Cmd when upgrading. */ Ext.application({ name: 'LPB', extend: 'LPB.Application', requires: [ 'LPB.util.sha256', 'Ext.plugin.Viewport', 'Ext.list.Tree', 'LPB.view.login.Login', 'LPB.view.admin.Main', 'LPB.view.user.User', 'Ext.container.Container', 'Ext.layout.container.Anchor', 'Ext.sunfield.imageUploader.ImageUploader', 'Ext.sunfield.locationSelect.LocationSelect', 'Ext.sunfield.imageField.ImageField', 'Ext.sunfield.imageField.DatesField', 'Ext.sunfield.DateSlider', 'Ext.sunfield.sunEditor.SunEditor', 'Ext.sunfield.mruImages.MruImages', 'Ext.sunfield.groupEditor.GroupEditor', 'Ext.ux.form.ItemSelector' ] // The name of the initial view to create. With the classic toolkit this class // will gain a "viewport" plugin if it does not extend Ext.Viewport. With the // modern toolkit, the main view will be added to the Viewport. // //mainView: 'LPB.view.main.Main' //------------------------------------------------------------------------- // Most customizations should be made to LPB.Application. If you need to // customize this file, doing so below this section reduces the likelihood // of merge conflicts when upgrading to new versions of Sencha Cmd. //------------------------------------------------------------------------- });
gpl-3.0
dastiii/Ilch-2.0
application/modules/article/views/admin/settings/index.php
7007
<h1><?=$this->getTrans('settings') ?></h1> <form class="form-horizontal" method="POST"> <?=$this->getTokenField() ?> <div class="form-group <?=$this->validation()->hasError('articlesPerPage') ? 'has-error' : '' ?>"> <label for="articlesPerPageInput" class="col-lg-2 control-label"> <?=$this->getTrans('articlesPerPage') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="articlesPerPageInput" name="articlesPerPage" min="1" value="<?=($this->get('articlesPerPage') != '') ? $this->escape($this->get('articlesPerPage')) : $this->originalInput('articlesPerPage') ?>" /> </div> </div> <div class="form-group <?=$this->validation()->hasError('articleRating') ? 'has-error' : '' ?>"> <div class="col-lg-2 control-label"> <?=$this->getTrans('articleRating') ?> </div> <div class="col-lg-4"> <div class="flipswitch"> <input type="radio" class="flipswitch-input" id="articleRating-on" name="articleRating" value="1" <?php if ($this->get('articleRating') == '1') { echo 'checked="checked"'; } ?> /> <label for="articleRating-on" class="flipswitch-label flipswitch-label-on"><?=$this->getTrans('on') ?></label> <input type="radio" class="flipswitch-input" id="articleRating-off" name="articleRating" value="0" <?php if ($this->get('articleRating') != '1') { echo 'checked="checked"'; } ?> /> <label for="articleRating-off" class="flipswitch-label flipswitch-label-off"><?=$this->getTrans('off') ?></label> <span class="flipswitch-selection"></span> </div> </div> </div> <div class="form-group <?=$this->validation()->hasError('disableComments') ? 'has-error' : '' ?>"> <div class="col-lg-2 control-label"> <?=$this->getTrans('disableComments') ?> </div> <div class="col-lg-4"> <div class="flipswitch"> <input type="radio" class="flipswitch-input" id="disableComments-on" name="disableComments" value="1" <?php if ($this->get('disableComments') == '1') { echo 'checked="checked"'; } ?> /> <label for="disableComments-on" class="flipswitch-label flipswitch-label-on"><?=$this->getTrans('on') ?></label> <input type="radio" class="flipswitch-input" id="disableComments-off" name="disableComments" value="0" <?php if ($this->get('disableComments') != '1') { echo 'checked="checked"'; } ?> /> <label for="disableComments-off" class="flipswitch-label flipswitch-label-off"><?=$this->getTrans('off') ?></label> <span class="flipswitch-selection"></span> </div> </div> </div> <h2><?=$this->getTrans('boxSettings') ?></h2> <b><?=$this->getTrans('boxArticle') ?></b> <div class="form-group <?=$this->validation()->hasError('boxArticleLimit') ? 'has-error' : '' ?>"> <label for="boxArticleLimit" class="col-lg-2 control-label"> <?=$this->getTrans('boxArticleLimit') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxArticleLimit" name="boxArticleLimit" min="1" value="<?=($this->get('boxArticleLimit') != '') ? $this->escape($this->get('boxArticleLimit')) : $this->originalInput('boxArticleLimit') ?>" /> </div> </div> <b><?=$this->getTrans('boxArchive') ?></b> <div class="form-group <?=$this->validation()->hasError('boxArchiveLimit') ? 'has-error' : '' ?>"> <label for="boxArchiveLimit" class="col-lg-2 control-label"> <?=$this->getTrans('boxArchiveLimit') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxArchiveLimit" name="boxArchiveLimit" min="1" value="<?=($this->get('boxArchiveLimit') != '') ? $this->escape($this->get('boxArchiveLimit')) : $this->originalInput('boxArchiveLimit') ?>" /> </div> </div> <b><?=$this->getTrans('boxKeywords') ?></b> <div class="form-group <?=$this->validation()->hasError('boxKeywordsH2') ? 'has-error' : '' ?>"> <label for="boxKeywordsH2" class="col-lg-2 control-label"> <?=$this->getTrans('boxKeywordsH2') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxKeywordsH2" name="boxKeywordsH2" min="1" value="<?=($this->get('boxKeywordsH2') != '') ? $this->escape($this->get('boxKeywordsH2')) : $this->originalInput('boxKeywordsH2') ?>" required /> </div> </div> <div class="form-group <?=$this->validation()->hasError('boxKeywordsH3') ? 'has-error' : '' ?>"> <label for="boxKeywordsH3" class="col-lg-2 control-label"> <?=$this->getTrans('boxKeywordsH3') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxKeywordsH3" name="boxKeywordsH3" min="1" value="<?=($this->get('boxKeywordsH3') != '') ? $this->escape($this->get('boxKeywordsH3')) : $this->originalInput('boxKeywordsH3') ?>" required /> </div> </div> <div class="form-group <?=$this->validation()->hasError('boxKeywordsH4') ? 'has-error' : '' ?>"> <label for="boxKeywordsH4" class="col-lg-2 control-label"> <?=$this->getTrans('boxKeywordsH4') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxKeywordsH4" name="boxKeywordsH4" min="1" value="<?=($this->get('boxKeywordsH4') != '') ? $this->escape($this->get('boxKeywordsH4')) : $this->originalInput('boxKeywordsH4') ?>" required /> </div> </div> <div class="form-group <?=$this->validation()->hasError('boxKeywordsH5') ? 'has-error' : '' ?>"> <label for="boxKeywordsH5" class="col-lg-2 control-label"> <?=$this->getTrans('boxKeywordsH5') ?> </label> <div class="col-lg-1"> <input type="number" class="form-control" id="boxKeywordsH5" name="boxKeywordsH5" min="1" value="<?=($this->get('boxKeywordsH5') != '') ? $this->escape($this->get('boxKeywordsH5')) : $this->originalInput('boxKeywordsH5') ?>" required /> </div> </div> <?=$this->getSaveBar() ?> </form>
gpl-3.0
sergiobenrocha2/RetroArch
gfx/video_state_tracker.c
7542
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2017 - Daniel De Matteis * * RetroArch 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch 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 RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <compat/strl.h> #include <retro_inline.h> #ifdef HAVE_CONFIG_H #include "../config.h" #endif #ifdef HAVE_PYTHON #include "drivers_tracker/video_state_python.h" #endif #include "video_state_tracker.h" #include "../input/input_config.h" #include "../verbosity.h" struct state_tracker_internal { char id[64]; bool is_input; const uint16_t *input_ptr; const uint8_t *ptr; #ifdef HAVE_PYTHON py_state_t *py; #endif uint32_t addr; uint16_t mask; uint16_t equal; enum state_tracker_type type; uint32_t prev[2]; int frame_count; int frame_count_prev; uint32_t old_value; int transition_count; }; struct state_tracker { struct state_tracker_internal *info; unsigned info_elem; uint16_t input_state[2]; #ifdef HAVE_PYTHON py_state_t *py; #endif }; /** * state_tracker_init: * @info : State tracker info handle. * * Creates and initializes graphics state tracker. * * Returns: new state tracker handle if successful, otherwise NULL. **/ state_tracker_t* state_tracker_init(const struct state_tracker_info *info) { unsigned i; struct state_tracker_internal *tracker_info = NULL; state_tracker_t *tracker = (state_tracker_t*) calloc(1, sizeof(*tracker)); if (!tracker) return NULL; #ifdef HAVE_PYTHON if (info->script) { tracker->py = py_state_new(info->script, info->script_is_file, info->script_class ? info->script_class : "GameAware"); if (!tracker->py) { RARCH_ERR("Failed to initialize Python script.\n"); goto error; } } #endif tracker_info = (struct state_tracker_internal*) calloc(info->info_elem, sizeof(struct state_tracker_internal)); if (!tracker_info) goto error; tracker->info = tracker_info; tracker->info_elem = info->info_elem; for (i = 0; i < info->info_elem; i++) { /* If we don't have a valid pointer. */ static const uint8_t empty = 0; strlcpy(tracker->info[i].id, info->info[i].id, sizeof(tracker->info[i].id)); tracker->info[i].addr = info->info[i].addr; tracker->info[i].type = info->info[i].type; tracker->info[i].mask = (info->info[i].mask == 0) ? 0xffff : info->info[i].mask; tracker->info[i].equal = info->info[i].equal; #ifdef HAVE_PYTHON if (info->info[i].type == RARCH_STATE_PYTHON) { if (!tracker->py) { RARCH_ERR("Python semantic was requested, but Python tracker is not loaded.\n"); free(tracker->info); goto error; } tracker->info[i].py = tracker->py; } #endif switch (info->info[i].ram_type) { case RARCH_STATE_WRAM: tracker->info[i].ptr = info->wram ? info->wram : &empty; break; case RARCH_STATE_INPUT_SLOT1: tracker->info[i].input_ptr = &tracker->input_state[0]; tracker->info[i].is_input = true; break; case RARCH_STATE_INPUT_SLOT2: tracker->info[i].input_ptr = &tracker->input_state[1]; tracker->info[i].is_input = true; break; default: tracker->info[i].ptr = &empty; } } return tracker; error: RARCH_ERR("Allocation of state tracker info failed.\n"); free(tracker); return NULL; } /** * state_tracker_free: * @tracker : State tracker handle. * * Frees a state tracker handle. **/ void state_tracker_free(state_tracker_t *tracker) { if (tracker) { free(tracker->info); #ifdef HAVE_PYTHON py_state_free(tracker->py); #endif } free(tracker); } static INLINE uint16_t state_tracker_fetch( const struct state_tracker_internal *info) { uint16_t val = info->ptr[info->addr]; if (info->is_input) val = *info->input_ptr; val &= info->mask; if (info->equal && val != info->equal) val = 0; return val; } static void state_tracker_update_element( struct state_tracker_uniform *uniform, struct state_tracker_internal *info, unsigned frame_count) { uniform->id = info->id; switch (info->type) { case RARCH_STATE_CAPTURE: uniform->value = state_tracker_fetch(info); break; case RARCH_STATE_CAPTURE_PREV: if (info->prev[0] != state_tracker_fetch(info)) { info->prev[1] = info->prev[0]; info->prev[0] = state_tracker_fetch(info); } uniform->value = info->prev[1]; break; case RARCH_STATE_TRANSITION: if (info->old_value != state_tracker_fetch(info)) { info->old_value = state_tracker_fetch(info); info->frame_count = frame_count; } uniform->value = info->frame_count; break; case RARCH_STATE_TRANSITION_COUNT: if (info->old_value != state_tracker_fetch(info)) { info->old_value = state_tracker_fetch(info); info->transition_count++; } uniform->value = info->transition_count; break; case RARCH_STATE_TRANSITION_PREV: if (info->old_value != state_tracker_fetch(info)) { info->old_value = state_tracker_fetch(info); info->frame_count_prev = info->frame_count; info->frame_count = frame_count; } uniform->value = info->frame_count_prev; break; #ifdef HAVE_PYTHON case RARCH_STATE_PYTHON: uniform->value = py_state_get(info->py, info->id, frame_count); break; #endif default: break; } } void state_tracker_update_input(uint16_t *input1, uint16_t *input2); /** * state_tracker_get_uniform: * @tracker : State tracker handle. * @uniforms : State tracker uniforms. * @elem : Amount of uniform elements. * @frame_count : Frame count. * * Calls state_tracker_update_input(), and updates each uniform * element accordingly. * * Returns: Amount of state elements (either equal to @elem * or equal to @tracker->info_eleme). **/ unsigned state_tracker_get_uniform(state_tracker_t *tracker, struct state_tracker_uniform *uniforms, unsigned elem, unsigned frame_count) { unsigned i, elems = elem; if (tracker->info_elem < elem) elems = tracker->info_elem; state_tracker_update_input(&tracker->input_state[0], &tracker->input_state[1]); for (i = 0; i < elems; i++) state_tracker_update_element( &uniforms[i], &tracker->info[i], frame_count); return elems; }
gpl-3.0
acesnik/proteoform-suite
ProteoformSuiteGUI/Properties/Settings.Designer.cs
1075
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ProteoformSuiteGUI.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
gpl-3.0
fw1121/Pandoras-Toolbox-for-Bioinformatics
src/SPAdes/ext/src/bamtools/api/BamMultiReader.cpp
16495
// *************************************************************************** // BamMultiReader.cpp (c) 2010 Erik Garrison, Derek Barnett // Marth Lab, Department of Biology, Boston College // --------------------------------------------------------------------------- // Last modified: 14 January 2013 (DB) // --------------------------------------------------------------------------- // Convenience class for reading multiple BAM files. // // This functionality allows applications to work on very large sets of files // without requiring intermediate merge, sort, and index steps for each file // subset. It also improves the performance of our merge system as it // precludes the need to sort merged files. // *************************************************************************** #include "bamtools/api/BamMultiReader.h" #include "internal/bam/BamMultiReader_p.h" using namespace BamTools; #include <string> #include <vector> using namespace std; /*! \class BamTools::BamMultiReader \brief Convenience class for reading multiple BAM files. */ /*! \enum BamMultiReader::MergeOrder \brief Used to describe the merge strategy of the BamMultiReader. The merge strategy determines which alignment is 'next' from across all opened BAM files. */ /*! \var BamMultiReader::MergeOrder BamMultiReader::RoundRobinMerge \brief Merge strategy when BAM files are unsorted, or their sorted status is either unknown or ignored */ /*! \var BamMultiReader::MergeOrder BamMultiReader::MergeByCoordinate \brief Merge strategy when BAM files are sorted by position ('coordinate') */ /*! \var BamMultiReader::MergeOrder BamMultiReader::MergeByName \brief Merge strategy when BAM files are sorted by read name ('queryname') */ /*! \fn BamMultiReader::BamMultiReader(void) \brief constructor */ BamMultiReader::BamMultiReader(void) : d(new Internal::BamMultiReaderPrivate) { } /*! \fn BamMultiReader::~BamMultiReader(void) \brief destructor */ BamMultiReader::~BamMultiReader(void) { delete d; d = 0; } /*! \fn void BamMultiReader::Close(void) \brief Closes all open BAM files. Also clears out all header and reference data. \sa CloseFile(), IsOpen(), Open(), BamReader::Close() */ bool BamMultiReader::Close(void) { return d->Close(); } /*! \fn void BamMultiReader::CloseFile(const std::string& filename) \brief Closes requested BAM file. Leaves any other file(s) open, along with header and reference data. \param[in] filename name of specific BAM file to close \sa Close(), IsOpen(), Open(), BamReader::Close() */ bool BamMultiReader::CloseFile(const std::string& filename) { return d->CloseFile(filename); } /*! \fn bool BamMultiReader::CreateIndexes(const BamIndex::IndexType& type) \brief Creates index files for the current BAM files. \param[in] type file format to create, see BamIndex::IndexType for available formats \return \c true if index files created OK \sa LocateIndexes(), OpenIndexes(), BamReader::CreateIndex() */ bool BamMultiReader::CreateIndexes(const BamIndex::IndexType& type) { return d->CreateIndexes(type); } /*! \fn const std::vector<std::string> BamMultiReader::Filenames(void) const \brief Returns list of filenames for all open BAM files. Retrieved filenames will contain whatever was passed via Open(). If you need full directory paths here, be sure to include them when you open the BAM files. \returns names of open BAM files. If no files are open, returns an empty vector. \sa IsOpen(), BamReader::GetFilename() */ const std::vector<std::string> BamMultiReader::Filenames(void) const { return d->Filenames(); } /*! \fn std::string BamMultiReader::GetErrorString(void) const \brief Returns a human-readable description of the last error that occurred This method allows elimination of STDERR pollution. Developers of client code may choose how the messages are displayed to the user, if at all. \return error description */ std::string BamMultiReader::GetErrorString(void) const { return d->GetErrorString(); } /*! \fn SamHeader BamMultiReader::GetHeader(void) const \brief Returns unified SAM-format header for all files \note Modifying the retrieved text does NOT affect the current BAM files. These files have been opened in a read-only mode. However, your modified header text can be used in conjunction with BamWriter to generate a new BAM file with the appropriate header information. \returns header data wrapped in SamHeader object \sa GetHeaderText(), BamReader::GetHeader() */ SamHeader BamMultiReader::GetHeader(void) const { return d->GetHeader(); } /*! \fn std::string BamMultiReader::GetHeaderText(void) const \brief Returns unified SAM-format header text for all files \note Modifying the retrieved text does NOT affect the current BAM files. These files have been opened in a read-only mode. However, your modified header text can be used in conjunction with BamWriter to generate a new BAM file with the appropriate header information. \returns SAM-formatted header text \sa GetHeader(), BamReader::GetHeaderText() */ std::string BamMultiReader::GetHeaderText(void) const { return d->GetHeaderText(); } /*! \fn BamMultiReader::MergeOrder BamMultiReader::GetMergeOrder(void) const \brief Returns curent merge order strategy. \returns current merge order enum value \sa BamMultiReader::MergeOrder, SetExplicitMergeOrder() */ BamMultiReader::MergeOrder BamMultiReader::GetMergeOrder(void) const { return d->GetMergeOrder(); } /*! \fn bool BamMultiReader::GetNextAlignment(BamAlignment& alignment) \brief Retrieves next available alignment. Equivalent to BamReader::GetNextAlignment() with respect to what is a valid overlapping alignment and what data gets populated. This method takes care of determining which alignment actually is 'next' across multiple files, depending on their sort order. \param[out] alignment destination for alignment record data \returns \c true if a valid alignment was found \sa GetNextAlignmentCore(), SetExplicitMergeOrder(), SetRegion(), BamReader::GetNextAlignment() */ bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) { return d->GetNextAlignment(nextAlignment); } /*! \fn bool BamMultiReader::GetNextAlignmentCore(BamAlignment& alignment) \brief Retrieves next available alignment. Equivalent to BamReader::GetNextAlignmentCore() with respect to what is a valid overlapping alignment and what data gets populated. This method takes care of determining which alignment actually is 'next' across multiple files, depending on their sort order. \param[out] alignment destination for alignment record data \returns \c true if a valid alignment was found \sa GetNextAlignment(), SetExplicitMergeOrder(), SetRegion(), BamReader::GetNextAlignmentCore() */ bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) { return d->GetNextAlignmentCore(nextAlignment); } /*! \fn int BamMultiReader::GetReferenceCount(void) const \brief Returns number of reference sequences. \sa BamReader::GetReferenceCount() */ int BamMultiReader::GetReferenceCount(void) const { return d->GetReferenceCount(); } /*! \fn const RefVector& BamMultiReader::GetReferenceData(void) const \brief Returns all reference sequence entries. \sa RefData, BamReader::GetReferenceData() */ const BamTools::RefVector BamMultiReader::GetReferenceData(void) const { return d->GetReferenceData(); } /*! \fn int BamMultiReader::GetReferenceID(const std::string& refName) const \brief Returns the ID of the reference with this name. If \a refName is not found, returns -1. \param[in] refName name of reference to look up \sa BamReader::GetReferenceID() */ int BamMultiReader::GetReferenceID(const std::string& refName) const { return d->GetReferenceID(refName); } /*! \fn bool BamMultiReader::HasIndexes(void) const \brief Returns \c true if all BAM files have index data available. \sa BamReader::HasIndex() */ bool BamMultiReader::HasIndexes(void) const { return d->HasIndexes(); } /*! \fn bool BamMultiReader::HasOpenReaders(void) const \brief Returns \c true if there are any open BAM files. */ bool BamMultiReader::HasOpenReaders(void) const { return d->HasOpenReaders(); } /*! \fn bool BamMultiReader::Jump(int refID, int position) \brief Performs a random-access jump within current BAM files. This is a convenience method, equivalent to calling SetRegion() with only a left boundary specified. \param[in] refID ID of reference to jump to \param[in] position (0-based) left boundary \returns \c true if jump was successful \sa HasIndex(), BamReader::Jump() */ bool BamMultiReader::Jump(int refID, int position) { return d->Jump(refID, position); } /*! \fn bool BamMultiReader::LocateIndexes(const BamIndex::IndexType& preferredType) \brief Looks for index files that match current BAM files. Use this function when you need index files, and perhaps have a preferred index format, but do not depend heavily on which indexes actually get loaded at runtime. For each BAM file, this function will defer to your \a preferredType whenever possible. However, if an index file of \a preferredType can not be found, then it will look for any other index file that matches that BAM file. An example case would look this: \code BamMultiReader reader; // do setup... // ensure that all files have an index if ( !reader.LocateIndexes() ) // opens any existing index files that match our BAM files reader.CreateIndexes(); // creates index files for any BAM files that still lack one // do interesting stuff using random-access... \endcode If you want precise control over which index files are loaded, use OpenIndexes() with the desired index filenames. If that function returns false, you can use CreateIndexes() to then build index files of the exact requested format. \param[in] preferredType desired index file format, see BamIndex::IndexType for available formats \returns \c true if index files could be found for \b ALL open BAM files \sa BamReader::LocateIndex() */ bool BamMultiReader::LocateIndexes(const BamIndex::IndexType& preferredType) { return d->LocateIndexes(preferredType); } /*! \fn bool BamMultiReader::Open(const std::vector<std::string>& filenames) \brief Opens BAM files. \note Opening BAM files will invalidate any current region set on the multireader. All file pointers will be returned to the beginning of the alignment data. Follow this with Jump() or SetRegion() to establish a region of interest. \param[in] filenames list of BAM filenames to open \returns \c true if BAM files were opened successfully \sa Close(), HasOpenReaders(), OpenFile(), OpenIndexes(), BamReader::Open() */ bool BamMultiReader::Open(const std::vector<std::string>& filenames) { return d->Open(filenames); } /*! \fn bool BamMultiReader::OpenFile(const std::string& filename) \brief Opens a single BAM file. Adds another BAM file to multireader "on-the-fly". \note Opening a BAM file will invalidate any current region set on the multireader. All file pointers will be returned to the beginning of the alignment data. Follow this with Jump() or SetRegion() to establish a region of interest. \param[in] filename BAM filename to open \returns \c true if BAM file was opened successfully \sa Close(), HasOpenReaders(), Open(), OpenIndexes(), BamReader::Open() */ bool BamMultiReader::OpenFile(const std::string& filename) { return d->OpenFile(filename); } /*! \fn bool BamMultiReader::OpenIndexes(const std::vector<std::string>& indexFilenames) \brief Opens index files for current BAM files. \note Currently assumes that index filenames match the order (and number) of BAM files passed to Open(). \param[in] indexFilenames list of BAM index file names \returns \c true if BAM index file was opened & data loaded successfully \sa LocateIndex(), Open(), SetIndex(), BamReader::OpenIndex() */ bool BamMultiReader::OpenIndexes(const std::vector<std::string>& indexFilenames) { return d->OpenIndexes(indexFilenames); } /*! \fn bool BamMultiReader::Rewind(void) \brief Returns the internal file pointers to the beginning of alignment records. Useful for performing multiple sequential passes through BAM files. Calling this function clears any prior region that may have been set. \returns \c true if rewind operation was successful \sa Jump(), SetRegion(), BamReader::Rewind() */ bool BamMultiReader::Rewind(void) { return d->Rewind(); } /*! \fn void BamMultiReader::SetExplicitMergeOrder(BamMultiReader::MergeOrder order) \brief Sets an explicit merge order, regardless of the BAM files' SO header tag. The default behavior of the BamMultiReader is to check the SO tag in the BAM files' SAM header text to determine the merge strategy". The merge strategy is used to determine from which BAM file the next alignment should come when either GetNextAlignment() or GetNextAlignmentCore() are called. If files share a 'coordinate' or 'queryname' value for this tag, then the merge strategy is selected accordingly. If any of them do not match, or if any fileis marked as 'unsorted', then the merge strategy is simply a round-robin. This method allows client code to explicitly override the lookup behavior. This method can be useful when you know, for example, that your BAM files are sorted by coordinate but upstream processes did not set the header tag properly. \note This method should \bold not be called while reading alignments via GetNextAlignment() or GetNextAlignmentCore(). For proper results, you should call this method before (or immediately after) opening files, rewinding, jumping, etc. but \bold not once alignment fetching has started. There is nothing in the API to prevent you from doing so, but the results may be unexpected. \returns \c true if merge order could be successfully applied \sa BamMultiReader::MergeOrder, GetMergeOrder(), GetNextAlignment(), GetNextAlignmentCore() */ bool BamMultiReader::SetExplicitMergeOrder(BamMultiReader::MergeOrder order) { return d->SetExplicitMergeOrder(order); } /*! \fn bool BamMultiReader::SetRegion(const BamRegion& region) \brief Sets a target region of interest Equivalent to calling BamReader::SetRegion() on all open BAM files. \warning BamRegion now represents a zero-based, HALF-OPEN interval. In previous versions of BamTools (0.x & 1.x) all intervals were treated as zero-based, CLOSED. \param[in] region desired region-of-interest to activate \returns \c true if ALL readers set the region successfully \sa HasIndexes(), Jump(), BamReader::SetRegion() */ bool BamMultiReader::SetRegion(const BamRegion& region) { return d->SetRegion(region); } /*! \fn bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) \brief Sets a target region of interest This is an overloaded function. Equivalent to calling BamReader::SetRegion() on all open BAM files. \warning This function now expects a zero-based, HALF-OPEN interval. In previous versions of BamTools (0.x & 1.x) all intervals were treated as zero-based, CLOSED. \param[in] leftRefID referenceID of region's left boundary \param[in] leftPosition position of region's left boundary \param[in] rightRefID reference ID of region's right boundary \param[in] rightPosition position of region's right boundary \returns \c true if ALL readers set the region successfully \sa HasIndexes(), Jump(), BamReader::SetRegion() */ bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) { return d->SetRegion( BamRegion(leftRefID, leftPosition, rightRefID, rightPosition) ); }
gpl-3.0
DragonZX/fdm
Include.Add/vmsBrowsersSharedData.h
4022
/* Free Download Manager Copyright (c) 2003-2014 FreeDownloadManager.ORG */ #pragma once #include "vmsSharedData.h" #include "vmsLowIntegrityLevel.h" #define vmsBrowsersSharedData_MAXBROWSERPROCESSES 100 class vmsBrowsersSharedData { protected: struct DataStruct { DWORD dwActiveDownloadsCount; DWORD dwPID; }; public: vmsBrowsersSharedData () { OSVERSIONINFO ver; ZeroMemory (&ver, sizeof (ver)); ver.dwOSVersionInfoSize = sizeof (ver); GetVersionEx (&ver); m_hmxData = CreateMutex (ver.dwMajorVersion > 5 ? &vmsLowLabelSecurityAttributes () : NULL, FALSE, _T ("A89138B6-0898-4dd5-AA1F-673973F61421")); if (!m_hmxData && GetLastError () == ERROR_ACCESS_DENIED) m_hmxData = OpenMutex (SYNCHRONIZE, FALSE, _T ("A89138B6-0898-4dd5-AA1F-673973F61421")); if (m_hmxData) { WaitForSingleObject (m_hmxData, INFINITE); if (!m_data.Aquire (_T ("B75DD868-61F6-420c-811E-D9514561353A"))) { m_data.Aquire (_T ("B75DD868-61F6-420c-811E-D9514561353A"), false, vmsBrowsersSharedData_MAXBROWSERPROCESSES * sizeof (DataStruct), FILE_MAP_ALL_ACCESS, ver.dwMajorVersion > 5 ? &vmsLowLabelSecurityAttributes () : NULL); DataStruct *pData = (DataStruct*) m_data.getData (); if (pData) ZeroMemory (pData, vmsBrowsersSharedData_MAXBROWSERPROCESSES * sizeof (DataStruct)); } ReleaseMutex (m_hmxData); } } ~vmsBrowsersSharedData () { if (m_hmxData) CloseHandle (m_hmxData); } public: bool ModifyActiveDownloadsCount (int cDiff) { if (!cDiff) return true; if (!m_hmxData) return false; DataStruct *pData = getDataStructForThisProcess (); if (pData) pData->dwActiveDownloadsCount += cDiff; return pData != NULL; } DWORD getActiveDownloadsCount (bool bInThisProcessOnly = false) { DataStruct *pData = bInThisProcessOnly ? getDataStructForThisProcess () : (DataStruct*) m_data.getData (); if (!pData) return 0; if (bInThisProcessOnly) return pData->dwActiveDownloadsCount; RemoveNonExistingProcessFromList (); DWORD dwResult = 0; for (size_t i = 0; i < vmsBrowsersSharedData_MAXBROWSERPROCESSES; i++) dwResult += pData [i].dwActiveDownloadsCount; return dwResult; } protected: void RemoveNonExistingProcessFromList () { DataStruct *pData = (DataStruct*) m_data.getData (); if (!pData) return; WaitForSingleObject (m_hmxData, INFINITE); for (size_t i = 0; i < vmsBrowsersSharedData_MAXBROWSERPROCESSES; i++) { if (pData [i].dwPID && !isProcessAlive (pData [i].dwPID)) { pData [i].dwPID = 0; pData [i].dwActiveDownloadsCount = 0; } } ReleaseMutex (m_hmxData); } static bool isProcessAlive (DWORD dwPID) { HANDLE hProcess = OpenProcess (SYNCHRONIZE, FALSE, dwPID); if (!hProcess) hProcess = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, dwPID); if (!hProcess) hProcess = OpenProcess (PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPID); if (hProcess) CloseHandle (hProcess); return hProcess != NULL; } DataStruct* getDataStructForThisProcess () { DataStruct *pData = (DataStruct*) m_data.getData (); if (!pData) return NULL; DWORD dwPID = GetCurrentProcessId (); for (size_t i = 0; i < vmsBrowsersSharedData_MAXBROWSERPROCESSES; i++) { if (pData [i].dwPID == dwPID) return pData; } WaitForSingleObject (m_hmxData, INFINITE); DataStruct *pResult = NULL; for (size_t i = 0; i < vmsBrowsersSharedData_MAXBROWSERPROCESSES; i++) { if (!pData [i].dwPID) { pResult = pData + i; break; } } if (!pResult) for (size_t i = 0; i < vmsBrowsersSharedData_MAXBROWSERPROCESSES; i++) { if (!isProcessAlive (pData [i].dwPID)) { pResult = pData + i; break; } } if (pResult) { pResult->dwPID = dwPID; pResult->dwActiveDownloadsCount = 0; } ReleaseMutex (m_hmxData); return pResult; } vmsSharedData m_data; HANDLE m_hmxData; };
gpl-3.0
BipolarAurora/H-CE-Opensauce-V5
OpenSauce/Halo1/Halo1_CE/Rasterizer/PostProcessing/Fade/c_shader_instance_fade.cpp
3549
/* Yelo: Open Sauce SDK Halo 1 (CE) Edition See license\OpenSauce\Halo1_CE for specific license information */ #include "Common/Precompile.hpp" #include "Rasterizer/PostProcessing/Fade/c_shader_instance_fade.hpp" #if !PLATFORM_IS_DEDI #include "Rasterizer/PostProcessing/c_post_processing_main.hpp" namespace Yelo { namespace Rasterizer { namespace PostProcessing { namespace Fade { /*! * \brief * Sets the fade shader this class will instance. * * \param definition * The fade shader this class will instance. * * Sets the fade shader this class will instance. * * \see * c_shader_fade */ void c_shader_instance_fade::SetShader(c_shader_postprocess* definition) { m_members_fade.definition = CAST_PTR(c_shader_fade*, definition); c_shader_instance::SetShader(definition); } /*! * \brief * Sets the shaders parameters to the current fade values. * * Sets the shaders parameters to the current fade values. */ void c_shader_instance_fade::SetShaderInstanceVariables() { s_shader_fade_definition* definition = m_members.definition->GetShaderDefinition<s_shader_fade_definition>(); YELO_ASSERT_DISPLAY(definition != nullptr, "Fade shader has no tag definition"); LPD3DXEFFECT effect = m_members.definition->GetEffect(); // TODO: why are we reasserting definition? YELO_ASSERT_DISPLAY(definition != nullptr, "Fade shader has no valid effect"); definition->fade_amount_handle.SetVariable(effect, &m_members_fade.fade_amount, false); }; /*! * \brief * Custom render function for fading an effects result. * * \param render_device * The current render device. * * \param quad_instance * The quad instance to render with. * * \param fade_amount * The amount to fade the result by. * * \returns * S_OK if successful, non-zero if otherwise. * * Custom render function for fading an effects result. The fade effect swaps the current target with the scene texture, and re draws * it with alpha blending to fade the result in/out. */ HRESULT c_shader_instance_fade::Render(IDirect3DDevice9* render_device, c_quad_instance* quad_instance, real fade_amount) { m_members_fade.fade_amount = fade_amount; // set the effect result as the scene texture c_post_processing_main::Instance().Globals().scene_buffer_chain.SetSceneToLast(); // set the scene prior to the effect as the render target c_post_processing_main::Instance().Globals().scene_buffer_chain.Flip(); // set the fade value to the shader SetShaderInstanceVariables(); // set the render state to enable alpha blending render_device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); render_device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA); render_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); render_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // render the effect HRESULT hr = GetShader()->Render(render_device, quad_instance); // reset the render state to disable alpha blending render_device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); render_device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE); render_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); render_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); return hr; } }; }; }; }; #endif
gpl-3.0
Arribas/gnss-sdr
src/algorithms/observables/gnuradio_blocks/gps_l1_ca_observables_cc.cc
13634
/*! * \file gps_l1_ca_observables_cc.cc * \brief Implementation of the pseudorange computation block for GPS L1 C/A * \author Javier Arribas, 2011. jarribas(at)cttc.es * ------------------------------------------------------------------------- * * Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors) * * GNSS-SDR is a software defined Global Navigation * Satellite Systems receiver * * This file is part of GNSS-SDR. * * GNSS-SDR 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. * * GNSS-SDR 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 GNSS-SDR. If not, see <http://www.gnu.org/licenses/>. * * ------------------------------------------------------------------------- */ #include "gps_l1_ca_observables_cc.h" #include <algorithm> #include <cmath> #include <iostream> #include <map> #include <vector> #include <utility> #include <armadillo> #include <gnuradio/io_signature.h> #include <glog/logging.h> #include "control_message_factory.h" #include "gnss_synchro.h" #include "GPS_L1_CA.h" using google::LogMessage; gps_l1_ca_observables_cc_sptr gps_l1_ca_make_observables_cc(unsigned int nchannels, bool dump, std::string dump_filename, unsigned int deep_history) { return gps_l1_ca_observables_cc_sptr(new gps_l1_ca_observables_cc(nchannels, dump, dump_filename, deep_history)); } gps_l1_ca_observables_cc::gps_l1_ca_observables_cc(unsigned int nchannels, bool dump, std::string dump_filename, unsigned int deep_history) : gr::block("gps_l1_ca_observables_cc", gr::io_signature::make(nchannels, nchannels, sizeof(Gnss_Synchro)), gr::io_signature::make(nchannels, nchannels, sizeof(Gnss_Synchro))) { // initialize internal vars d_dump = dump; d_nchannels = nchannels; d_dump_filename = dump_filename; history_deep = deep_history; for (unsigned int i = 0; i < d_nchannels; i++) { d_acc_carrier_phase_queue_rads.push_back(std::deque<double>(d_nchannels)); d_carrier_doppler_queue_hz.push_back(std::deque<double>(d_nchannels)); d_symbol_TOW_queue_s.push_back(std::deque<double>(d_nchannels)); } // ############# ENABLE DATA FILE LOG ################# if (d_dump == true) { if (d_dump_file.is_open() == false) { try { d_dump_file.exceptions (std::ifstream::failbit | std::ifstream::badbit ); d_dump_file.open(d_dump_filename.c_str(), std::ios::out | std::ios::binary); LOG(INFO) << "Observables dump enabled Log file: " << d_dump_filename.c_str(); } catch (const std::ifstream::failure & e) { LOG(WARNING) << "Exception opening observables dump file " << e.what(); } } } } gps_l1_ca_observables_cc::~gps_l1_ca_observables_cc() { d_dump_file.close(); } bool pairCompare_gnss_synchro_Prn_delay_ms(const std::pair<int,Gnss_Synchro>& a, const std::pair<int,Gnss_Synchro>& b) { return (a.second.Prn_timestamp_ms) < (b.second.Prn_timestamp_ms); } bool pairCompare_gnss_synchro_d_TOW_at_current_symbol(const std::pair<int,Gnss_Synchro>& a, const std::pair<int,Gnss_Synchro>& b) { return (a.second.d_TOW_at_current_symbol) < (b.second.d_TOW_at_current_symbol); } int gps_l1_ca_observables_cc::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { Gnss_Synchro **in = (Gnss_Synchro **) &input_items[0]; // Get the input pointer Gnss_Synchro **out = (Gnss_Synchro **) &output_items[0]; // Get the output pointer Gnss_Synchro current_gnss_synchro[d_nchannels]; std::map<int,Gnss_Synchro> current_gnss_synchro_map; std::map<int,Gnss_Synchro>::iterator gnss_synchro_iter; if (d_nchannels != ninput_items.size()) { LOG(WARNING) << "The Observables block is not well connected"; } /* * 1. Read the GNSS SYNCHRO objects from available channels */ for (unsigned int i = 0; i < d_nchannels; i++) { //Copy the telemetry decoder data to local copy current_gnss_synchro[i] = in[i][0]; /* * 1.2 Assume no valid pseudoranges */ current_gnss_synchro[i].Flag_valid_pseudorange = false; current_gnss_synchro[i].Pseudorange_m = 0.0; if (current_gnss_synchro[i].Flag_valid_word) //if this channel have valid word { //record the word structure in a map for pseudorange computation current_gnss_synchro_map.insert(std::pair<int, Gnss_Synchro>(current_gnss_synchro[i].Channel_ID, current_gnss_synchro[i])); //################### SAVE DOPPLER AND ACC CARRIER PHASE HISTORIC DATA FOR INTERPOLATION IN OBSERVABLE MODULE ####### d_carrier_doppler_queue_hz[i].push_back(current_gnss_synchro[i].Carrier_Doppler_hz); d_acc_carrier_phase_queue_rads[i].push_back(current_gnss_synchro[i].Carrier_phase_rads); // save TOW history d_symbol_TOW_queue_s[i].push_back(current_gnss_synchro[i].d_TOW_at_current_symbol); if (d_carrier_doppler_queue_hz[i].size() > history_deep) { d_carrier_doppler_queue_hz[i].pop_front(); } if (d_acc_carrier_phase_queue_rads[i].size() > history_deep) { d_acc_carrier_phase_queue_rads[i].pop_front(); } if (d_symbol_TOW_queue_s[i].size() > history_deep) { d_symbol_TOW_queue_s[i].pop_front(); } } else { // Clear the observables history for this channel if (d_symbol_TOW_queue_s[i].size() > 0) { d_symbol_TOW_queue_s[i].clear(); d_carrier_doppler_queue_hz[i].clear(); d_acc_carrier_phase_queue_rads[i].clear(); } } } /* * 2. Compute RAW pseudoranges using COMMON RECEPTION TIME algorithm. Use only the valid channels (channels that are tracking a satellite) */ if(current_gnss_synchro_map.size() > 0) { /* * 2.1 Use CURRENT set of measurements and find the nearest satellite * common RX time algorithm */ // what is the most recent symbol TOW in the current set? -> this will be the reference symbol gnss_synchro_iter = max_element(current_gnss_synchro_map.begin(), current_gnss_synchro_map.end(), pairCompare_gnss_synchro_d_TOW_at_current_symbol); double d_TOW_reference = gnss_synchro_iter->second.d_TOW_at_current_symbol; double d_ref_PRN_rx_time_ms = gnss_synchro_iter->second.Prn_timestamp_ms; // Now compute RX time differences due to the PRN alignment in the correlators double traveltime_ms; double pseudorange_m; double delta_rx_time_ms; arma::vec symbol_TOW_vec_s; arma::vec dopper_vec_hz; arma::vec dopper_vec_interp_hz; arma::vec acc_phase_vec_rads; arma::vec acc_phase_vec_interp_rads; arma::vec desired_symbol_TOW(1); for(gnss_synchro_iter = current_gnss_synchro_map.begin(); gnss_synchro_iter != current_gnss_synchro_map.end(); gnss_synchro_iter++) { // compute the required symbol history shift in order to match the reference symbol delta_rx_time_ms = gnss_synchro_iter->second.Prn_timestamp_ms - d_ref_PRN_rx_time_ms; //compute the pseudorange traveltime_ms = (d_TOW_reference - gnss_synchro_iter->second.d_TOW_at_current_symbol) * 1000.0 + delta_rx_time_ms + GPS_STARTOFFSET_ms; //convert to meters and remove the receiver time offset in meters pseudorange_m = traveltime_ms * GPS_C_m_ms; // [m] // update the pseudorange object current_gnss_synchro[gnss_synchro_iter->second.Channel_ID] = gnss_synchro_iter->second; current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Pseudorange_m = pseudorange_m; current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Flag_valid_pseudorange = true; current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].d_TOW_at_current_symbol = round(d_TOW_reference * 1000.0) / 1000.0 + GPS_STARTOFFSET_ms / 1000.0; if (d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].size() >= history_deep) { // compute interpolated observation values for Doppler and Accumulate carrier phase symbol_TOW_vec_s = arma::vec(std::vector<double>(d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].begin(), d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].end())); acc_phase_vec_rads = arma::vec(std::vector<double>(d_acc_carrier_phase_queue_rads[gnss_synchro_iter->second.Channel_ID].begin(), d_acc_carrier_phase_queue_rads[gnss_synchro_iter->second.Channel_ID].end())); dopper_vec_hz = arma::vec(std::vector<double>(d_carrier_doppler_queue_hz[gnss_synchro_iter->second.Channel_ID].begin(), d_carrier_doppler_queue_hz[gnss_synchro_iter->second.Channel_ID].end())); desired_symbol_TOW[0] = symbol_TOW_vec_s[history_deep - 1] + delta_rx_time_ms / 1000.0; // arma::interp1(symbol_TOW_vec_s,dopper_vec_hz,desired_symbol_TOW,dopper_vec_interp_hz); // arma::interp1(symbol_TOW_vec_s,acc_phase_vec_rads,desired_symbol_TOW,acc_phase_vec_interp_rads); // Curve fitting to quadratic function arma::mat A = arma::ones<arma::mat> (history_deep, 2); A.col(1) = symbol_TOW_vec_s; arma::mat coef_acc_phase(1,3); arma::mat pinv_A = arma::pinv(A.t() * A) * A.t(); coef_acc_phase = pinv_A * acc_phase_vec_rads; arma::mat coef_doppler(1,3); coef_doppler = pinv_A * dopper_vec_hz; arma::vec acc_phase_lin; arma::vec carrier_doppler_lin; acc_phase_lin = coef_acc_phase[0] + coef_acc_phase[1] * desired_symbol_TOW[0]; carrier_doppler_lin = coef_doppler[0] + coef_doppler[1] * desired_symbol_TOW[0]; current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Carrier_phase_rads = acc_phase_lin[0]; current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Carrier_Doppler_hz = carrier_doppler_lin[0]; } } } if(d_dump == true) { // MULTIPLEXED FILE RECORDING - Record results to file try { double tmp_double; for (unsigned int i = 0; i < d_nchannels; i++) { tmp_double = current_gnss_synchro[i].d_TOW_at_current_symbol; d_dump_file.write((char*)&tmp_double, sizeof(double)); //tmp_double = current_gnss_synchro[i].Prn_timestamp_ms; tmp_double = current_gnss_synchro[i].Carrier_Doppler_hz; d_dump_file.write((char*)&tmp_double, sizeof(double)); tmp_double = current_gnss_synchro[i].Carrier_phase_rads/GPS_TWO_PI; d_dump_file.write((char*)&tmp_double, sizeof(double)); tmp_double = current_gnss_synchro[i].Pseudorange_m; d_dump_file.write((char*)&tmp_double, sizeof(double)); tmp_double = current_gnss_synchro[i].PRN; d_dump_file.write((char*)&tmp_double, sizeof(double)); } } catch (const std::ifstream::failure& e) { LOG(WARNING) << "Exception writing observables dump file " << e.what(); } } consume_each(1); //one by one for (unsigned int i = 0; i < d_nchannels; i++) { *out[i] = current_gnss_synchro[i]; } if (noutput_items == 0) { LOG(WARNING) << "noutput_items = 0"; } return 1; }
gpl-3.0
hyunsunWkd/team10-yetris
src/block.h
1560
/* yetris - Tetris(tm) on the console. * Copyright (C) 2013 Alexandre Dantas (kure) * * This file is part of yetris. * * yetris 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * homepage: http://www.github.com/alexdantas/yetris/ * mailto: [email protected] */ #ifndef BLOCK_H_DEFINED #define BLOCK_H_DEFINED #include "engine.h" /** Which states can a block be? Will not print when it's EMPTY */ typedef enum { BLOCK, EMPTY } block_e; /** All info about individual block */ struct block_s { int x; /**< x position relative to the board */ int y; /**< y position relative to the board */ block_e type; /**< state of the block, see #block_e */ int color; /**< color that will print the block */ char theme[2]; /**< appearance (how it will be printed onscreen) */ }; #ifndef _BLOCK_S #define _BLOCK_S typedef struct block_s block_s; #endif block_s new_block(int x, int y, char theme[], color_e color); #endif /* BLOCK_H_DEFINED */
gpl-3.0
MOD-ASL/ModularRobotSystemToolKit
unity3d/Assets/Scripts/Objects/ConnectionObject.cs
408
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; public class ConnectionObject { public string moduleName1; public string moduleName2; public string nodeName1; public string nodeName2; public float distance; public float angle; public ConnectionObject () { distance = 0f; angle = 0f; } }
gpl-3.0
together-web-pj/together-web-pj
node_modules/twilio/lib/rest/api/v2010/account/queue/member.js
17007
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Q = require('q'); /* jshint ignore:line */ var _ = require('lodash'); /* jshint ignore:line */ var Page = require('../../../../../base/Page'); /* jshint ignore:line */ var deserialize = require( '../../../../../base/deserialize'); /* jshint ignore:line */ var values = require('../../../../../base/values'); /* jshint ignore:line */ var MemberList; var MemberPage; var MemberInstance; var MemberContext; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @description Initialize the MemberList * * @param {Twilio.Api.V2010} version - Version of the resource * @param {string} accountSid - The account_sid * @param {string} queueSid - A string that uniquely identifies this queue */ /* jshint ignore:end */ MemberList = function MemberList(version, accountSid, queueSid) { /* jshint ignore:start */ /** * @function members * @memberof Twilio.Api.V2010.AccountContext.QueueContext * @instance * * @param {string} sid - sid of instance * * @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext} */ /* jshint ignore:end */ function MemberListInstance(sid) { return MemberListInstance.get(sid); } MemberListInstance._version = version; // Path Solution MemberListInstance._solution = { accountSid: accountSid, queueSid: queueSid }; MemberListInstance._uri = _.template( '/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members.json' // jshint ignore:line )(MemberListInstance._solution); /* jshint ignore:start */ /** * Streams MemberInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory efficient. * * If a function is passed as the first argument, it will be used as the callback function. * * @function each * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize=50] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ MemberListInstance.each = function each(opts, callback) { opts = opts || {}; if (_.isFunction(opts)) { opts = { callback: opts }; } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) { opts.callback = callback; } if (_.isUndefined(opts.callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var currentResource = 0; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { done = true; return false; } currentResource++; opts.callback(instance, onComplete); }); if ((limits.pageLimit && limits.pageLimit <= currentPage)) { onComplete(); } else if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); }; /* jshint ignore:start */ /** * @description Lists MemberInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback function. * * @function list * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of MemberInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @function page * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.page = function page(opts, callback) { opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({ uri: this._uri, method: 'GET', params: data }); promise = promise.then(function(payload) { deferred.resolve(new MemberPage( this._version, payload, this._solution )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single target page of MemberInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @function getPage * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {string} [targetUrl] - API-generated URL for the requested results page * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.getPage = function getPage(targetUrl, callback) { var deferred = Q.defer(); var promise = this._version._domain.twilio.request({ method: 'GET', uri: targetUrl }); promise = promise.then(function(payload) { deferred.resolve(new MemberPage( this._version, payload, this._solution )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Constructs a member * * @function get * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {string} callSid - The call_sid * * @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext} */ /* jshint ignore:end */ MemberListInstance.get = function get(callSid) { return new MemberContext( this._version, this._solution.accountSid, this._solution.queueSid, callSid ); }; return MemberListInstance; }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberPage * @augments Page * @description Initialize the MemberPage * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} response - Response from the API * @param {object} solution - Path solution * * @returns MemberPage */ /* jshint ignore:end */ MemberPage = function MemberPage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); }; _.extend(MemberPage.prototype, Page.prototype); MemberPage.prototype.constructor = MemberPage; /* jshint ignore:start */ /** * Build an instance of MemberInstance * * @function getInstance * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberPage * @instance * * @param {object} payload - Payload response from the API * * @returns MemberInstance */ /* jshint ignore:end */ MemberPage.prototype.getInstance = function getInstance(payload) { return new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid ); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @description Initialize the MemberContext * * @property {string} callSid - Unique string that identifies this resource * @property {Date} dateEnqueued - The date the member was enqueued * @property {number} position - This member's current position in the queue. * @property {string} uri - The uri * @property {number} waitTime - * The number of seconds the member has been in the queue. * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} payload - The instance payload * @param {sid} accountSid - The account_sid * @param {sid} queueSid - The Queue in which to find the members * @param {sid} callSid - The call_sid */ /* jshint ignore:end */ MemberInstance = function MemberInstance(version, payload, accountSid, queueSid, callSid) { this._version = version; // Marshaled Properties this.callSid = payload.call_sid; // jshint ignore:line this.dateEnqueued = deserialize.rfc2822DateTime(payload.date_enqueued); // jshint ignore:line this.position = deserialize.integer(payload.position); // jshint ignore:line this.uri = payload.uri; // jshint ignore:line this.waitTime = deserialize.integer(payload.wait_time); // jshint ignore:line // Context this._context = undefined; this._solution = { accountSid: accountSid, queueSid: queueSid, callSid: callSid || this.callSid, }; }; Object.defineProperty(MemberInstance.prototype, '_proxy', { get: function() { if (!this._context) { this._context = new MemberContext( this._version, this._solution.accountSid, this._solution.queueSid, this._solution.callSid ); } return this._context; } }); /* jshint ignore:start */ /** * fetch a MemberInstance * * @function fetch * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @instance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberInstance.prototype.fetch = function fetch(callback) { return this._proxy.fetch(callback); }; /* jshint ignore:start */ /** * update a MemberInstance * * @function update * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @instance * * @param {object} opts - ... * @param {string} opts.url - The url * @param {string} opts.method - The method * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberInstance.prototype.update = function update(opts, callback) { return this._proxy.update(opts, callback); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @description Initialize the MemberContext * * @param {Twilio.Api.V2010} version - Version of the resource * @param {sid} accountSid - The account_sid * @param {sid} queueSid - The Queue in which to find the members * @param {sid} callSid - The call_sid */ /* jshint ignore:end */ MemberContext = function MemberContext(version, accountSid, queueSid, callSid) { this._version = version; // Path Solution this._solution = { accountSid: accountSid, queueSid: queueSid, callSid: callSid, }; this._uri = _.template( '/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members/<%= callSid %>.json' // jshint ignore:line )(this._solution); }; /* jshint ignore:start */ /** * fetch a MemberInstance * * @function fetch * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @instance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberContext.prototype.fetch = function fetch(callback) { var deferred = Q.defer(); var promise = this._version.fetch({ uri: this._uri, method: 'GET' }); promise = promise.then(function(payload) { deferred.resolve(new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid, this._solution.callSid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * update a MemberInstance * * @function update * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @instance * * @param {object} opts - ... * @param {string} opts.url - The url * @param {string} opts.method - The method * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberContext.prototype.update = function update(opts, callback) { if (_.isUndefined(opts)) { throw new Error('Required parameter "opts" missing.'); } if (_.isUndefined(opts.url)) { throw new Error('Required parameter "opts.url" missing.'); } if (_.isUndefined(opts.method)) { throw new Error('Required parameter "opts.method" missing.'); } var deferred = Q.defer(); var data = values.of({ 'Url': _.get(opts, 'url'), 'Method': _.get(opts, 'method') }); var promise = this._version.update({ uri: this._uri, method: 'POST', data: data }); promise = promise.then(function(payload) { deferred.resolve(new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid, this._solution.callSid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; module.exports = { MemberList: MemberList, MemberPage: MemberPage, MemberInstance: MemberInstance, MemberContext: MemberContext };
gpl-3.0