How can I use Perl's format function? - function

I'm learning Perl formatting by following the tutorial at Perl - Formats, but when I type their example into my IDE:
format EMPLOYEE =
===================================
#<<<<<<<<<<<<<<<<<<<<<< #<<
$name $age
######.##
$salary
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
#n = ("Ali", "Raza", "Jaffer");
#a = (20,30, 40);
#s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (#n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
I get the error:
Scalar found where operator expected at .\qb.pl line 7, near "$name $age"
(Missing operator before $age?)
syntax error at .\qb.pl line 7, near "$name $age"
Execution of .\qb.pl aborted due to compilation errors.
I'm using Perl 5, version 30, Subversion 2 (v5.30.2) built for MSWin32-x64-multi-thread.

When I run your code on 5.24, I see this warning message:
Use of comma-less variable list is deprecated at...
which points to the $name $age line as well.
When I enable diagnostics, I get this explanation:
(D deprecated) The values you give to a format should be
separated by commas, not just aligned on a line.
When I add the comma as follows:
$name,$age
the warning goes away, and I get this output:
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
This warning became an error in 5.28, according to perl5280delta.

Your first mistake was in thinking that formats were a useful tool that would solve your problem. Formats have been largely ignored for almost as long as I've been using Perl. You'll probably find that using Perl6::Form is a better approach.
Your second mistake was in thinking that Tutorials Point was a good place to get information about anything. The tutorials there are written by people who seem to know next to nothing about their subject and (as you have seen here) the examples are riddled with typos that makes them next to useless.
If you're determined to use Perl formats, then the perlform manual page would be the best place to start.

Perhaps the following code sample is easier to read. The output is also easier to comprehend at a quick glance:
use strict;
use warnings;
my($name, $age, $salary);
while(<DATA>) {
($name, $age, $salary) = split;
write;
}
format STDOUT_TOP =
Employee Age Salary
----------------------------------------
.
format STDOUT =
#<<<<<<<<<<<<<<<<<<<<<< #<< ######.##
$name, $age, $salary
.
__DATA__
Ali 20 2000.00
Raza 30 2500.00
Jaffer 40 4000.00
Output
Employee Age Salary
----------------------------------------
Ali 20 2000.00
Raza 30 2500.00
Jaffer 40 4000.00
There are many ways to provide input data. One of them is a hash to keep related data.
use strict;
use warnings;
my %employees = (
Ali => { age => 20, salary => 2000.00},
Raza => { age => 30, salary => 2500.00},
Jaffer => { age => 40, salary => 4000.00}
);
my($name, $age, $salary);
for $name (sort keys %employees) {
($age, $salary) = #{$employees{$name}}{qw/age salary/};
write;
}
format STDOUT_TOP =
Employee Age Salary
----------------------------------------
.
format STDOUT =
#<<<<<<<<<<<<<<<<<<<<<< #<< ######.##
$name, $age, $salary
.
Output
Employee Age Salary
----------------------------------------
Ali 20 2000.00
Jaffer 40 4000.00
Raza 30 2500.00

Related

Convert JSON with a ton of values under each (property? object?) to CSV with many rows is returning all values in one string

I'm trying to use PowerShell to convert a json with the following format:
{"Value1":[89,91,88,71,59],"Value2":[53,58,54,53,58]}
To a CSV with the following format:
Value1,Value2
89,53
91,58
88,54
71,53
59,58
The issue I'm running into is that this code that I've cobbled together
Get-Content 'C:\test\test.json' | ConvertFrom-Json |
select #{n='value1';e={-split $_.value1}},
#{n='value2';e={-split $_.value2}} |
Export-Csv -NoTypeInformation 'C:\test\test.csv'
is making a CSV with the following format:
Value1,Value2
89 91 88 71 59,53 58 54 53 58
Does anybody have any ideas on what I could do here? I'm really new to PowerShell and I'm getting pretty lost. I've read a ton of similar items on here and other sites, but none that exactly fit the issue I'm running into.
Thanks
There might be more sophisticated solutions but at least for this simple example the following snippet works I think:
$Var = '{"Value1":[89,91,88,71,59],"Value2":[53,58,54,53,58]}' | ConvertFrom-Json
$Var.Value1.Count
for ($i = 0; $i -lt $Var.Value1.Count; $i++) {
[PSCustomObject]#{
Value1 = $Var.Value1[$i]
Value2 = $Var.Value2[$i]
}
}
The output looks like this:
Value1 Value2
------ ------
89 53
91 58
88 54
71 53
59 58

Laravel orWhereIn and orWhereIn and so on

