Macro match arm pattern "no rules expected the token `if`" - error-handling

So i have this macro thats used to match Box<dyn error::Error> against multiple error types
#[macro_export]
macro_rules! dynmatch {
($e:expr, $(type $ty:ty {$(arm $pat:pat => $result:expr),*, _ => $any:expr}),*, _ => $end:expr) => (
$(
if let Some(e) = $e.downcast_ref::<$ty>() {
match e {
$(
$pat => {$result}
)*
_ => $any
}
} else
)*
{$end}
);
}
It was working fine until i tried adding match gaurds. when i try using "if" statements in the pattern it gives me the error no rules expected the token 'if'
let _i = match example(2) {
Ok(i) => i,
Err(e) => {
dynmatch!(e,
type ExampleError1 {
arm ExampleError1::ThisError(2) => panic!("it was 2!"),
_ => panic!("{}",e)
},
type ExampleError2 {
arm ExampleError2::ThatError(8) => panic!("it was 8!"),
arm ExampleError2::ThatError(9..=11) => 10,
_ => panic!("{}",e)
},
type std::io::Error {
arm i if i.kind() == std::io::ErrorKind::NotFound => panic!("not found"), //ERROR no rules expected the token `if`
_ => panic!("{}", e)
},
_ => panic!("{}",e)
)
}
};
Is there any way to use match guards in my pattern matching without getting token errors?

and of course, even though i spent like an hour looking for a solution, right after i post this question i find an answer.
the correct macro looks like:
#[macro_export]
macro_rules! dynmatch {
($e:expr, $(type $ty:ty {$(arm $( $pattern:pat )|+ $( if $guard: expr )? => $result:expr),*, _ => $any:expr}),*, _ => $end:expr) => (
$(
if let Some(e) = $e.downcast_ref::<$ty>() {
match e {
$(
$( $pattern )|+ $( if $guard )? => {$result}
)*
_ => $any
}
} else
)*
{$end}
);
}
credit to the rust matches! source lines 244-251

Related

Prestashop 1.7.7 - HelperForm in a Multistore Context

I'm testing a first simple version for a Multistore-compatible module. It has just two settings, which have to be saved differently depending on the current shop Context (a single shop mainly).
Now, I know that from 1.7.8 there are additional checkbox for each setting in the BO Form, but I have to manage to get it work also for 1.7.7.
Now, both Configuration::updateValue() and Configuration::get() should be multistore-ready, meaning that they update or retrieve the value only for the current context, so it should be fine.
The weird thing is that, after installing the test module, if I go to the configuration page, it automatically redirects to an All-Shop context and, if I try to manually switch (from the dropdown in the top right), it shows a blank page. Same thing happens if I try to deactivate the bottom checkbox "Activate this module in the context of: all shops".
Here is my code:
class TestModule extends Module
{
public function __construct()
{
$this->name = 'testmodule';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'Test';
$this->need_instance = 1;
$this->ps_versions_compliancy = [
'min' => '1.7.0.0',
'max' => '1.7.8.0',
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l("Test Module");
$this->description = $this->l('Collection of custom test extensions');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TESTM_v')) {
$this->warning = $this->l('No version provided');
}
}
public function install()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return (
parent::install()
&& $this->registerHook('header')
&& $this->registerHook('backOfficeHeader')
&& Configuration::updateValue('TESTM_v', $this->version)
);
}
public function uninstall()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return (
parent::uninstall()
&& $this->unregisterHook('header')
&& $this->unregisterHook('backOfficeHeader')
&& Configuration::deleteByName('TESTM_v')
);
}
public function getContent()
{
// this part is executed only when the form is submitted
if (Tools::isSubmit('submit' . $this->name)) {
// retrieve the value set by the user
$configValue1 = (string) Tools::getValue('TESTM_CONFIG_1');
$configValue2 = (string) Tools::getValue('TESTM_CONFIG_2');
// check that the value 1 is valid
if (empty($configValue1)) {
// invalid value, show an error
$output = $this->displayError($this->l('Invalid Configuration value'));
} else {
// value is ok, update it and display a confirmation message
Configuration::updateValue('TESTM_CONFIG_1', $configValue1);
$output = $this->displayConfirmation($this->l('Settings updated'));
}
// check that the value 2 is valid
Configuration::updateValue('TESTM_CONFIG_2', $configValue2);
$output = $this->displayConfirmation($this->l('Settings updated'));
}
// display any message, then the form
return $output . $this->displayForm();
}
public function displayForm()
{
// Init Fields form array
$form = [
'form' => [
'legend' => [
'title' => $this->l('Settings'),
],
'input' => [
[
'type' => 'text',
'label' => $this->l('Custom CSS file-name.'),
'name' => 'TESTM_CONFIG_1',
'size' => 20,
'required' => true,
],
[
'type' => 'switch',
'label' => $this->l('Enable custom CSS loading.'),
'name' => 'TESTM_CONFIG_2',
'is_bool' => true,
'desc' => $this->l('required'),
'values' => array(
array(
'id' => 'sw1_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'sw1_off',
'value' => 0,
'label' => $this->l('Disabled')
)
)
],
],
'submit' => [
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right',
],
],
];
$helper = new HelperForm();
// Module, token and currentIndex
$helper->table = $this->table;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&' . http_build_query(['configure' => $this->name]);
$helper->submit_action = 'submit' . $this->name;
// Default language
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
// Load current value into the form or take default
$helper->fields_value['TESTM_CONFIG_1'] = Tools::getValue('TESTM_CONFIG_1', Configuration::get('TESTM_CONFIG_1'));
$helper->fields_value['TESTM_CONFIG_2'] = Tools::getValue('TESTM_CONFIG_2', Configuration::get('TESTM_CONFIG_2'));
return $helper->generateForm([$form]);
}
/**
* Custom CSS & JavaScript Hook for FO
*/
public function hookHeader()
{
//$this->context->controller->addJS($this->_path.'/views/js/front.js');
if (Configuration::get('TESTM_CONFIG_2') == 1) {
$this->context->controller->addCSS($this->_path.'/views/css/'.((string)Configuration::get('TESTM_CONFIG_1')));
} else {
$this->context->controller->removeCSS($this->_path.'/views/css/'.((string)Configuration::get('TESTM_CONFIG_1')));
}
}
}
As you can see it's a pretty simple setting: just load a custom CSS file and choose if loading it or not. I've red official PS Docs per Multistore handling and searched online, but cannot find an answer to this specific problem.
I've also tried to add:
if (Shop::isFeatureActive()) {
$currentIdShop = Shop::getContextShopID();
Shop::setContext(Shop::CONTEXT_SHOP, $currentIdShop);
}
To the 'displayForm()' function, but without results.
Thank you in advance.
It seemsit was a caching error.
After trying many variations, I can confirm that the first solution I've tried was the correct one, meaning that:
if (Shop::isFeatureActive()) {
$currentIdShop = Shop::getContextShopID();
Shop::setContext(Shop::CONTEXT_SHOP, $currentIdShop);
}
needs to be added ad the beginning of the "displayForm()" function for it to work when selecting a single shop. Values are now correctly saved in the database. With a little bit extra logic it can be arranged to behave differently (if needed) when saving for "All shops" context.

