Proper way to format for multiple domains in KRL search annotation - krl

I am configuring a rule in KRL to annotate based on results of 2+ distinct domains showing in the search results. The first domain works fine, but adding a 2nd or more breaks the rule. Sample of the code I'm using below - is there another way to list these domains?
rule search_annotate_cust is active {
select using "google.com|bing.com/search|search.yahoo.com/search" setting()
every {
emit <<
function annotate_cust(toAnnotate, wrapper, data) {
if (data.domain == "exampleurl.com" ||
(data.domain == "anotherurl.com" ||
(data.domain == "sub.exampleurl.com) {
wrapper.append("<div style='border: 0px solid red'><img src=http://www.example.com/uploads/product/cust_icon.jpg>");
wrapper.show();
}
}
>>;
annotate:annotate("cust") with
annotator = <| annotate_cust |>;
}
}

Related

Set custom filters for boost log sink with custom attribute & severity level

I have a log setup in which I have 2 types of log messages:
1 based solely on severity level
1 based solely on a custom tag attribute
These attributes are defined as follows:
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
I want to create a filter function that allows a message to be added to my log based on either of the 2 criteria (note that the log messages based on the custom tag attribute are always printed with severity level info, based on the trivial logger's severity levels).
So I want to have a filter, which allows a message based on if a message has the custom tag, and if it does not have it, based on the severity of the message.
I have tried to have a relative simple filter which does the following:
sink_->set_filter(
trivial::severity >= severityLevel
|| (expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_)
);
But as it is possible that the severityLevel can be either Debug, Info, Warning, Error or Fatal, if the level is configured as either Debug or Info, the custom tag attribute is ignored by the filter.
I have tried using a c++11 lambda, as following:
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (<condition for custom tag first>) {
return true;
} else if (<condition for severity level second>) {
return true;
} else {
return false;
}
});
But then I don't have an idea on how to actually check for my conditions. I have tried the following:
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
But the compiler throws several errors about this:
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:127:48: error: expected primary-expression before '>' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:127:50: error: expected primary-expression before ')' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:129:72: error: expected primary-expression before '>' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp:129:74: error: expected primary-expression before ')' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:134:5: error: control reaches end of non-void function [-Werror=return-type]
});
^
cc1plus: all warnings being treated as errors
scons: *** [obj/release/Core/Source/Log/Logger.os] Error 1
====5 errors, 0 warnings====
I have been scouring the boost log documentation about extracting the attributes myself, but I cannot find the information I need.
EDIT:
For posterity, I'll add how I've solved my issue (with thanks to the given answer by Andrey):
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (attr_set[tag_attr] == "JSON") {
return logJson_;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
});
The filter can be written in multiple ways, I will demonstrate a few alternatives.
First, using expression templates you can write it this way:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_) ||
trivial::severity >= severityLevel
);
Following the normal short-circuiting rules of C++, the tag attribute will be tested first and if that condition succeeds, the severity will not be tested. If the tag is not present or not JSON or logJson_ is not true, then severity level is tested.
Note that the filter above will save copies of its arguments (including logJson_ and severityLevel) at the point of construction, so if you change logJson_ later on the filter will keep using the old value. This is an important difference from your later attempts with C++14 lambdas, which access logJson_ via the captured this pointer. If you actually want to save a reference to your member logJson_ in the filter, you can use phoenix::ref:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && boost::phoenix::ref(logJson_)) ||
trivial::severity >= severityLevel
);
However, you should remember that the filter can be called concurrently in multiple threads, so the access to logJson_ is unprotected. You will have to implement your own thread synchronization if you want to update logJson_ in run time.
Barring multithreading issues, your second attempt with a lambda is almost correct. The compiler is complaining because the lambda function is a template, and the result of attr_set["Tag"] expression depends on one of the template parameters (namely, the type of attr_set). In this case, the programmer has to qualify that the following extract<std::string>() expression is a template instantiation and not a sequence of comparisons. This is done by adding a template keyword:
if (attr_set["Tag"].template extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].template extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
Note that you could use a standalone function to the same effect, which wouldn't require the template qualification:
if (boost::log::extract<std::string>("Tag", attr_set) == "JSON" && logJson_) {
return true;
} else if (boost::log::extract<trivial::severity_level>("Severity", attr_set) >= severityLevel) {
return true;
} else {
return false;
}
Finally, the preferred way to extract attribute values is to leverage attribute keywords, which you declared previously. Not only this allows to avoid the template qualification quirk but it also removes a lot of code duplication.
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
if (attr_set[tag_attr] == "JSON" && logJson_) {
return true;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
The attribute value name and type are inferred from the keyword declaration in this case. This use of attribute keywords is documented at the end of this section.

Firestore Security Rules: request.time "undefined on object"

I'm trying to create a Security Rule based upon request.time as given in an example on AngularFirebase website.
My function is
function isThrottled() {
return request.time < resource.data.lastUpdate + duration.value(1, 'm')
}
Where I'm trying to allow update: if isThrottled() == false
However, when I try to update a document with this rule, it fails due to time being not defined on the object.
Error: simulator.rules line [169], column [12]. Property time is
undefined on object.
Shouldn't every request have a time or TimeStamp attached to it? Is this something to do with how I'm initializing my Cloud Functions or client app?
Screenshots below:
EDIT
A snippet for the rest of the update security rules are:
service cloud.firestore {
match /databases/{db}/documents {
match /users/{userId} {
match /username/{id} {
allow update: if isSelf(userId)
&& usernameAvailable(incomingData().username)
&& incomingData().username is string
&& incomingData().username.size() <= 25
&& incomingFields().size() == 1
&& isThrottled() == false;
}
}
function incomingData() {
return request.resource.data
}
function isThrottled() {
return request.time < resource.data.lastUpdate + duration.value(1, 'm')
}
function incomingFields() {
return incomingData().keys()
}
function isSelf(userId) {
return userId == currentUser().uid;
}
function usernameAvailable(username) {
return !exists(/databases/$(db)/documents/usernames/$(username));
}
}
}
The username collection is a subcollection under each user document (in the users root collection. Each username document only has 1 field called username that users can update).
This might not be useful for your case in particular, but I had the same error when checking a custom claim on the token object.
Before accessing the field you can use in to check whether the property exists on the object. This code generates the error if agent is not defined:
allow write: if request.auth != null && request.auth.token.agent == true;
This code works fine if agent is not defined:
allow write: if request.auth != null && "agent" in request.auth.token && request.auth.token.agent == true;

How I can get search form value in Drupal 7

I've tried to implement a new module that catches the keys written in the default search form and displays other results than the default search result page. With these other results I will make an external query, which is put in a special block.
Any idea on how to do this?
I've tried to use a custom module making a "hook_alter_form " with no success.
In other words :
I have a function like this:
function my_function_name_form_alter(&$form,&$form_state,$form_id){
switch($form_id){
case 'search-block-form':
//Here i want to catch the text that i wrote in the search box
break;
}
}
Thank u!
You can alter the search query in order to show other results:
function mymodule_query_alter(QueryAlterableInterface $query){
$is_search = FALSE;
foreach ($query->getTables() as $table) {
if ($table['table'] == 'search_index') {
$is_search = TRUE;
}
}
if ($is_search) {
global $language;
$db_or = db_or();
$db_or->condition('n.type', 'event', '=');
$db_or->condition('n.type', 'real_sitio', '=');
$query->condition($db_or);
$query->condition('n.language' , $language->language, '=');
}
}
This is a bit performance killer so there's a patch for drupal at http://drupal.org/node/1435834 that adds a hook for making the alter directly in the search query:
So finally it would look like:
function mymodule_search_query_search_node_alter(&$query) {
$query->condition('n.type', 'article', '=');
}

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.

How can I tell if a <script> tag with a given src attribute is present on the page in ASP.net?

Like the title says, I'm trying to find out if I need to include a script library that my ASP.net UserControl needs to work. I don't want to include it multiple times per page, but I want my control to be able to be used multiple times on the same page.
How can I, in the codebehind of my control, check to see if a given <script/> tag is present?
This is .Net 2.0, no LINQ.
If !Page.ClientScript.IsClientScriptIncludeRegistered("jQuery")
Page.ClientScript.RegisterClientScriptInclude("jQuery", "/scripts/jquery.js");
or if you need a script block, And want to include the control's type:
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "myScript"))
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myScript"
, "<script>alert('xx');</script>", false);
This might be a bit overkill for your usage, but I'm using it to search for existing CSS and JS before adding to the page:
private static bool HeaderLinkExists(Page page, string path)
{
path = path.ToLowerInvariant();
foreach (Control c in page.Header.Controls)
{
if (c is HtmlLink)
{
// stylesheet (or other links), check href
HtmlLink link = (HtmlLink)c;
if (link.Href.ToLowerInvariant().Contains(path))
{
return true;
}
}
else if (c is HtmlGenericControl)
{
// any generic html tag, check for src or href
HtmlGenericControl hgc = (HtmlGenericControl)c;
if ((!string.IsNullOrEmpty(hgc.Attributes["src"]) && hgc.Attributes["src"].ToLowerInvariant().Contains(path)) || (!string.IsNullOrEmpty(hgc.Attributes["href"]) && hgc.Attributes["href"].ToLowerInvariant().Contains(path)))
{
return true;
}
}
else if (c is LiteralControl)
{
// scripts or other html literal controls, use regex to look for src or hrefs and check each one
LiteralControl lit = (LiteralControl)c;
if (MatchLiteralText(lit.Text, path))
{
return true;
}
}
else if (c is Literal)
{
// similar to above, use regex to look for src or hrefs and check each one
Literal lit = (Literal)c;
if (MatchLiteralText(lit.Text, path))
{
return true;
}
}
}
return false;
}
private static readonly Regex linkMatcher = new Regex(#"(?:src|href)\s*=\s*([""']?)(?<LinkValue>[^\1]+?)[\1>]", RegexOptions.Compiled);
private static bool MatchLiteralText(string text, string path)
{
if (!string.IsNullOrEmpty(text))
{
text = text.ToLowerInvariant()
foreach (Match m in linkMatcher.Matches(text))
{
if (m.Groups["LinkValue"].Value.Contains(path))
{
return true;
}
}
}
return false;
}
// usage:
if (!HeaderLinkExists(page, "/css/controlstyles.css"))
{
HtmlHeadUtility.RegisterStylesheetInHeader(page, "~/css/controlstyles.css");
}
if (!HeaderLinkExists(page, "/js/controlscript.js"))
{
HtmlHeadUtility.RegisterClientScriptIncludeInHeader(page, "~/js/controlscript.js");
}
It works great if you're sure that the LINK or SCRIPT is guaranteed to be in the HEAD.
No, there isn't.
Instead, you should maintain a set of <script> tags that have already been included, and update it whenever you add a script. (For example, a [ThreadStatic] static List<String>)
I would suggest re-thinking your problem/solution. It seems like what you are trying to do would couple your user control and the pages that use it. This would require that a page reference that script in order to use a control.
Is there any reason you can't just put the script tag in your user control so that the pages consuming your user control don't need to know that they need to include a specific script tag to work?
I tend to think that if you want to just use a control you should be able to just use it.