To be honest I rly do not know how to describe my query problem, hope example will clear things up:
I've got simple query:
return $query->whereHas('categories', function ($q) use ($ids) {
$q->whereIn('category_id', $ids);
}, '=', count($ids));
which returns records that match array of categories ids. To present this better right now we've got such condition
getRecordsThatMatchThisCondition(id1 && id2 && id3... and so on).
What I want is to achieve such comparasion
getRecordsThatMatchThisCondition((id1.1 || id1.2 || id1.3) && (id2.1 || id2.2) ... and so on.)
I've couldn't find any help with this problem so far. Even naming such query would be helpfull. My table is simple PIVOT
id record_id category_id
------------------------------------
1 1 35
2 2 41
3 2 74
4 3 74
5 3 40
6 4 40
Summarizing my problem with words:
I do not have record relation to parent_category of selected category... Right now I need to display all records that match multiple categories.
Visualising problem:
Record is assigned to categories like this:
35
└40
└41 ☑
36
└74 ☑
By providing id 35 and 36, record should be found! By providing 40, 74 should NOT be found...
Hope I've described my problem well enough.
You can't query with whereIn method like this, but can use a foreach loop, like this :
return $query->whereHas('categories', function ($q) use ($ids) {
foreach($ids as $key => $value) {
$q->orWhere('category_id', $value)
}
}, '=', count($ids));
Or, with for loop :
return $query->whereHas('categories', function ($q) use ($ids) {
for ($i = 0; $i < count($ids); $i++){
$q->orWhere('category_id', $ids[$i]);
}
}, '=', count($ids));

Regression by year and companyID to save coefficients

I am trying to run regressions by companyID and year, and save the coefficients for each firm-year model as new variables in a new column right besides the other columns. There is an additional wrinkle‹ I have panel data for 1990-2010 and want to run each regression using t to t-4 only (I.e., for 2001, use only 1998-2001 years of data and i.e. for 1990 then only the data of 1990 and so on). I am new to using foreach loops and I found some prior coding on the web. I have tried to adapt it to my situation but two issues: anything.....
the output is staying blank
I have not figured out how to use the rolling four year data periods.
Here is the code I tried. Any suggestions would be much appreciated.
use paneldata.dta // the dataset I am working in
generate coeff . //empty variable for coefficient
foreach x of local levels {
forval z = 1990/2010
{
capture reg excess_returns excess_market
replace coeff = _b[fyear] & _b[CompanyID] if e(sample) }
}
So below is a short snapshot of what the data looks like;
CompanyID Re_Rf Rm-Rf Year
10 2 2 1990 
10 3 2 1991 
15 3 2 1991 
15 4 2 1992
15 5 2 1993 
21 4 2 1990 
21 4 2 1991 
34 3 1 1990 
34 3 1 1991
34 4 1 1992
34 2 1 1993  
34 3 1 1994
34 4 1 1995
34 2 1 1996   
 
Re_Rf = excess_returns 
Rm_Rf = excess_market 
I want to run the following regression: ​​​​​​​
reg excess_returns excess_market
There is a good discussion on Statalist, but I think this answer may be helpful for your learning about loops and how Stata syntax work.
the code I would use is as follows:
generate coeff = . //empty variable for coefficient
// put the values of gvkey into a local macro called levels
qui levelsof CompanyID, local(levels)
foreach co of local levels {
forval yr = 1994/2010 {
// run the regression with the condition that year is between yr
// and yr-3 (which is what you write in your example)
// and the CompanyID is the same as in the regression
qui reg Re_Rf Rm_Rf if fyear <= `yr' & fyear >= `yr'-3 & CompanyID== `co'
// now replace coeff equal to the coefficient on Rm_Rf with the same
// condiditions as above, but only for year yr
replace coeff = _b[Rm_Rf] if fyear == `yr' & CompanyID == `co'
}
}
This is a potentially dangerous thing to do if you do not have a balanced panel. If you are worried about this, there may be a way to deal with it using capture or changing the fyear loop to include something like:
levelsof fyear if CompanyID == `co', local(yr_level)
foreach yr of `yr_level' { ...

Grails 2.3.2: findOrCreate using Enums in Bootstrap