Create field from file name condition in logstash

I have several logs with the following names, where [E-1].[P-28], [E-1].[P-45] and [E-1].[P-51] are operators that generate these logs (They do not appear within the data. I can only identify them by obtaining from the file name)
p2sajava131.srv.gva.es_11101.log.online.[E-1].[P-28].21.01.21.log
p1sajava130.srv.gva.es_11101.log.online.[E-1].[P-45].21.03.04.log
p1sajava130.srv.gva.es_11101.log.online.[E-1].[P-51].21.03.04.log
...
is it posible to use translate filter create a new field?
somethink like:
translate{
field => "[log.file.path]"
destination => "[operator_name]"
dictionary => {
if contains "[E-1].[P-28]" => "OPERATOR-1"
if contains "[E-1].[P-45]" => "OPERATOR-2"
if contains "[E-1].[P-51]" => "OPERATOR-3"
thanx
I don't have ELK here so I can't test but this should works
if [log][file][path] =~ "[E-1].[P-28]" {
mutate {
add_field => { "[operator][name]" => "OPERATOR-1" }
}
}
if [log][file][path] =~ "[E-1].[P-45]" {
mutate {
add_field => { "[operator][name]" => "OPERATOR-2" }
}
}
if [log][file][path] =~ "[E-1].[P-51]" {
mutate {
add_field => { "[operator][name]" => "OPERATOR-3" }
}
}

Error when I try to create index in elastic search from logstash

Hi Im getting the following error when I try to create index in ElasticSearch from logstash:
[Converge PipelineAction::Create] agent - Failed to execute action
{:action=>LogStash::PipelineAction::Create/pipeline_id:main,
:exception=>"LogStash::ConfigurationError", :message=>"Expected one of #, input, filter, output at
line 1, column 1 (byte 1)"
Can you tell me if I got something wrong in my .conf file
iput {
file {
path => "/opt/sis-host/process/uptime_test*"
# start_position => "beginning"
ignore_older => 0
}
}*emphasized text*
filter {
grok {
match => { "message" => "%{DATA:hora} %{DATA:fecha} %{DATA:status} %{DATA:server} %
{INT:segundos}" }
}
date {
match => ["horayfecha", "HH:mm:ss MM/dd/YYYY" ]
target => "#timestamp"
}
}
output {
elasticsearch {
hosts => ["host:9200"]
index => "uptime_test-%{+YYYY.MM.dd}"
}
stdout { codec => rubydebug }
}
The configuration file should start with input and not "iput"
input { # not iput
file {
path => "/opt/sis-host/process/uptime_test*"
# start_position => "beginning"
ignore_older => 0
}
}
filter {
grok {
match => { "message" => "%{DATA:hora} %{DATA:fecha} %{DATA:status} %{DATA:server} %
{INT:segundos}" }
}
date {
match => ["horayfecha", "HH:mm:ss MM/dd/YYYY" ]
target => "#timestamp"
}
}
output {
elasticsearch {
hosts => ["host:9200"]
index => "uptime_test-%{+YYYY.MM.dd}"
}
stdout { codec => rubydebug }
}

SQL query for restoring the latest revision on all posts in wordpress

My wordpress site recently got attacked and all the posts seem to have been updated with a blank version. So I want to restore the most latest revision for all posts. (NB: In wordpress the current published version is also stored in the database as a revision. So I think I would need to restore the 2nd revision (when arranged in the descending order))
What would be the SQL query for that?
Any help would be greatly appreciated!
So, all you need is in your database (luckily). The posts themselves can be retrieved like this
global $wpdb;
$query = "SELECT * FROM wp_posts WHERE post_type = 'revision'";
$query_results = $wpdb->get_results($query, ARRAY_A);
foreach ($query_results as $q_key => $q_value) {
$post = array(
'post_content' => $q_value['post_content']
'post_name' => $q_value['post_name']
'post_title' => $q_value['post_title']
'post_status' => $q_value['post_status']
'post_type' => 'post'
'post_author' => $q_value['post_author']
'ping_status' => $q_value['ping_status']
'post_parent' => $q_value['post_parent']
'menu_order' => $q_value['menu_order']
'to_ping' => $q_value['to_ping']
'pinged' => $q_value['pinged']
'post_password' => $q_value['post_password']
'guid' => $q_value['guid']
'post_content_filtered' => $q_value['post_content_filtered']
'post_excerpt' => $q_value['post_excerpt']
'post_date' => $q_value['post_date']
'post_date_gmt' => $q_value['post_date_gmt']
'comment_status' => $q_value['comment_status']
);
wp_insert_post( $post );
}
Read about wp_insert_post() here.
Now, depending on how much posts you have, this can either take a while, or it can break. If it breaks, then you'll need to wrap this in a function that you'll call with AJAX. Something like this should do the trick:
add_action( 'wp_ajax_insert_posts', 'database_ajax_insert_posts' );
add_action( 'wp_ajax_nopriv_insert_posts', 'database_ajax_insert_posts' );
function database_ajax_insert_posts(){
global $wpdb;
$offset = $_POST['offset'];
$query = "SELECT * FROM wp_posts WHERE post_type = 'revision' LIMIT $offset, 1";
$query_results = $wpdb->get_results($query, ARRAY_A);
foreach ($query_results as $q_key => $q_value) {
$post = array(
'post_content' => $q_value['post_content']
'post_name' => $q_value['post_name']
'post_title' => $q_value['post_title']
'post_status' => $q_value['post_status']
'post_type' => 'post'
'post_author' => $q_value['post_author']
'ping_status' => $q_value['ping_status']
'post_parent' => $q_value['post_parent']
'menu_order' => $q_value['menu_order']
'to_ping' => $q_value['to_ping']
'pinged' => $q_value['pinged']
'post_password' => $q_value['post_password']
'guid' => $q_value['guid']
'post_content_filtered' => $q_value['post_content_filtered']
'post_excerpt' => $q_value['post_excerpt']
'post_date' => $q_value['post_date']
'post_date_gmt' => $q_value['post_date_gmt']
'comment_status' => $q_value['comment_status']
);
wp_insert_post( $post );
}
}
And AJAX
jQuery(document).ready(function($) {
"use strict";
var offset = 1;
function ajax_call(){
$.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'insert_posts',
'offset': offset,
},
success: function(response) {
if (offset < 100){ //Number of posts go here
offset += 1;
ajax_call();
} else{
$('#wpbody-content').append('<p>All done!</p>' );
}
},
error : function (jqXHR, textStatus, errorThrown) {
$('#wpbody-content').html(jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown);
}
});
}
ajax_call();
});
Also be sure to localize your AJAX url with the handle of the script in which you'll put your AJAX call.
wp_localize_script('your_handle', 'db_from_WP', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
Taxonomy should be in the database, and you could get them in a similar fashion.
This is not foolproof, but should work. The thing that I can see that could be a bit problematic is getting the right taxonomy for the post, but that is doable, although with a bit fiddling around.
Hope this helps.

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920