Regex Using dynamic named subpattern? - regex

I am doing something like this to prepare a dynamic regex.
$mapping = "asa/user/{u}/d/{d}/{f}"; //line 1
$mapper = preg_replace('/\{.*?\}/m','(\w+)',str_replace('/','#',$mapping)); //line 2
preg_match("/".$mapper."/",str_replace('/','#',$input),$arr);
print_r($arr);
which give output like this for $input = /asa/user/ZZA/d/asasa/gh
Array ( [0] => asa#user#ZZA#d#asasa#gh [1] => ZZA [2] => asasa [3] => gh )
What I want is to get something like this.
Array ( [u] => ZZA [d] => asasa [f] => gh )
I know I can do this with using ?P, so trying this
$mapper = preg_replace('/\{.*?\}/m','(?P<name>\w+)',str_replace('/','#',$mapping));
Which obviously would not work as it will use same index name for all params,what i need to do is replace name with u,d,f dynamically.
i can do this with explode i believe, then traversing the array and replace one by one. But is there any better solution to do this type of operation?
At line 2 can read value between braces and then use it as index to replace with?

At line 2 can read value between braces and then use it as index to
replace with?
Yes, by capturing groups () and backrefrences $n.
You should change the second line to:
$mapper = preg_replace('/\{(.*?)\}/m','(?P<$1>\w+)', str_replace('/','#',$mapping));
Which results in:
Array
(
[0] => asa#user#ZZA#d#asasa#gh
[u] => ZZA
[1] => ZZA
[d] => asasa
[2] => asasa
[f] => gh
[3] => gh
)

Related

How to remove double quotes from keys in RDD and split JSON into two lines?

I need to modify the data to give input to CEP system, my current data looks like below
val rdd = {"var":"system-ready","value":0.0,"objectID":"2018","partnumber":2,"t":"2017-08-25 11:27:39.000"}
I need output like
t = "2017-08-25 11:27:39.000
Check = { var = "system-ready",value = 0.0, objectID = "2018", partnumber = 2 }
I have to write RDD map operations to achieve this if anybody suggests better option welcome. colcount is the number of columns.
rdd.map(x => x.split("\":").mkString("\" ="))
.map((f => (f.dropRight(1).split(",").last.toString, f.drop(1).split(",").toSeq.take(colCount-1).toString)))
.map(f => (f._1, f._2.replace("WrappedArray(", "Check = {")))
.map(f => (f._1.drop(0).replace("\"t\"", "t"), f._2.dropRight(1).replace("(", "{"))) /
.map(f => f.toString().split(",C").mkString("\nC").replace(")", "}").drop(0).replace("(", "")) // replacing , with \n, droping (
.map(f => f.replace("\" =\"", "=\"").replace("\", \"", "\",").replace("\" =", "=").replace(", \"", ",").replace("{\"", "{"))
Scala's JSON parser seems to be a good choice for this problem:
import scala.util.parsing.json
rdd.map( x => {
JSON.parseFull(x).get.asInstanceOf[Map[String,String]]
})
This will result in an RDD[Map[String, String]]. You can then access the t field from the JSON, for example, using:
.map(dict => "t = "+dict("t"))

Cakephp sum() with multiplication

Is it possible to find the cakephp with additional condition or can we multiply the sum() field with conditional variable?
I don't know, what could be a best question to let you guys know what I'm asking. so I'm giving a more detail about question. I'm able to find similar data with single array with some trick. but I'm unable to find for this. Please help me or give me an idea to do such task. Thanks.
Using CakePhp 2.6
I want to find data from first table here..
$incentiveweekly=$this->Incentive->find('all',
array('conditions' =>
array(
"AND"=>array(
"Incentive.fromdate >=" => $from,
"Incentive.todate <=" => $to
)
)
)
);
according to number of rows. I have to find another table
Here is the result of above find condition.
Array
(
[Incentive] => Array
(
[id] => 2
[target1] => 3000
[price1] => 1.5
[target2] => 6000
[price2] => 2.5
[target3] => 8000
[price3] => 3.5
[formonth] =>
[type] => 1
[fromdate] => 2016-11-13
[todate] => 2016-11-21
[updatedby] => 1
[created] => 2016-11-15 23:57:21
[modified] => 2016-11-15 23:57:21
)
)
Array
(
[Incentive] => Array
(
[id] => 3
[target1] => 3000
[price1] => 1.5
[target2] => 6000
[price2] => 2.5
[target3] => 8000
[price3] => 3.5
[formonth] =>
[type] => 1
[fromdate] => 2016-11-24
[todate] => 2016-11-28
[updatedby] => 1
[created] => 2016-11-15 23:57:21
[modified] => 2016-11-15 23:57:21
)
)
Now I want to find the array according to number of array record.
$byweek=array(); // Storing Customer data by Target dates in array()
foreach ($incentiveweekly as $weekly){
print_r($weekly);
$target3=$weekly['Incentive']['target3'];
$target2=$weekly['Incentive']['target2'];
$target1=$weekly['Incentive']['target1'];
$price3=$weekly['Incentive']['price3'];
$price2=$weekly['Incentive']['price2'];
$price1=$weekly['Incentive']['price1'];
$byweek[]=$customers=$this->Customer->find('all',array(
'fields'=>array(
'SUM(amount) AS amount',
'created_by'
),
'group' => 'Customer.created_by',
'conditions' => array(
"AND" =>array(
"Customer.created >=" => $weekly['Incentive']['fromdate'],
"Customer.created <=" => $weekly['Incentive']['todate']
)
),
'recursive'=>-1 )
);
//print_r($byweek);
}
I'm getting result like ...
Array
(
[0] => Array
(
[0] => Array
(
[Customer] => Array
(
[created_by] => 3
)
)
)
)
Array
(
[0] => Array
(
[0] => Array
(
[Customer] => Array
(
[created_by] => 3
)
)
)
[1] => Array
(
[0] => Array
(
[Customer] => Array
(
[created_by] => 1
)
)
[1] => Array
(
[Customer] => Array
(
[created_by] => 2
)
)
)
)
But I want that amount would multiply with on the if else condition where I'm using ternary operator.
$value[0]['amount']>=$valuem['Incentive']['target3']?"Target Third":($value[0]['amount']>=$valuem['Incentive']['target2']?"Target Second":($value[0]['amount']>=$valuem['Incentive']['target1']?"Target First":"None"))
Main purpose to find the details are. I want to create an incentive amount where total sales amount should be match with given target amount. If target1 amount one match then incentive would be total amount*price1 and same with target2 and target3. where i'm using tenantry operator. Target price should be multiply(by condition) with the same find condition data.
I search on google and stack overflow but can't find it's solutions. However I'm thankful to stack overflow and all you gusy that i'm able to find a lots of trick and solutions.
I haven't got exactly though you can try with below solution as per my thought,
You need to use WHEN close in MYSQL,
$incenve = 'CASE WHEN amount>5000 THEN "FIRST Target" WHEN amount>3000 THEN "Second Target" ELSE 0 '
and inside fields in above query
'incentive' => $incentive
Thanks Oldskool for this solution Virtualfields with If Condition
Finaly I, Got my solutions by this code bellow. I'm getting result as expected. :)
$this->Customer->virtualFields=array(
'incentive' => "if(SUM(Customer.amount)>=$target3,(SUM(Customer.amount))*$price3,if(SUM(Customer.amount)>=$target2,(SUM(Customer.amount))*$price2,if(SUM(Customer.amount)>=$target1,(SUM(Customer.amount))*$price1,0)))",
);
Now I can use Virtualfied to get the Incentive value.

reading facebook status and storing it in mysql

I am trying to read all the status messages of a user. I have used the following code.
//gets statusid, message and uid of the user
function get_status_message($access_token){
// Run fql query
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q=SELECT+message+,+status_id+,+uid+FROM+status+WHERE+uid=me()'
. '&access_token=' . $access_token;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
//display results of fql query
echo '<pre>';
print_r("query results:");
print_r($fql_query_obj);
echo '</pre>';
return $fql_query_obj;
}
It returns the following
query results:Array
(
[data] => Array
(
[0] => Array
(
[message] => test3
[status_id] => 5.0606879274642E+14
[uid] => 1.0000029926744E+14
)
[1] => Array
(
[message] => test2
[status_id] => 5.060443560822E+14
[uid] => 1.0000029926744E+14
)
[2] => Array
(
[message] => testing !
[status_id] => 5.0304255638238E+14
[uid] => 1.0000029926744E+14
)
)
)
I have to retrieve the status id and put it in mysql db. I tried foreach but I am unable to loop. The code below works
but I need to explicitly give the first index value as $value*[0]*["status_id"]. Can someone please help
You need to check if the Facebook call actually retrieved data for you to process then loop through the result and insert to your DB, with something like:
if(!empty($fql_query_obj['data'])) {
foreach($fql_query_obj['data'] as $status) {
$status_id = $status['status_id'];
// create SQL insert batch
}
// Run the insert batch
}

Array Issue with QueryBuilder Doctrine2

I have a Problem with the Querybuilder,
$qb = $this->_em->createQueryBuilder();
$qb->select('k, l')
-> i got a array such as
Array
(
[0] => Array
(
[id] => 15
-> ok
when i do
$qb->select('k.id, l.title')->add('from', 'Base\Entities\Company k')
i get
Array
(
[0] => Array
(
[id] => 15
[title] =>
)
-> ok
ISSUE:
When id do:
$qb->select('k, l.title')->add('from', 'Base\Entities\Company k')
i get:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 15
i always do $result = $query->getArrayResult(); at the End
how can i remove the array in the array? i only want title as part of the array in k (like above)
I believe it's not really possible to do so, You'll have to iterate over the results to achieve this. You can read more about it in documentation.

Easily parsable output from rrdtool

I'm working with a large bunch of RRD-files, where I have to query the data quite a lot - and mostly by reading all the data and pass it on.
Currently, I use rrdtool fetch <filename> CF --start XXX --end YYY, but as it only returns data for one CF at a time, I first have to do a separate query to find the CF's (= run and parse rrdtool info <filename>) and then run rrdtool fetch for each found CF. The output is trivial to parse, though.
Alternately, there is rrdtool xport DEF:XX=<filename>:RRA:CF ... XPORT:XX:XX ... with multiple "sets" of the latter commands for each thing I want. On the upside, this can give me all the data in one go, but I still need to have a fairly good idea about what data I want beforehand. Also, it only spits out XML (always a hassle to parse).
I have a feeling I'm missing something very obvious, as it simply can't be such a big hassle to get a list of timestamp → numbers out of a file... Any clues?
While there are patches around for adding JSON-support, there is currently no way around:
Parsing at least two different output formats (rrdtool info's ASCII and then either XML from rrdtool xport or tabular data from rrdtool fetch).
Dumping the entire contents of the file to XML via rrdtool dump and then re-implementing quite a bit of librrd's internals.
I've written a parser that turns the output of rrdtool info /tmp/pb_1_amp.rrd into a nested array. So from:
filename = "/tmp/pb_1_amp.rrd"
rrd_version = "0003"
step = 1800
last_update = 1372685403
header_size = 1208
ds[amp].index = 0
ds[amp].type = "GAUGE"
ds[amp].minimal_heartbeat = 3200
ds[amp].min = 0.0000000000e+00
ds[amp].max = 1.0000000000e+02
ds[amp].last_ds = "5.6"
ds[amp].value = 1.6800000000e+01
ds[amp].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].rows = 576
rra[0].cur_row = 385
rra[0].pdp_per_row = 1
rra[0].xff = 5.0000000000e-01
rra[0].cdp_prep[0].value = NaN
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[1].cf = "AVERAGE"
rra[1].rows = 672
rra[1].cur_row = 159
rra[1].pdp_per_row = 6
rra[1].xff = 5.0000000000e-01
rra[1].cdp_prep[0].value = 1.6999833333e+01
rra[1].cdp_prep[0].unknown_datapoints = 0
rra[2].cf = "AVERAGE"
rra[2].rows = 732
rra[2].cur_row = 639
rra[2].pdp_per_row = 24
rra[2].xff = 5.0000000000e-01
rra[2].cdp_prep[0].value = 1.6999833333e+01
rra[2].cdp_prep[0].unknown_datapoints = 0
rra[3].cf = "AVERAGE"
rra[3].rows = 1460
rra[3].cur_row = 593
rra[3].pdp_per_row = 144
rra[3].xff = 5.0000000000e-01
rra[3].cdp_prep[0].value = 6.6083527778e+02
rra[3].cdp_prep[0].unknown_datapoints = 0
to:
Array
(
[filename] => /tmp/pb_1_amp.rrd
[rrd_version] => 0003
[step] => 1800
[last_update] => 1372685403
[header_size] => 1208
[ds] => Array
(
[amp] => Array
(
[index] => 0
[type] => GAUGE
[minimal_heartbeat] => 3200
[min] => 0.0000000000e+00
[max] => 1.0000000000e+02
[last_ds] => 5.6
[value] => 1.6800000000e+01
[unknown_sec] => 0
)
)
[rra] => Array
(
[0] => Array
(
[cf] => AVERAGE
[rows] => 576
[cur_row] => 385
[pdp_per_row] => 1
[xff] => 5.0000000000e-01
[cdp_prep] => Array
(
[0] => Array
(
[value] => NaN
[unknown_datapoints] => 0
)
)
)
[1] => Array
(
[cf] => AVERAGE
[rows] => 672
[cur_row] => 159
[pdp_per_row] => 6
[xff] => 5.0000000000e-01
[cdp_prep] => Array
(
[0] => Array
(
[value] => 1.6999833333e+01
[unknown_datapoints] => 0
)
)
)
[2] => Array
(
[cf] => AVERAGE
[rows] => 732
[cur_row] => 639
[pdp_per_row] => 24
[xff] => 5.0000000000e-01
[cdp_prep] => Array
(
[0] => Array
(
[value] => 1.6999833333e+01
[unknown_datapoints] => 0
)
)
)
[3] => Array
(
[cf] => AVERAGE
[rows] => 1460
[cur_row] => 593
[pdp_per_row] => 144
[xff] => 5.0000000000e-01
[cdp_prep] => Array
(
[0] => Array
(
[value] => 6.6083527778e+02
[unknown_datapoints] => 0
)
)
)
)
)
It's in PHP but it should be easy to port to any other language. Here's the code:
$store = array();
foreach ($lines as $line) {
list($raw_key, $raw_val) = explode(' = ', $line);
$keys = preg_split('/[\.\[\]]/', $raw_key, -1, PREG_SPLIT_NO_EMPTY);
$key_count = count($keys);
$pointer = &$store;
foreach ($keys as $key_num => $key) {
if (!array_key_exists($key, $pointer)) {
$pointer[$key] = array();
}
$pointer = &$pointer[$key];
if ($key_num+1 === $key_count) {
$pointer = trim($raw_val, '"');
}
}
}
It assumes the rrdtool info output is split by newline (\n) and found in $lines. Hope this helps.
If you want the 'table of contents' use rrdtool info, if you want the whole content, use rrdtool dump.
BUT ... why would you want that?
cheers
tobi