I am having dictionary like this.
print Dumper($emp)
$VAR1 = {
'mike' => {
'country' => {
'US' => {
'pop' => 100
}
}
}
}
I want to append a new entry inside 'country' like this.
$VAR1 = {
'mike' => {
'country' => {
'US' => {
'pop' => 100
},
'Canada' => {
'pop' => 101
}
}
}
}
Right now I am building it like this
$emp -> {$name}{country} = getCountry();
sub getCountry{
....
return country;
}
It's not clear what getCountry returns. Seeing as it's a single scalar, I'm going to assume it's a hash of countries keyed by name despite the name.
{ Canada => { pop => 101 } }
A simple way to merge two hashes is
%h = ( %h, %new );
so
%{ $emp->{$name}{country} } = (
%{ $emp->{$name}{country} },
%{ getCountry() },
);
If getCountry were to return the country's name and the country, you'd could use the following:
my ($country_name, $country) = getCountry();
$emp->{$name}{country}{$country_name} = $country;
So, if the hash returned by getCountry returns just a single country, you could also do the following without changing getCountry:
my ($country_name, $country) = %{ getCountry() };
$emp->{$name}{country}{$country_name} = $country;
Related
I have a hash variable as a tree:
\%data = {
'node' => {
'RN:4' => {
'next' => {
'1' => {
'RN:23' => {
'next' => {
'1' => {
'RN:29' => {
'end' => 1
}
},
'2' => {
'RN:32' => {
'next' => {
'1' => {
'RN:30' => {
'end' = 1
}
}
}
}
}
}
I want to convert this tree to correct paths like this:
1, RN:4 >> RN:23 >> RN:29
2, RN:4 >> RN:23 >> RN:32 >> RN:30
I have tried some recursive code but alway get wrong path.
Help me please !
The data structure is wholly too complicated. Hashes are being used as arrays, and it would be easier if the id wasn't used as the key. It would be better if a node looked like this:
{
id => ...,
children => [ ... ]
}
The structure would become
[
{
id => 'RN:4',
children => [
{
id => 'RN:23',
children => [
{
id => 'RN:29',
children => []
},
{
id => 'RN:32',
children => [
{
id => 'RN:30',
children => []
}
]
}
]
}
]
}
]
You need the id of all ancestors so we pass a long a list of the ancestors as the parameters.
use 5.016;
sub print_paths {
my $i = 0;
my $helper = sub {
my $node = $_[-1];
my $children = $node->{children};
if (#$children) {
__SUB__->(#_, $_) for #$children;
} else {
say $i, ", ", join(" >> ", map { $_->{id} } #_);
}
};
$helper->(#_);
}
print_paths($_) for #$roots;
The above assumes the ends are the nodes with no children. If your ends can have children, you have a trie. Simply add end => 1 to the end nodes and use the following as the core of the visitor:
if (#$children) {
__SUB__->(#_, $_) for #$children;
}
if ($node->{end}) {
say $i, ", ", join(" >> ", map { $_->{id} } #_);
}
With your format, it's trickier (and more expensive).
$node->{id} is replaced with (keys(%$node))[0].
$node->{children} is replaced with $node->{$id}{next}.
$node->{end} is replaced with $node->{$id}{end}.
for my $child (#$children) is replaced with for (my $j=1; my $child = $children->{$j}; ++$j).
use 5.016;
sub print_paths {
my $i = 0;
my $helper = sub {
my $node = $_[-1];
my $id = (keys(%$node))[0];
my $children = $node->{$id}{next};
if ($children) {
for (my $j=1; my $child = $children->{$j}; ++$j) {
__SUB__->(#_, $child) for #$children;
}
}
if ($node->{$id}{end}) {
say $i, ", ", join(" >> ", map { (keys(%$node))[0] } #_);
}
};
$helper->(#_);
}
print_paths($data->{node});
I have a SQL query that return the result to List
public class WebTrafficStat
{
public string Group { get; set; }
public string Stat { get; set; }
public string Total { get; set; }
public bool? IsSubTotal { get; set; }
}
The result must be displayed as HTML Pivot table with either results grouped by "Stat" or "Group" field.
SQL result:
Desired result as HTML
I did the functions that does this PHP but now the project must be written in MVC Core
This is my PHP functions that I used currently
I grouped the array from SQL call results here:
function array_group_by(array $arr, $gElement, $gkey) {
$refined = $arr;
$result = array();
foreach ($arr[$gElement] as $data) {
$id = $data[$gkey];
if ( isset($data[$gkey]) && !empty($data[$gkey]) ) {
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
}
if ( !empty($result) ) {
$refined[$gElement] = array();
foreach($result as $key=>$value) {
$refined[$gElement][] = array('name' => $key, 'childs' => $value);
}
$refined['grouped'] = 1;
}
return $refined;
}
And second function is
function grouped_array_to_html ($grouped, $groupField ){
$tableRows = array();
$columns = array();
$Row_Data = array();
if ( $grouped['grouped'] == 1 ){ // grouping found
$columns[] = 'Group';
// table columns/headers
foreach ($grouped['rows'] as $row) {
foreach ($row['childs'] as $child) {
if ( !in_array($child[$groupField], $columns ) ){
$columns[] = $child[$groupField];
}
}
}
//table rows
foreach ($grouped['rows'] as $a => $row) {
$tableRows[$a][] = $row['name'];
foreach ($row['childs'] as $c => $child) {
foreach ($columns as $x => $col){
if ( $col == $child[$groupField] )
{
$tableRows[$a][$x] = $child['total'];
break;
}
}
}
}
//Output Finale
foreach ( $tableRows as $b => $tr )
{
foreach ($columns as $c => $col) {
if ( !isset($tableRows[$b][$c]) )
$Row_Data[$b][$c] = '-';
else
$Row_Data[$b][$c] = $tableRows[$b][$c];
}
}
} else { // no grouping
foreach ($grouped['rows'] as $row) {
$Row_Data[] = $row;
}
}
$htmlOut = array(
'theaders' => $columns,
'trows' => $Row_Data
);
$grouped['rows']['html'] = $htmlOut;
return $grouped;
}
And I call PHP like this ... this gives me HTML table header rows and Body rows
In this case, I tell it to group by "Stat" column
$result = grouped_array_to_html( array_group_by($response, 'rows', 'group'), 'stat' );
So please how can I achieve same result using EF Core or Linq
I ended up approaching it like this:
if ((Model.WebReport != null) && Model.WebReport.Rows.Any())
{
var columns = Model.WebReport.Rows
.Select(c => (Model.GroupBy.Equals("Group") ? c.Stat : c.Group))
.Distinct()
.ToList();
columns.Insert(0, "Group");
var reportStat = Model.WebReport.Rows
.GroupBy(g => (Model.GroupBy.Equals("Group") ? g.Group : g.Stat))
.Select(x => new
{
Group = x.Key,
Stats = x.ToDictionary(y => (Model.GroupBy.Equals("Group") ? y.Stat : y.Group), y => y.Total)
});
Model.Columns = columns;
Model.ReportStats = reportStat.ToList();
}
I use jenssegers/laravel-mongodb. I make scope
public function scopeWhereFullText($query, $search)
{
return $query->whereRaw(['$text' => ['$search' => $search]],['score'=>['$meta'=>'textScore']]);
}
How I can order By score field like in MongoDB js example:
db.products.find({$text:{$search:"SomeText"}},{score:{$meta:'textScore'}}).sort({score:{$meta:'textScore'}})
What is the solution without crutch:
public function scopeWhereFullText($query, $search)
{
$query->getQuery()->projections = ['score'=>['$meta'=>'textScore']];
return $query->whereRaw(['$text' => ['$search' => $search]]);
}
and in result
$products = Product::whereFullText($request->get('q',''))
->orderBy('score',['$meta'=>'textScore'])->get();
$max = $products->max('score');
$min = $products->min('score');
$products = $products->filter(function($item) use($max,$min){
return $item->score > ($max+$min)/2;
});
Use
$results = DB::connection()->collection('_User')->whereRaw(['$text' => ['$search' => 'SEARCH QUERY']])->project(['score'=>['$meta'=>'textScore']])->orderBy('score', ['$meta' => "textScore"])->limit(10)->get();
Im trying to make a hashes of hashes to uniquely identify the number that only comes under one set of levels. the hash structure looks something like this :
my %gh = {
'Test1' => {
'level1a' => {
'level2b' => {
'level3a' => {
'level4a' => {
'level5' => '63'
}
}
}
}
}
};
Can some please tell me what is the simplest way to traverse the hash so i can get the value 63.
I have been using
my $x = '';
foreach my $l0 (%gh){
foreach my $l1 (%{$l0}){
foreach my $l2 (%$l1){
foreach my $l3 (%{$l2}){
foreach my $l4 (%$l3){
foreach my $l5 (%{$l4}){
$x = $l5;
}
}
}
}
}
}
This process seems to be working fine . But i was just looking for something simpler and shorter;
Thanks in advance
This will work in your case (only hashes, and plain scalar value at the end)
sub hval {
my ($h) = #_;
return map { ref() ? hval($_) : $_ } values %$h;
}
my $gh = {
'Test1' => {
'level1a' => {
'level2b' => {
'level3a' => {
'level4a' => {
'level5' => '63'
}
}
}
}
}
};
my ($x) = hval($gh);
If you use a reference to a hash instead, here is one way:
use warnings;
use strict;
my $gh = {
'Test1' => {
'level1a' => {
'level2b' => {
'level3a' => {
'level4a' => {
'level5' => '63'
}
}
}
}
}
};
print $gh->{Test1}{level1a}{level2b}{level3a}{level4a}{level5}, "\n";
See also: perldoc perldsc and Data::Diver
I am trying to return today's birthdays. This is what I have right now, which works, but I need to grab the month and day to input into the statement. I thought maybe I could grab them from localtime, but that didn't work out. Any suggestions would be appreciated.
sub author_birth {
my ($self) = #_;
my ($day,$month) = (localtime())[3..4];
my $author_result = $self->search_like(
{
birth => '%03-20'
},
{
select => [
'id',
'complete_name',
],
#result_class => 'DBIx::Class::ResultClass::HashRefInflator'
}
);
my #author_ids = ();
while (my $row = $author_result->next) {
push #author_ids, $row->id;
}
return $self->get_author_info_by_id(\#author_ids);
}
I ended up doing something like this.
my ($self) = #_;
my $conc = '%';
my $datetime = Time::Piece->new->strftime('%m-%d');
my $date = $conc . $datetime;
my $author_result = $self->search_like(
{
birth => $date,
},
{
select => [
'id',
'complete_name',
],
#result_class => 'DBIx::Class::ResultClass::HashRefInflator'
}
);