I am having troubles with using the findOrCreateBy method in the Bootstrap.groovy.
class Guest {
String firstname
String lastname
Gender gender
static constraints = {
firstname blank: false
lastname blank: false
gender nullable: false
}
}
enum Gender {
MALE('male'), FEMALE('female')
final String v
Gender(String s) { v = s }
}
And in the Bootstrap I try to create Guests if they do not exist yet.
Guest guest = Guest.findOrCreateByFirstnameAndLastnameAndGender(firstname, lastname, Gender.MALE)
guest.save()
The first time I run the app against MySQL everything works fine. The apps starts without any error. If I run the app a second time (this time with guest in the database) I get the following failure.
| Error 2013-11-17 14:27:37,621 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Message: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Line | Method
->> 105 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 106 | createGuest in BootStrap
| 102 | createGuest . . . . . . . . . . in ''
| 66 | doCall in BootStrap$_closure1
| 308 | evaluateEnvironmentSpecificBlock in grails.util.Environment
| 301 | executeForEnvironment in ''
| 277 | executeForCurrentEnvironment . . in ''
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . . . . . . . . in java.lang.Thread
It seems the the first time Gorm writes values '0' and '1' to the database. In the second run it fails to convert these 0 and 1 into the corresponding enum value. Can anybody tell me what I am doing wrong?
Try this - Add the parameter generateSimpleParameterMetadata=true to your url connect string,
...
url = "jdbc:mysql://localhost/bootstraptest?generateSimpleParameterMetadata=true"
...
This has something to do with the way the driver interprets the enum meta data (frankly i don't understand it well) see http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
This solution is very db specific, so you don't need any other changes
Note that the actual enum label will now be stored in the database ('NEW', 'WIP', 'DONE' instead of 0, 1, 2)
I think this is related to mysql, I dont have mysql to test it against and never worked with mysql, but try to specifically map the enum, like this:
static mapping = {
...
gender column: 'gender', sqlType: 'enum', name: 'gender'
}
ref
And if you are manually creating your database table , try to create the enum for your columns similar to this:
CREATE TABLE sizes (
name ENUM('small', 'medium', 'large')
);
ref
This is another article that can help here
I suggest to change mapping using IdentityEnumType:
static mapping = {
...
gender column: 'gender', type: IdentityEnumType
}
Modify your Enum, by adding id to it:
public enum Gender {
MALE (1, "male"),
FEMALE (2, "female"),
final Integer id
final String value
Gender (Integer id, String value) {
this.id = id
this.value = value
}
String getValue() {
return value
}
String toString() {
return name()
}
String getKey() {
return name()
}
That should help you.

Displaying MySQL tables as ASCII in blog posts

I would like to quickly display MySQL recordsets in blog posts, using a similar ASCII layout to that used by mysql.com in their help pages. I'm using wordpress v2.7. Any ideas? I should also add that I'm using wp-syntax for syntax highlighting, so it's really just generating the ASCII that I'm interesting in.
If you mean things like
+----+------+
| id | name |
+----+------+
| 1 | Bob |
| 2 | Mary |
| 3 | Jane |
| 4 | Lisa |
+----+------+
then just running the query from the MySQL commandline should suffice, as the results are formatted when running queries in interactive mode on the commandline. You can then copy and paste them into your blog post, surrounding them with <pre> or similar if necessary.
The ASCII you speak of is the way the MySQL command-line client lays out its results.
mysql> select task_nextrun,task_name from pref_task;
+--------------+-----------------+
| task_nextrun | task_name |
+--------------+-----------------+
| 1235999760 | datacache_clean |
| 1236002760 | process_stats |
+--------------+-----------------+
2 rows in set (0.00 sec)
mysql>
You would just need to send your commands to the MySQL command line client.
If you want to do it without calling the command-line client, here's a way in PHP. Note that this is pretty crude code and that I haven't tested it, I'm mostly just trying to explain the process. It will also left-align everything, I believe the mysql client right-aligns numbers, emulating that would require a bit more work, but nothing difficult.
Assuming that you've fetched the records into an associative-only array named $resultset, using something like mysqli_result's fetch_all() function:
// determine maximum value lengths for each column
foreach ($resultset as $result)
{
foreach ($result as $col => $val)
{
if (strlen($val) > $max_length[$col])
{
$max_length[$col] = strlen($val);
}
}
}
// construct border lines
foreach ($max_length as $col_length)
{
$border_line .= '+'.str_repeat('-', $col_length+2);
}
$border_line .= "+";
// print header
print $border_line."<br />\n";
foreach ($max_length as $col_name => $col_length)
{
print '| '.str_pad($col_name, $col_length, ' ').' |';
}
print "<br />\n";
print $border_line."<br />\n";
// print data
foreach ($resultset as $result)
{
foreach ($result as $col => $val)
{
print '| '.str_pad($val, $max_length[$col], ' ').' |';
}
print "<br />\n";
}
print $border_line."<br />\n";