April 26, 2013
mojo tt2 defaults layout patch
Fayland And Programming
You wrote code with open source like CPAN. You meet problems with them. You investigate, write tests then provide patches. Your patches are accepeted.
I really enjoy the way it moves.
Here is another patch for Mojolicious::Plugin::TtRenderer.
the issue is that $self->defaults(layout => 'wrapper'); is always dropping the [% content %] without reason. and with debug I see the content is really in $c->stash->{'mojo.content'}. so a simple patch is that just $c->stash->{content} ||= $c->stash->{'mojo.content'}->{content};
recently I’m writing another new app with bitcoin <-> litecoin and other virtual coins exchange. and I have a wrapper.html.tt for the whole site. but I do not want to use it in the email TT2 render.
if I put WRAPPER => 'layouts/wrapper.html.tt', in the TT2 options, it will also apply to the mail render. a better approach is to use defaults layout. then in email render, set the layout as empty or actually we need use partial => 1.
MainApp.pm
$self->plugin('tt_renderer');
$self->defaults(layout => 'wrapper');
$self->renderer->default_handler( 'tt' );
OtherController.pm
my $body = $c->render(
template => 'emails/forgot_pass', format => 'mail',
other_stash => $var,
partial => 1
);
partial => 1 will set layout as null. so it will give us what we want.
Have fun!
April 11, 2013
Mojolicious TT2 patch
Fayland And Programming
I am kindy busy with adding new features to my job site
but it’s very boring to restart the app on template updates. TT2 should be able to pick up the changes automatically. it works under Dancer or Catalyst, but not Mojolicious.
I thought I should spend some time on investigating why before writing more stuff. and after a while, I have a patch for Mojolicious::Plugin::TtRenderer.
it dues to the Provider in TtRender always return 1 instead of mtime on _template_modified.
plicease accepts it quite fast with slight changes but I’m waiting for a CPAN release. :-)
here is few changes on http://findmjob.com/ recently.
-
Location link is added like: San Francisco, CA
Happy hacking!
April 09, 2013
Dancer to Mojolicious
Fayland And Programming
The progress went smoothly because all of them are just Perl code.
old Dancer code: FindmJob::WWW
new Mojolicious code: FindmJob::WWW, FindmJob::WWW::Root and others
Few notes
hooks
from before_template_render to before_render
Dancer forward VS Mojolicious before_dispatch
we can modify the req->url->path in before_dispatch with assigning stash.
# feed.(rss|atom) and /p.2/
$self->hook( before_dispatch => sub {
my $self = shift;
my $p = $self->req->url->path;
if ($p =~ s{/feed\.(rss|atom)$}{}) {
$self->stash('is_feed' => $1);
}
if ($p =~ s{/p\.(\d+)(/|$)}{$2}) {
$self->stash('page' => $1);
}
$self->req->url->path($p);
});
supervise
Dancer:
plackup -E production -s Starman --workers=3 -l /tmp/findmjob.sock -a /findmjob.com/www/bin/app.pl
Mojolicious:
hypnotoad -f /findmjob.com/bin/www.pl
Note -f is important here, or supervise will keep restarting the script.
above plackup using sock and hypnotoad use port. so we need update the ngnix config a bit.
and it looks like hypnotoad is working better than plackup Starman
Template name conversation
there is no rule in Dancer for the Template name. but in Mojolicious, we have to do it with $name.$format.$handler
in this case we have to rename index.tt2 to index.html.tt
Conclusion
well, I’m not saying that Dancer is worse than Mojolicous or any other words. both of them are great.
but Dancer is a bit messy with Dancer and Dancer2. actually I love Moo a lot, but I don’t want to spend time on upgrading Dancer to Dancer2 (there seems some more difference than expected.)
in the other hand, Mojolicious looks amazing, sri improves it every week and I admire/trust his professional knowledge.
Have fun.
March 29, 2013
Two new CPAN modules
Fayland And Programming
I got two new CPAN modules uploaded today.
WWW::SpinnerChief
I wrote this based on the Python code
it’s pretty good that you know how to read the Python.
Business::PayPoint
aka tips to write SOAP module in Perl.
the PHP SOAP lib is pretty good while the Perl one is a little suck.
so usually if I can’t write it at the first try in Perl, I would use PHP to find the sending request/response
$client = new SoapClient('https://www.example.com/Test?wsdl', array(
'trace' => 1,
) );
$client->__call('TestAction', $params);
echo "RESPONSE:\n" . $client->__getLastResponse() . "\n";
echo "REQUEST HEADER:\n" . $client->__getLastRequestHeaders() . "\n";
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
After I got the correct sample request, I’ll try to use Perl library to send the same XML with trace on.
use SOAP::Lite +trace => 'all';
well, you even can’t write correct one sometimes (maybe I am a little stupid).
but I have a final trick for it. use XML::Write to genereate the request XML. then use
my $som = $soap->call($method, SOAP::Data->type('xml' => $xml));
you won’t be wrong in this case. :)
Have fun.
March 17, 2013
Net::Telnet with bitflu
Fayland And Programming
Even Net::Telnet is quite old, it’s still very powerful and simple to use.
use strict;
use warnings;
use Net::Telnet ();
use Data::Dumper;
my $host = '0';
my $port = 4001;
my $telnet = Net::Telnet->new();
unless ($telnet->open( Host => $host, Port => $port, Timeout => 30 )) {
die "Can't connect to $host:$port\n";
}
$telnet->waitfor('/bitflu> /');
my @messages = map { chomp; $_ } $telnet->cmd(String => 'ls');
pop @messages if $messages[-1] eq 'bitflu';
print Dumper(\@messages);
$telnet->close();
there are some tips:
remove ANSI color
foreach my $msg (@messages) {
# if you do not remove this, your regex with /^\[/ may break
$msg =~ s/\e\[[\d;]*[a-zA-Z]//g;
}
Change Window Size
if you use term to do bitflu> ls, you’ll see full torrent name. but with the code above, you can only see few chars. here is the note to change the Window Size:
my $telnet = Net::Telnet->new();
$telnet->option_callback( sub { return; } );
$telnet->option_accept(Do => 31);
unless ($telnet->open( Host => $host, Port => $port, Timeout => 60 )) {
die "Can't connect to $host:$port\n";
}
$telnet->waitfor('/bitflu> /');
## copied from http://blog.webdir.bg/perl-apache-realtime-output-from-script/
## Many Thanks!
$telnet->telnetmode(0);
$telnet->put(pack("C9",
255, # TELNET_IAC
250, # TELNET_SB
31, 0, 200, 0, 0, # TELOPT_NAWS
255, # TELNET_IAC
240)); # TELNET_SE
$telnet->telnetmode(1);
March 10, 2013
Learn Python Note 1
Fayland And Programming
I’m starting learning Python a bit.
argparse
if you have args setup in different modules, like you want setup --log on logging, setup --tor --skip-tor on requesting, the combination of add_help=False and parse_known_args is pretty cool.
import argparse
parent_argparse = argparse.ArgumentParser(add_help=False)
parent_argparse.add_argument('--log', action='store', default='ERROR', dest='log', help='logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL')
_args, _args_unknown = parent_argparse.parse_known_args()
afterwards, in real place, do
parser = argparse.ArgumentParser(description='Some real CLI', parents=[parent_argparse])
init.py and as
actually it’s a very cool feature. you can put some common code for all sub-modules in __init__.py like config code (to avoid write another file)
import ConfigParser
try:
cfg = ConfigParser.ConfigParser()
cfg.read(['/somwhere/conf/project.ini', '/somwhere/conf/project_local.ini'])
except ConfigParser.Error, e:
logger.critical('Cannot read configuration file, reason [%s]' % e)
and as is pretty amazing.
from modulename import cfg as project_config
BeautifulSoup is another HTML::TreeBuilder
BeautifulSoup works like Perl HTML::TreeBuilder.
from bs4 import BeautifulSoup
soup = BeautifulSoup(text)
for tag in soup.find_all('span', attrs={'id': re.compile('^ctl00_contentPageContent_lbl(.*?)Value$')}):
id = tag['id']
id = id.replace('ctl00_contentPageContent_lbl', '').replace('Value', '')
data[id] = tag.get_text()
something I do like in Python
def with args and default values. (Perl sub was developed too many years ago.)
you don’t need type so many {} or ().
something I do not like in Python
string interpolation is quite inconvenience. there are %, format and Template. but I really miss the $ with Perl.
I miss Perl regexp a lot. the re.compile, re.sub, re.I is too much typing.
Disclaim
I’m still a newbie. so parden me if anything is wrong. I’ll write more when I learn more. and I admit it’s pretty fun to learn Python.
March 06, 2013
add alert note for old posts in Jekyll
Fayland And Programming
add alert note for old posts
For Jekyll Bootstrap, it’s quite simple as we can do something like below:
edit _includes/themes/twitter/post.html, add
{% assign page_year = page.date | date: "%Y" %}
{% if page_year < '2010' %}
<div class='alert alert-info'>This post may be outdated due to it was written on {{ page_year }}. The links may be broken. The code may be not working anymore. Leave comments if needed.</div>
{% endif %}
20 items in rss/atom
I have another if in the {% for post in site.posts %} for rss.xml and atom.xml
{% if forloop.index < 20 %}
...
{% endif %}
paginate
edit _config.yml
paginate: 10
paginate_path: 'page/:num'
Have fun.
Blogger local file > Jekyll migrator
I have an old Blogger before I move to MT5, it contains my posts from 2006 to 2009. some are quite old, broken, useless and even not worth reading. but some are still very useful and it’s a part of my memory and life. (Sorry that comments are dropped that I can’t import it into Disqus.)
so I wrote a simple Perl script to convert the local HTML files into Jekyll here. the source code can be found in github.
it’s quite simple and maybe just fit for my need. but feel free to change it if you have same demand.
Have fun.
March 05, 2013
MT > Jekyll perl migrator
Fayland And Programming
I bought a new domain fayland.me.
I picked Jekyll as the blog engine.
I wrote a simple Perl script to convert my old Movable Type 5 blogs to Jekyll Bootstrap.
the difference between this one and the Jekyll::MT is that it supports tags and it’s for Jekyll Bootstrap.
at last, using
rsync -arv --delete _site fay:/srv/www/fayland.me/
to rsync the site.
Have fun.
November 21, 2012
Net-Amazon-DynamoDB
Fayland And ProgrammingI have been playing with Net::Amazon::DynamoDB a lot recently. this article is not to comment on that service. it's just a few notes for Perl guys who're using it.
package My::Dummy::Cache::FastMmap;use Moo;use Cache::FastMmap;has 'cache' => (is => 'lazy');sub _build_cache { Cache::FastMmap->new(share_file => '/tmp/mycache_fastmmap', unlink_on_exit => 0) }# Cache::FastMmap do not have thaw/freeze subsub thaw {my $self = shift;$self->cache->get(@_);}sub freeze {my $self = shift;$self->cache->set(@_);}sub remove {my $self = shift;$self->cache->remove(@_);}1;
October 10, 2012
Care each other
purl in your heart
October 08, 2012
诗篇 118:14-16
purl in your heart
October 01, 2012
http://bible.us/Ps69.12.CCB
purl in your heart
September 27, 2012
http://bible.us/Ps60.4-5.CCB
purl in your heart
Romans 3:23-24
?? 52:8-9 CCB
诗篇 55:6-8, 16, 22 CCB
September 19, 2012
BJ Rental price as a chart
purl in your heart
September 13, 2012
reCaptcha and lightbox and ajaxPost
Fayland And Programmingsometimes, you want to do lightbox for Email Us or Contact Us page.
<script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
see we have a tricky that keep check if Recaptcha is inited (which will be done when recatpcha_ajax.js is loaded).<script type="text/javascript">$(document).ready(function(){var reCaptcha_timer;reCaptcha_timer = setInterval(function(){if (typeof(Recaptcha) != 'undefined') {clearInterval(reCaptcha_timer);CreateReCaptcha();}}, 50);});function CreateReCaptcha() {Recaptcha.create("public_key_blabla", 'captcha-placeholder', {theme: "white",callback: Recaptcha.focus_response_field});}</script>
before load the js, we reset it so it works like it's the first time we are trying to create reCaptcha.<script type="text/javascript">// so that we can reload itif (typeof(Recaptcha) != 'undefined') Recaptcha = undefined;</script><script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
September 11, 2012
MacOSx homebrew postgresql issue note
Fayland And Programmingafter brew install postgresql
selecting default shared_buffers ... 400kBcreating configuration files ... okcreating template1 database in /usr/local/var/postgres/base/1 ... FATAL: could not create shared memory segment: Cannot allocate memoryDETAIL: Failed system call was shmget(key=1, size=2138112, 03600).HINT: This error usually means that PostgreSQL's request for a shared memory segment exceeded available memory or swap space, or exceeded your kernel's SHMALL parameter. You can either reduce the request size or reconfigure the kernel with larger SHMALL. To reduce the request size (currently 2138112 bytes), reduce PostgreSQL's shared memory usage, perhaps by reducing shared_buffers or max_connections.The PostgreSQL documentation contains more information about shared memory configuration.child process exited with exit code 1initdb: removing data directory "/usr/local/var/postgres"
August 18, 2012
Proverbs 21:23-24
purl in your heart
http://bible.us/Prov21.23.CCB 管住口舌,免遭祸患。嘲讽者狂妄自大,行事骄横无比。
August 17, 2012
John 18:36
purl in your heart
http://bible.us/John18.36.CCB 耶稣答道:“我的国不属于这个世界,如果我的国属于这个世界,我的臣仆早就起来争战了,我也不会被交在犹太人的手里。但我的国不属于这个世界。”
July 03, 2012
真理必叫你们得到自由
purl in your heart
by Jon Walker
“Then you will know the truth, and the truth will set you free.” (John 8:32 NIV)
你们必认识真理,真理必叫你们得到自由。 约翰福音 8:32 CCB
Read this as a prayer today:
请你今天用祷告的方式来读:
Jesus, you are the Truth, and the Truth sets me free. You are the Truth, and your Truth lives in me.
耶稣,你是真理,而真理必要叫我得到自由。你是真理,而且你的真理就住在我的里面。
I clothe myself in your Truth, Jesus, putting on the coat of a new self, “created to be like God in true righteousness and holiness” (Ephesians 4:24 NIV). You are “the way and the truth and the life,” and I am connected to God through you and you alone (John 14:6 NIV). Because of you, I know the Truth about who I am and I know that your life is working in me (Galatians 2:20).
耶稣,我让自己披戴你的真理,“穿上照着上帝形象所造的新人。这新人有从真理而来的公义和圣洁。”(以弗所书 4:24)。你“就是道路、真理、生命”,而且我是靠你,也只能靠你,才能和上帝相连(约翰福音 14:6)。因为你,我知道关于自己是谁的真相。我知道现在是你活在我的里面(加拉太书 2:20)。
Truth enables me to discern and reject the lies of the enemy. Your Truth demolishes arguments and pretensions that are at war with the knowledge of God. In your Truth, I will “take captive every thought” and make it obedient to you (2 Corinthians 10:5 NIV). With your Truth, I will teach these thoughts to obey you, King Jesus (suggested by 2 Corinthians 10:5 MSG).
真理使我能明辨是非,拒绝仇敌的谎言。你的真理使那些阻碍人认识上帝的谬论和高傲言论都被击破。在你的真理中,我能“夺回被掳去的心思意念,使其顺服基督”(哥林多后书 10:5 CCB)。在你的真理中,我要教导那些心思意念都去顺服你,认识你是主耶稣。
Your Truth says I’m forgiven, I’m loved by my Creator, and I’m God’s child, beloved and empowered by the Spirit of Truth.
你的真理告诉我,自己是被赦免的,我是得造物主喜悦的,是神的爱子,也充满了圣灵的大能。
The Truth enables me to respond to your direction. I can trust your leadership, I can trust your commands, and I can trust your plans because you are the Truth.
这真理让我回应你的指引。我也能相信你的带领,我能信靠你的话语,我能坚信你的计划,因为你就是真理。
I will leave it up to you to interpret the facts and determine the truth of any situation. I will let your Truth make the decisions, and then I will obey and leave the consequences in your loving, truth-filled hands.
我会让你来告诉我事实真相是如何的,带我在每个状况中明辨是非。我会让你的真理替我做决定,然后我还要遵行这个决定,从而把自己放在你的慈爱和信实中。
All the decisions are yours to make. Because you are Truth, I can respond in the Truth in all situations; I am no longer a slave to my emotions.
所有的决定都是出于你。因为你是真理,我也决心在每个状况中以真理回应你,我不再是情绪的奴隶。
Jon Walker is managing editor of Rick Warren’s Daily Hope Devotionals. He is also the author of Costly Grace: A Contemporary View of Bonhoeffer’s ‘The Cost of Discipleship’ and In Visible Fellowship: A Contemporary View of Bonhoeffer's Classic Work ‘Life Together’.
This devotional © Copyright 2012 Jon Walker. All rights reserved. Used by permission.
真理必叫你们得到自由
by Jon Walker
“Then you will know the truth, and the truth will set you free.” (John 8:32 NIV)
你们必认识真理,真理必叫你们得到自由。 约翰福音 8:32 CCB
Read this as a prayer today:
请你今天用祷告的方式来读:
Jesus, you are the Truth, and the Truth sets me free. You are the Truth, and your Truth lives in me.
耶稣,你是真理,而真理必要叫我得到自由。你是真理,而且你的真理就住在我的里面。
I clothe myself in your Truth, Jesus, putting on the coat of a new self, “created to be like God in true righteousness and holiness” (Ephesians 4:24 NIV). You are “the way and the truth and the life,” and I am connected to God through you and you alone (John 14:6 NIV). Because of you, I know the Truth about who I am and I know that your life is working in me (Galatians 2:20).
耶稣,我让自己披戴你的真理,“穿上照着上帝形象所造的新人。这新人有从真理而来的公义和圣洁。”(以弗所书 4:24)。你“就是道路、真理、生命”,而且我是靠你,也只能靠你,才能和上帝相连(约翰福音 14:6)。因为你,我知道关于自己是谁的真相。我知道现在是你活在我的里面(加拉太书 2:20)。
Truth enables me to discern and reject the lies of the enemy. Your Truth demolishes arguments and pretensions that are at war with the knowledge of God. In your Truth, I will “take captive every thought” and make it obedient to you (2 Corinthians 10:5 NIV). With your Truth, I will teach these thoughts to obey you, King Jesus (suggested by 2 Corinthians 10:5 MSG).
真理使我能明辨是非,拒绝仇敌的谎言。你的真理使那些阻碍人认识上帝的谬论和高傲言论都被击破。在你的真理中,我能“夺回被掳去的心思意念,使其顺服基督”(哥林多后书 10:5 CCB)。在你的真理中,我要教导那些心思意念都去顺服你,认识你是主耶稣。
Your Truth says I’m forgiven, I’m loved by my Creator, and I’m God’s child, beloved and empowered by the Spirit of Truth.
你的真理告诉我,自己是被赦免的,我是得造物主喜悦的,是神的爱子,也充满了圣灵的大能。
The Truth enables me to respond to your direction. I can trust your leadership, I can trust your commands, and I can trust your plans because you are the Truth.
这真理让我回应你的指引。我也能相信你的带领,我能信靠你的话语,我能坚信你的计划,因为你就是真理。
I will leave it up to you to interpret the facts and determine the truth of any situation. I will let your Truth make the decisions, and then I will obey and leave the consequences in your loving, truth-filled hands.
我会让你来告诉我事实真相是如何的,带我在每个状况中明辨是非。我会让你的真理替我做决定,然后我还要遵行这个决定,从而把自己放在你的慈爱和信实中。
All the decisions are yours to make. Because you are Truth, I can respond in the Truth in all situations; I am no longer a slave to my emotions.
所有的决定都是出于你。因为你是真理,我也决心在每个状况中以真理回应你,我不再是情绪的奴隶。
Jon Walker is managing editor of Rick Warren’s Daily Hope Devotionals. He is also the author of Costly Grace: A Contemporary View of Bonhoeffer’s ‘The Cost of Discipleship’ and In Visible Fellowship: A Contemporary View of Bonhoeffer's Classic Work ‘Life Together’.
This devotional © Copyright 2012 Jon Walker. All rights reserved. Used by permission.
April 29, 2012
Untitled
purl in your heart
April 25, 2012
MongoDB and Perl
Fayland And Programmingit's really a pain to work with MongoDB in Perl. Perl has no 'type' so when you get INT value from DBI, it might be really "1" instead of int 1.
PRIMARY> db.jobs.find().forEach(function(job) {job.time = parseInt(job.time);db.jobs.save(job);});
April 13, 2012
api and android app
Fayland And ProgrammingI'm a fan of Android. even I like my iPad and MBP very much too.
April 07, 2012
sphinx search with varchar primary key
Fayland And Programmingusually when you index the mysql data into sphinx, you'll use id int/bigint for the primary key. but it's broken for me on http://findmjob.com/, we use uuid everywhere for the primary key.
sql_query_pre = SET NAMES utf8sql_query_pre = SET @id := 1;sql_query = \SELECT @id := @id + 1 AS tid, id, title, description, location, contact, inserted_at FROM job ORDER BY inserted_at DESC LIMIT 10000sql_field_string = id
my @jobids = map { $_->{id} } @{$ret->{matches}};
April 05, 2012
Wildlife park, Beijing
purl in your heart
cidr2regexp.pl
$ cidr2regexp.pl 210.212.0.0/11
210\.((19[2-9])|(20[0-9])|(21[0-9])|(22[0-3]))
$ cidr2regexp.pl 210.212.0.0/12
210\.((20[8-9])|(21[0-9])|(22[0-3]))
$ cidr2regexp.pl 210.212.0.0/13
210\.((20[8-9])|(21[0-5]))
#!/usr/bin/perl -l
BEGIN{ ($ip,$bits)=split q(\/), shift }
$bin_str=substr( (join qq(), map { sprintf q(%08b), $_ } split (q(\.), $ip)), 0, $bits);
push @eight_bins, $1 while $bin_str=~m{(.{1,8})}g;
@ddd = map {
if (length($_) == 8) { eval qq(0b$_) }
else {
qq(@{[eval qq(0b@{[substr($_.q(0)x8,0,8)]})]} .. @{[eval qq(0b@{[substr($_.q(1)x8,0,8)]})]})
}
} @eight_bins;
END {
do { @digits=split q(), $_; $seen{join q(), @digits[0..$#digits-1]}.=$digits[-1] }
for eval qq( @{[grep { m{\.\.} } @ddd]} );
print join qq(\\\.), (grep { !m{\.\.} } @ddd ),
eval {
q{(}.
(
join qq(\|),
map {qq(($_\[@{[substr($seen{$_},0,1)]}-@{[substr($seen{$_},-1,1)]}]))}
sort {$a<=>$b} keys %seen
)
.q{)}
if $ddd[-1]=~m{\.\.}
}
}
April 03, 2012
DBIx::Class with Moose has
Fayland And Programmingwell, I don't know how to name it.
package FindmJob::Schema::Result::Job;....use FindmJob::Utils 'seo_title';has 'url' => ( is => 'ro', isa => 'Str', lazy_build => 1 );sub _build_url {my ($self) = @_;return "/job/" . $self->id . "/" . seo_title($self->title) . ".html";}
April 01, 2012
findmjob.com
Fayland And Programmingmaybe to earn some money (not for fun this time), I decided to write a new website http://findmjob.com/
better pagination url design in Dancer
usually People do param for pager like ?page=1 or ?p=1, it maybe not that good for search engine because they may not go scrape inside. so we may come out a solution with /page=1/ or /p=1/ or even /p.1/ etc.
get qr'.*?/p\.(\d+).*?' => sub {my $uri = request->uri;$uri =~ s'/p\.(\d+)'';var page => $1;$uri =~ s/\/$//;forward $uri;};get '/' => sub {my $p = vars->{page} || 1; $p = 1 unless $p =~ /^\d+$/;
March 29, 2012
Net-GitHub-0.43_01
Fayland And ProgrammingGithub is moving on with their API that "We will terminate API v1 and API v2 in 1 month on May 1st, 2012.".
use Net::GitHub;my $gh = Net::GitHub->new( login => 'fayland', pass => 'secret' );my $oauth = $gh->oauth;my $o = $oauth->create_authorization( {scopes => ['user', 'public_repo', 'repo', 'gist'], # just ['public_repo']note => 'test purpose',} );print $o->{token};
Thanks.my $github = Net::GitHub->new(access_token => $token, # from above);
March 16, 2012
Heartfelt man
purl in your heart
February 26, 2012
在 神我们的父面前,那清洁没有玷污的虔诚,就是看顾在患难中的孤儿寡妇,并且保守自己不沾染世俗。 http://bible.us/jas1.27.cunpss
purl in your heart
January 19, 2012
Split inside specific column and expend to key-value extractor
purl in your heart
{
perl -F\\t -lane 'BEGIN{ $i=shift; @h=split q(,), shift; print STDERR join qq(\t), @h } %k=map { @{[split(q(:), $_)]}[0,1] } split q(, ), $F[$i]; print join qq(\t), map { $k{$_} } @h' $*
} $ echo 2010Q1:H, 2007:Y, 2009:Y| col2kv 0 2006,2007,2008,2009,2010Q1,2010Q2 2>&1| row2col
2006
2007 Y
2008
2009 Y
2010Q1 H
2010Q2
January 06, 2012
How to make group_by_in_perl?
purl in your heart
group_by_in_perl ()
{
perl -F\\t -lane 'BEGIN{$group_by=shift; $sum_by=shift} END { print for map{ join qq(\t), $_, $sum{$_}} keys %sum } $sum{join qq(\t), @F[eval($group_by)]} += $F[eval($sum_by)]' $*
}
BJ in snowing
December 27, 2011
xml-table-maker for Windows
purl in your heart
perl -e "use Win32::Clipboard; use DBIx::XHTML_Table; Win32::Clipboard::Set(DBIx::XHTML_Table->new(q(dbi:Oracle),qq(@ARGV))->exec_query(eval <STDIN>)->modify(table=>{border=>1, bordercolor=> q(#888888), cellspacing=>0})->output())"
December 03, 2011
Plack::Middleware::FileWrap
Fayland And Programming
December 02, 2011
git submodule
Fayland And ProgrammingWhen you include another open source in your own project, it's usually pretty hard to keep it up to date. it becomes even more harder if you have some modification on it.
kindergarden> git submodule add https://github.com/twitter/bootstrap.git static/bootstrapkindergarden> git add .gitmodules static/bootstrapkindergarden> git commit -a -m "remote bootstrap"kindergarden> git pushkindergarden> git submodule init
kindergarden$ git submodule initkindergarden$ git submodule update
November 30, 2011
2011 CN Perl Advent
Fayland And ProgrammingHi, it's time for advent again!
November 29, 2011
我们为你们所存的盼望是确定的
purl in your heart
PDC: 圣经说,爱是个习惯
| ||
The Bible Says Love Is a Habit 圣经说,爱是个习惯 | ||
“If you love those who love you, what credit is that to you? Even sinners love those who love them.” (Luke 6:32 NIV) 你们若单爱那爱你们的人,有什么可酬谢的呢?就是罪人也爱那爱他们的人。路加福音 6:32 If you only love on and off like a light switch, you do not love others like God wants you to love. Jesus said, “If you only love those who love you, what credit is that to you?” (Luke 6:32a NIV) 如果你的爱像电灯一样时开时关,那么你就没有按照神的心意去(活出�的)爱了。所以,耶稣这样说:“你们若单爱那爱你们的人,有什么可酬谢的呢?”(路加福音 6:32) His point is this: All of us can love those who love us back. Becoming a master lover means you learn to love the unlovable � when you love people who don’t love you, when you love people who irritate you, when you love people who stab you in the back or gossip about you. 他的意思是:我们每个人都能做的,就是爱那些知恩图报的人。而你若想要成为一个有博爱之心的人,就得学着去爱那些不可爱的人。也就是,去爱那些不爱你的人,包括那些常常触怒你的人,或是那些在你背后指指点点、说长道短的人。 This may seem like an impossible task, and it is � that’s why we need God’s love in us, so we can then love others: “We know and rely on the love God has for us” (1 John 4:16a NIV). 如果这听上去有点象天方夜谭,那你其实是清醒的。因为,无私的付出爱,并且一味的坚持,这真的需要神的爱先充满我们的心。所以,圣经这样说:“神爱我们的心,我们也知道也信”(约翰一书 4:16)。 When you realize how much God loves you � with an extravagant, irresistible, unconditional love � then his love will change your entire focus on life. If we don’t receive God’s love for us, we’ll have a hard time loving other people. I’m talking about loving people who are unlovely, difficult, irritable, and those who are different or demanding. 当你认识到神对自己的爱有多么丰盛、多么的坚忍、多么的无私,那么�的爱就能改变你对生命的关注点。如果我们不去接受神给我们的爱,那么关爱他人就是一件太难太难的事。注意,这里我们说的仍然是爱那些不可爱的、满是困难的、易于激怒人的、与常人迥异的、常常不满足的人。 You can’t do that until you have God’s love coming through you. You need to know God’s love so it can overflow out of your life into others. 没有神的爱在你心里运行,这些就真的太难了。你必须去认识神的爱,这样你的心里才能充满�的爱,直到这爱开始满溢,涌流出来,进入他人的生命中。 |
November 26, 2011
KinderGarden
Fayland And Programmingas talked yesterday, I get it uploaded into github. well, under PerlChina. https://github.com/PerlChina/kindergarden
November 25, 2011
Dancer::Template::Xslate
Fayland And ProgrammingI'm writing some toy once again with Plack and Dancer (and Mojo later).
Note there is always more than one way to do it.# config.ymltemplate: xslateengines:xslate:syntax: 'TTerse'extension: 'tt'header:- 'layout/header.tt'footer:- 'layout/footer.tt'module:- KinderGardenX::Text::Xslate::Bridge::KinderGarden# KinderGardenX::Text::Xslate::Bridge::KinderGardenpackage KinderGardenX::Text::Xslate::Bridge::KinderGarden;use strict;use warnings;use parent qw(Text::Xslate::Bridge);use Gravatar::URL;my %funtion_methods = (gravatar_url => \&gravatar_url,);__PACKAGE__->bridge(function => \%funtion_methods,);1;# template<img src="[% gravatar_url( email => user.email, size => 30) %]" /><img src="[% gravatar_url( email => user.email, size => 50) %]" /><img src="[% gravatar_url( email => user.email) %]" />
November 07, 2011
new baby
Fayland And ProgrammingI'm very happy to share the good news with all the world. my second kid, another boy, was born today. 9:45am Beijing Time, Nov 8th, 2011. 2800g. and everything is good. Thanks.
November 06, 2011
Psalm 16:7
purl in your heart
October 25, 2011
po4a for the translation of Perldoc
purl in your heart
To make a translation of perldoc, use the tool named po4a
[jjiang@fedora14 ~]$ pmvers Locale::Po4a::TransTractor
0.41
[jjiang@fedora14 ~]$ po4a-gettextize --help-format
List of valid formats:
- dia: uncompressed Dia diagrams.
- docbook: DocBook XML.
- guide: Gentoo Linux's XML documentation format.
- ini: INI format.
- kernelhelp: Help messages of each kernel compilation option.
- latex: LaTeX format.
- man: Good old manual page format.
- pod: Perl Online Documentation format.
- sgml: either DebianDoc or DocBook DTD.
- texinfo: The info page format.
- tex: generic TeX documents (see also latex).
- text: simple text document.
- wml: WML documents.
- xhtml: XHTML documents.
- xml: generic XML documents (see also docbook).
[jjiang@fedora14 ~]$ perldoc -l perlretut
/usr/share/perl5/pod/perlretut.pod
[jjiang@fedora14 ~]$ po4a-gettextize -f pod -m $(perldoc -l perlretut) | tee perlretut.po | wc -l
5155
[jjiang@fedora14 ~]$ vim perlretut.po
…
#. type: =head1
#: /usr/share/perl5/pod/perlretut.pod:1
msgid "NAME"
msgstr "名称"
#. type: textblock
#: /usr/share/perl5/pod/perlretut.pod:3
msgid "perlretut - Perl regular expressions tutorial"
msgstr "perlretut - Perl 正则表达式指南"
#. type: =head1
#: /usr/share/perl5/pod/perlretut.pod:5
msgid "DESCRIPTION"
msgstr "简介"
#. type: textblock
#: /usr/share/perl5/pod/perlretut.pod:7
msgid ""
"This page provides a basic tutorial on understanding, creating and using "
"regular expressions in Perl. It serves as a complement to the reference "
"page on regular expressions L<perlre>. Regular expressions are an integral "
"part of the C<m//>, C<s///>, C<qr//> and C<split> operators and so this "
"tutorial also overlaps with L<perlop/\"Regexp Quote-Like Operators\"> and "
"L<perlfunc/split>."
msgstr ""
"这篇文章用来介绍 Perl 正则表达式的解读、编写和使用方面的基础知识。相对于 L<perlre> 中的介绍来说,这篇文章更加侧重于提供一些增补知识。正则表达式,它是 C<m//>, C<s///>, C<qr//> 和 C<split> 这些操作符的主要兴趣所在,因此L<perlop/\"Regexp Quote-Like Operators\"> 和 L<perlfunc/split> 里面也有许多相关的描述。"
…
[jjiang@fedora14 ~]$ po4a-translate -k 0 -f pod -m $(perldoc -l perlretut) -p perlretut.po | less
October 20, 2011
Non-stop debugging of perl programs
purl in your heart
Package -e.
in @=main::abc(0) from -e:1
out @=main::abc(0) from -e:1
list context return from main::abc:
0 1
in @=main::abc(3) from -e:1
out @=main::abc(3) from -e:1
list context return from main::abc:
0 4
1 4
October 19, 2011
PDC:慷慨也是信心的表现
purl in your heart
| ||
Generosity is a Matter of Faith慷慨也是信心的表现 | ||
A generous man will prosper and he who refreshes others will himself be refreshed. Proverbs 11:25 (NIV) When you share with others, God shares with you. 当你与他人分享的时候,神也会与你分享。 The world says, “Get everything you can and you will be financially secure.” The Bible says share with others in need and you’ll sow what you reap: “Give and it will be given to you.” (Luke 6:38 NIV) 这个世界的逻辑是“尽可能的攫取,这样你就会富有”,而圣经的原则是要尽可能的与他人分享,这样你就会有丰厚的回报:“你们要给人,就必有给你们的”(路加福音 6:38) God says that when you give to somebody else, you're not throwing it away. It’s an investment in the lives of others. God says the one who gives will gain even more: “He who is kind to the poor, lends to the Lord and He will reward him for what he has done.” (Proverbs 19:17 NIV) 在神的眼中,当你给予别人的时候,并不是在舍弃什么,而是对其他人的生命进行投资。神会对那些慷慨付出的人给予更多回报:“怜悯贫穷的,就是借给耶和华。他的善行,耶和华必偿还”(箴言 19:17) When you see people in need and you give to them, God looks at this as if it were a loan to Him. He says, “I will reward back.” 所以,当你向那些需要的人伸出援手的时候,神会把这看成是对�自己的一次借贷。�就这样想:“我必须偿还他”。 God is always going to take care of you and your needs. Do you believe that is true? Generosity is a matter of faith. Will you take God at his Word? 神总是想要帮助你,满足你的需要。你相信这个道理么?慷慨也是信心的一种表现。你要不要在这个方面顺服神的吩咐呢? |
October 12, 2011
remove/add job to crontab by commandline
Fayland And Programming1. add job to crontab
October 11, 2011
Psalm 118:24
purl in your heart
September 29, 2011
Draw the Cross in Unicode
purl in your heart
✞
September 28, 2011
sphinx 0.99 bug (attributes count vs fields count)
Fayland And Programmingwhen you have 4 columns in sql_query, and you want 3 columns as attributes. you'll get a failure. 0 size sphinx files.
OK. actually 'dumb' is dumb because it takes more disk than 'a'.SELECT id, radians(longitude) as long_radians, radians(latitude) as lat_radians, 'dumb' FROM table
September 25, 2011
Script to find the root directory usage, on system with lots of mounts
purl in your heart
sudo perl -MList::MoreUtils=any -lne 'BEGIN{@m=map {@F=split; qq(^$F[2])} map {$1 if m{(.*)}} qx{mount|tail --line=+2}; open STDIN, q(find / -maxdepth 3 -mindepth 1 |)} $p=$_; do {print join qq(\t), qx(du -s "$_")=~m{(.*)}} unless any {$p=~m{$_} or $_=~m{$p}} @m' | sort -k1 -nrg | head
September 24, 2011
Net-GitHub 0.40_02
Fayland And Programmingit's a story following the previous one. and this one will be shorter.
sub __build_methods {my $package = shift;my %methods = @_;foreach my $m (keys %methods) {my $v = $methods{$m};my $url = $v->{url};my $method = $v->{method} || 'GET';my $args = $v->{args} || 0; # args for ->querymy $check_status = $v->{check_status};my $is_u_repo = $v->{is_u_repo}; # need auto shift u/repo$package->meta->add_method( $m => sub {my $self = shift;# count how much %s inside umy $n = 0; while ($url =~ /\%s/g) { $n++ }## if is_u_repo, both ($user, $repo, @args) or (@args) should be supportedif ( ($is_u_repo or index($url, '/repos/%s/%s') > -1) and @_ < $n + $args) {unshift @_, ($self->u, $self->repo);}# make url, replace %s with real argsmy @uargs = splice(@_, 0, $n);my $u = sprintf($url, @uargs);# args for json data POSTmy @qargs = $args ? splice(@_, 0, $args) : ();if ($check_status) { # need check Response Statusmy $old_raw_response = $self->raw_response;$self->raw_response(1); # need check headermy $res = $self->query($method, $u, @qargs);$self->raw_response($old_raw_response);return index($res->header('Status'), $check_status) > -1 ? 1 : 0;} else {return $self->query($method, $u, @qargs);}} );}}
September 23, 2011
Net-GitHub 0.40_01
Fayland And Programmingit's a quite long story. but it's all about Net::GitHub
use Net::GitHub;my $gh = Net::GitHub->new( login => 'fayland', pass => 'secret' );my $data = $gh->query('/user');$gh->query('PATCH', '/user', { bio => 'another Perl Programmer and Father' });$gh->query('DELETE', '/user/emails', [ 'myemail@somewhere.com' ]);
2. more than half of the Github API is binded with :user/:repo. but it will be really very boring to type user/repo for every call.sub emails { (shift)->query('/user/emails'); }
I kicked out the version to public today. but there are still a lot of stuff missing. I released it because I want to hear some feedback from the users. below are some todos.$gh->set_default_user_repo('fayland', 'perl-net-github');my @issues = $gh->issue->issues;my @pulls = $gh->pull_request->pulls;# or one-off callmy @contributors = $gh->respo->contributors($user, $repo);
SQLite related 2 utilities, to fix the book & chapter names problems of Blackberry YouVersion bible reader
purl in your heart
SQLite.pl
#!/usr/bin/perl -w
use strict;
use DBI;
my @r;
my $d=DBI->connect(qq(dbi:SQLite:dbname=@{[shift]}), q(), q());
my $s=$d->prepare_cached(join q(),<STDIN>);
$s->execute(@ARGV);
$,=qq(\t); $\=qq(\n);
print STDERR @{$s->{NAME}}; print @r while @r=$s->fetchrow_array;
$s->finish; $d->disconnect;
Do-SQLite-for.pl
#!/usr/bin/perl -w
use strict;
use DBI;
my $d=DBI->connect(qq(dbi:SQLite:dbname=@{[shift]}), q(), q());
my $s= $d->prepare_cached(do { open(SQL, q(<), shift); join(q(),<SQL>) });
$,=qq(\t); $\=qq(\n);
while(<>) {
chomp;
my @F = split(qq(\t), $_, -1);
$s->execute(@F);
}
$s->finish; $d->disconnect; close SQL;





