How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.


"no module named sendgrid" error reported with below codes:

<?php
system("/usr/bin/python sendmail.py 2>&1");
system("/usr/bin/python --version 2>&1", $ret);
?>

sendmail.py

import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
to_email = Email("test@example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
....




nginx config your websites' favicon

        1. vim nginx.conf
        # set site favicon
        location /favicon.ico {
            root html;
        }

       2. place a favicon.ico file under html/

       3. optional, add below codes to your index.html.
<link rel="icon" href="/favicon.ico" mce_href="/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="/favicon.ico" mce_href="/favicon.ico" type="image/x-icon">    



        # set site favicon
        location /favicon.ico {
            root html;
        }

How to extend file extensions to be parsed by PHP

sudo vim /etc/php/7.0/fpm/pool.d/www.confsudo vim /etc/php/7.0/fpm/pool.d/www.conf
By default, PHP only parse files with .php extension.
We can extend extensions with security.limit_extensions directive.

sudo vim /etc/php/7.0/fpm/pool.d/www.conf
sudo vim /etc/php/7.0/fpm/pool.d/www.conf
; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; exectute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
; You can add any extensions you want to be parsed as php
security.limit_extensions = .php .php3 .php4 .php5 .php7 .ler

sudo service php7.0-fpm restart

Config nginx:

/etc/nginx/nginx.conf
        location ~ \.(php|ler)$ {
            include fastcgi.conf;
            fastcgi_pass   unix:/run/php/php7.0-fpm.sock;
        }

        location ~ \.(php|ler)$ {
            root vhosts/$root_name;
            include fastcgi.conf;
            fastcgi_pass   unix:/run/php/php7.0-fpm.sock;
        }
sudo service php7.0-fpm restart 

sudo service nginx restart

Let's do the test.

cat index.ler<?php
phpinfo();
?>
.ler parsed as .php too, works well.

How to set up LNMP(linux+nginx+mysql+php) developer tool on your ubuntu server

Install all software:
sudo apt-get install nginx
sudo apt-get install php7.0-fpm
sudo apt-get install php7.0-curl
sudo apt-get install php7.0-gd php7.0-mcrypt php7.0-mysql
sudo apt-get install mysql-server mysql-client

Please remember your mysql database root password!!!

Let's config up.

1. Add nginx user and group, nginx server and php-fpm will run as nginx user.
sudo groupadd nginx 
sudo groupadd nginx
sudo useradd -g nginx nginx
sudo service php7.0-fpm restart

2. Config php-fpm
/etc/php/7.0/fpm/php.ini
cgi.fix_pathinfo=0

/etc/php/7.0/fpm/pool.d/www.conf
listen = /run/php/php7.0-fpm.sock
listen.owner = nginx
listen.group = nginx

sudo service php7.0-fpm restart

3. Config nginx
/etc/nginx/nginx.conf
user nginx nginx;
location ~ \.php$ {
    include fastcgi.conf;
    fastcgi_pass   unix:/run/php/php7.0-fpm.sock;
}

sudo service nginx restart

PS:keep the user/group of php-fpm same as nginx server, I have marked as blue nginx above.


And it should not the same user that owns your virtual host directory for better security.
My websites are in vhosts folder, the user/group are errong_leng.
drwxrwxr-x  4 errong_leng errong_leng 4096 May 19 09:11 vhosts

Ok. let's do the test.
cat index.php
<?php
phpinfo();
?>

Everything looks fine.




cat index.php 
<?php
phpinfo();
?>
drwxrwxr-x  4 errong_leng errong_leng 4096 May 19 09:11 vhosts
drwxrwxr-x  4 errong_leng errong_leng 4096 May 19 09:11 vhosts
drwxrwxr-x  4 errong_leng errong_leng 4096 May 19 09:11 vhosts
drwxrwxr-x  4 errong_leng errong_leng 4096 May 19 09:11 vhosts

Send email with attachments on your google compute engine via sendgrid-python

precondition:
  1. Use the Google Cloud Launcher to sign up for the SendGrid Email service. Make a note of your SendGrid SMTP account credentials, which include username, password, and hostname. Your SMTP username and password are the same as what you used to sign up for the service. The SendGrid hostname is smtp.sendgrid.net.
  2. Create an API key:
    1. Sign in to Sendgrid and go to Settings > API Keys.
    2. Create an API key.
    3. Select the permissions for the key. At a minimum, the key will need Mail send permissions to send email.
    4. Click Save to create the key.
    5. SendGrid generates a new key. This is the only copy of the key so make sure to copy the key and save it for later.


 
Please remember your key and save it somewhere safe.
 
OK. Now we can use sendgrid python library to send email.
Of cause, you can still follow offical help to use sendgrid with other solution.
https://cloud.google.com/compute/docs/tutorials/sending-mail/using-sendgrid

install sendgrid-python 
$pip install sendgrid
 
Sample python codes:
errong_leng@blogvpn:~/algo$ cat sendmail.py
import base64
import getopt
import mimetypes
import os
import sendgrid
import sys
from sendgrid.helpers.mail import *

def useage():
    print ("python sendmail.py [-s subject] [-a attachment ] [-c cc-addr] [-b bcc-addr] [-f from-addr] [-t to-addr] to-addr . . .")
    sys.exit()

opts, args = getopt.getopt(sys.argv[1:], "ha:b:c:f:s:t:")

attachs = []
cc = []
bc = []
tc = []
from_addr = ''
subject = ''

for op, value in opts:
  if op == "-h":
      useage()
  elif op == "-a":
      attachs.append(value)
  elif op == "-b":
      bc.append(value)
  elif op == "-c":
      cc.append(value)
  elif op == "-s":
      subject = value
  elif op == "-f":
      from_addr = value
  elif op == "-t":
      tc.append(value)

if (len(args) <= 0):
    useage()

sg = sendgrid.SendGridAPIClient(apikey='REPLACEWITHYOURAPIKEY')
mail = Mail()
mail.from_email = (Email(from_addr))
mail.subject = subject
personalization = Personalization()
personalization.add_to(Email(args[0]))
for tcs in tc:
    personalization.add_to(Email(tcs))
for ccs in cc:
    personalization.add_cc(Email(ccs))
for bcc in bc:
    personalization.add_bcc(Email(bcc))
personalization.subject = subject
mail.add_personalization(personalization)

contents = args[1:]
for ct in contents:
    if (len(ct) > 0):
        mail.add_content(Content("text/plain", ct))
      
for af in attachs:
    data = ''
    with open(af, 'rb') as f:
        data = f.read()
        f.close()
    if (len(data) > 0):
        adata = base64.b64encode(data)
        attachment = Attachment()
        attachment.content = adata
        s = os.path.split(af)
        attachment.filename = s[len(s)-1]
        attachment.type = mimetypes.guess_type(attachment.filename)[0]
        attachment.disposition = "attachment"
        attachment.content_id = af
        mail.add_attachment(attachment)

response = sg.client.mail.send.post(request_body=mail.get())

print(response.status_code)
print(response.body)
print(response.headers)            
 
 
errong_leng@blogvpn:~/algo$ python sendmail.py -t "errong.leng@abc.com" -s 
"Hello" -f "errong.leng@gmail.com" -c "errong.leng@hotmail.com" 
-b "errong.leng@samsung.com" -a configs/104.199.178.17/zqzz.p12 
-a configs/104.199.178.17/zqzz.mobileconfig 
errong.leng@gmail.com "Hello with content and attachment" 
 
202

Server: nginx
Date: Fri, 19 May 2017 04:04:45 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 0
Connection: close
X-Message-Id: x7xHfWk8SmWlxUe6Ew6tmA
X-Frame-Options: DENY
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
 
Once you see 202, which means email sending successfully. 
 
 
 

神先爱了我们



当那日,我必为我的民,与田野的走兽和空中的飞鸟,并地上的昆虫立约;又必在国中折断弓刀,止息争战,使他们安然躺卧。  (何西阿书 2:18 和合本)
In that day I will make a covenant for them with the beasts of the field, the birds in the sky and the creatures that move along the ground. Bow and sword and battle I will abolish from the land, so that all may lie down in safety.  (Hosea 2:18 NIV)
我必聘你永远归我为妻,以仁义、公平、慈爱、怜悯聘你归我;  (何西阿书 2:19 和合本)
I will betroth you to me forever; I will betroth you in righteousness and justice, in love and compassion.  (Hosea 2:19 NIV)
也以诚实聘你归我,你就必认识我—耶和华。 (何西阿书 2:20 和合本)
I will betroth you in faithfulness, and you will acknowledge the Lord .  (Hosea 2:20 NIV)
耶和华说:那日我必应允,我必应允天,天必应允地; (何西阿书 2:21 和合本)
“In that day I will respond,” declares the Lord — “I will respond to the skies, and they will respond to the earth;  (Hosea 2:21 NIV)
地必应允五谷、新酒,和油,这些必应允耶斯列民(耶斯列就是 神栽种的意思) 。 (何西阿书 2:22 和合本)
and the earth will respond to the grain, the new wine and the olive oil, and they will respond to Jezreel.  (Hosea 2:22 NIV)
我必将她种在这地。素不蒙怜悯的,我必怜悯;本非我民的,我必对他说:你是我的民;他必说:你是我的 神。” (何西阿书 2:23 和合本)
I will plant her for myself in the land; I will show my love to the one I called ‘Not my loved one. ’ I will say to those called ‘Not my people, ’ ‘You are my people’; and they will say, ‘You are my God.’ ”  (Hosea 2:23 NIV)


The best way to force http request redirect to https in nginx

Use 301 redirect.
 
    server {
        listen  80;
        server_name blog.errong.win;
        return 301 https://$server_name$request_uri;
    }

    server {
        listen  80;
        server_name freevpn.errong.win;
        return 301 https://$server_name$request_uri;
    }

    server {
        listen  80;
        server_name www.errong.win errong.win;
        return 301 https://$server_name$request_uri;
    }

    server {
        listen       443 ssl;

        ssl_certificate      /etc/letsencrypt/live/errong.win/fullchain.pem;
        ssl_certificate_key  /etc/letsencrypt/live/errong.win/privkey.pem;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        server_name  ~^(.+)?\.errong\.win$;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   vhosts/$1;
            index  index.html index.htm;
        }
   } 
 
Remember reload your nginx server 
sudo sbin/nginx -s reload 

You can check with developer tool:
 

How to enable https of your websites with Let's Encrypt CA via nginx

To enable HTTPS on your website, you need to get a certificate (a type of file) from a Certificate Authority (CA). Let's Encrypt is a CA, the most famous free CA.
https://letsencrypt.org/getting-started/

How to config multi servers(second domain name server) with one server {} in your nginx.conf

config sample:

server {
    listen       80;
    server_name  ~^(.+)?\.errong\.win$;
    if ($host = errong.win) {
        rewrite ^ http://www.errong.win permanent;
    }

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   vhosts/$1;
        index  index.html index.htm;
    }
}

义人的祷告必蒙应允 耶稣基督是中保



他对我说:“大蒙眷爱的但以理啊,要明白我与你所说的话,只管站起来,因为我现在奉差遣来到你这里。”他对我说这话,我便战战兢兢地立起来。  (但以理书 10:11 和合本)
He said, “Daniel, you who are highly esteemed, consider carefully the words I am about to speak to you, and stand up, for I have now been sent to you.” And when he said this to me, I stood up trembling.  (Daniel 10:11 NIV)
他就说:“但以理啊,不要惧怕!因为从你第一日专心求明白将来的事,又在你 神面前刻苦己心,你的言语已蒙应允;我是因你的言语而来。  (但以理书 10:12 和合本)
Then he continued, “Do not be afraid, Daniel. Since the first day that you set your mind to gain understanding and to humble yourself before your God, your words were heard, and I have come in response to them.  (Daniel 10:12 NIV)
他说:“大蒙眷爱的人哪,不要惧怕,愿你平安!你总要坚强。”他一向我说话,我便觉得有力量,说:“我主请说,因你使我有力量。”  (但以理书 10:19 和合本)
“Do not be afraid, you who are highly esteemed,” he said. “Peace! Be strong now; be strong.” When he spoke to me, I was strengthened and said, “Speak, my lord, since you have given me strength.”  (Daniel 10:19 NIV)


Set up ikev2 VPN on your Google Compute Engine via strongswan

Accually, There is one key set up scripts, algo.
Algo supports DigitalOcean (most user friendly), Amazon EC2, Google Compute Engine, and Microsoft Azure.

Install strongswan:
sudo apt-get install strongswan strongswan-plugin-eap-mschapv2 strongswan-plugin-xauth-generic

errong_leng@freevpn:~$ ipsec version
Linux strongSwan U5.3.5/K4.8.0-51-generic
Institute for Internet Technologies and Applications
University of Applied Sciences Rapperswil, Switzerland
See 'ipsec --copyright' for copyright information.

不可跪拜那些像,也不可事奉它,因为我耶和华—你的 神是忌邪的 神。恨我的,我必追讨他的罪,自父及子,直到三四代;  (出埃及记 20:5 和合本)
You shall not bow down to them or worship them; for I, the Lord your God, am a jealous God, punishing the children for the sin of the parents to the third and fourth generation of those who hate me,  (Exodus 20:5 NIV)
爱我、守我诫命的,我必向他们发慈爱,直到千代。 (出埃及记 20:6 和合本)
but showing love to a thousand generations of those who love me and keep my commandments.  (Exodus 20:6 NIV)

尼布甲尼撒问他们说:“沙得拉、米煞、亚伯尼歌,你们不事奉我的神,也不敬拜我所立的金像,是故意的吗?  (但以理书 3:14 和合本)
and Nebuchadnezzar said to them, “Is it true, Shadrach, Meshach and Abednego, that you do not serve my gods or worship the image of gold I have set up?  (Daniel 3:14 NIV)
你们再听见角、笛、琵琶、琴、瑟、笙,和各样乐器的声音,若俯伏敬拜我所造的像,却还可以;若不敬拜,必立时扔在烈火的窑中,有何神能救你们脱离我手呢?” (但以理书 3:15 和合本)
Now when you hear the sound of the horn, flute, zither, lyre, harp, pipe and all kinds of music, if you are ready to fall down and worship the image I made, very good. But if you do not worship it, you will be thrown immediately into a blazing furnace. Then what god will be able to rescue you from my hand?”  (Daniel 3:15 NIV)
沙得拉、米煞、亚伯尼歌对王说:“尼布甲尼撒啊,这件事我们不必回答你,  (但以理书 3:16 和合本)
Shadrach, Meshach and Abednego replied to him, “King Nebuchadnezzar, we do not need to defend ourselves before you in this matter.  (Daniel 3:16 NIV)
即便如此,我们所事奉的 神能将我们从烈火的窑中救出来。王啊,他也必救我们脱离你的手;  (但以理书 3:17 和合本)
If we are thrown into the blazing furnace, the God we serve is able to deliver us from it, and he will deliver us from Your Majesty’s hand.  (Daniel 3:17 NIV)
即或不然,王啊,你当知道我们决不事奉你的神,也不敬拜你所立的金像。” (但以理书 3:18 和合本)
But even if he does not, we want you to know, Your Majesty, that we will not serve your gods or worship the image of gold you have set up.”  (Daniel 3:18 NIV)
那时,尼布甲尼撒王惊奇,急忙起来,对谋士说:“我们捆起来扔在火里的不是三个人吗?”他们回答王说:“王啊,是。”  (但以理书 3:24 和合本)
Then King Nebuchadnezzar leaped to his feet in amazement and asked his advisers, “Weren’t there three men that we tied up and threw into the fire?” They replied, “Certainly, Your Majesty.”  (Daniel 3:24 NIV)
王说:“看哪,我见有四个人,并没有捆绑,在火中游行,也没有受伤;那第四个的相貌好像神子。” (但以理书 3:25 和合本)
He said, “Look! I see four men walking around in the fire, unbound and unharmed, and the fourth looks like a son of the gods.”  (Daniel 3:25 NIV)
于是,尼布甲尼撒就近烈火窑门,说:“至高 神的仆人沙得拉、米煞、亚伯尼歌出来,上这里来吧!”沙得拉、米煞、亚伯尼歌就从火中出来了。  (但以理书 3:26 和合本)
Nebuchadnezzar then approached the opening of the blazing furnace and shouted, “Shadrach, Meshach and Abednego, servants of the Most High God, come out! Come here!” So Shadrach, Meshach and Abednego came out of the fire,  (Daniel 3:26 NIV)
那些总督、钦差、巡抚,和王的谋士一同聚集看这三个人,见火无力伤他们的身体,头发也没有烧焦,衣裳也没有变色,并没有火燎的气味。  (但以理书 3:27 和合本)
and the satraps, prefects, governors and royal advisers crowded around them. They saw that the fire had not harmed their bodies, nor was a hair of their heads singed; their robes were not scorched, and there was no smell of fire on them.  (Daniel 3:27 NIV)
尼布甲尼撒说:“沙得拉、米煞、亚伯尼歌的 神是应当称颂的!他差遣使者救护倚靠他的仆人,他们不遵王命,舍去己身,在他们 神以外不肯事奉敬拜别神。  (但以理书 3:28 和合本)
Then Nebuchadnezzar said, “Praise be to the God of Shadrach, Meshach and Abednego, who has sent his angel and rescued his servants! They trusted in him and defied the king’s command and were willing to give up their lives rather than serve or worship any god except their own God.  (Daniel 3:28 NIV)

神显明深奥隐密的事



但以理说:“ 神的名是应当称颂的!从亘古直到永远,因为智慧能力都属乎他。  (但以理书 2:20 和合本)
and said: “Praise be to the name of God for ever and ever; wisdom and power are his.  (Daniel 2:20 NIV)
他改变时候、日期,废王,立王,将智慧赐与智慧人,将知识赐与聪明人。  (但以理书 2:21 和合本)
He changes times and seasons; he deposes kings and raises up others. He gives wisdom to the wise and knowledge to the discerning.  (Daniel 2:21 NIV)
他显明深奥隐秘的事,知道暗中所有的,光明也与他同居。  (但以理书 2:22 和合本)
He reveals deep and hidden things; he knows what lies in darkness, and light dwells with him.  (Daniel 2:22 NIV)
当那列王在位的时候,天上的 神必另立一国,永不败坏,也不归别国的人,却要打碎灭绝那一切国,这国必存到永远。  (但以理书 2:44 和合本)
“In the time of those kings, the God of heaven will set up a kingdom that will never be destroyed, nor will it be left to another people. It will crush all those kingdoms and bring them to an end, but it will itself endure forever.  (Daniel 2:44 NIV)


神吩咐

 神吩咐这一切的话说:  (出埃及记 20:1 和合本)
And God spoke all these words:  (Exodus 20:1 NIV)
“我是耶和华—你的 神,曾将你从埃及地为奴之家领出来。 (出埃及记 20:2 和合本)
“I am the Lord your God, who brought you out of Egypt, out of the land of slavery.  (Exodus 20:2 NIV)
“除了我以外,你不可有别的神。 (出埃及记 20:3 和合本)
“You shall have no other gods before me.  (Exodus 20:3 NIV)
“不可为自己雕刻偶像,也不可做什么形象仿佛上天、下地,和地底下、水中的百物。  (出埃及记 20:4 和合本)
“You shall not make for yourself an image in the form of anything in heaven above or on the earth beneath or in the waters below.  (Exodus 20:4 NIV)
不可跪拜那些像,也不可事奉它,因为我耶和华—你的 神是忌邪的 神。恨我的,我必追讨他的罪,自父及子,直到三四代;  (出埃及记 20:5 和合本)
You shall not bow down to them or worship them; for I, the Lord your God, am a jealous God, punishing the children for the sin of the parents to the third and fourth generation of those who hate me,  (Exodus 20:5 NIV)
爱我、守我诫命的,我必向他们发慈爱,直到千代。 (出埃及记 20:6 和合本)
but showing love to a thousand generations of those who love me and keep my commandments.  (Exodus 20:6 NIV)
“不可妄称耶和华—你 神的名;因为妄称耶和华名的,耶和华必不以他为无罪。 (出埃及记 20:7 和合本)
“You shall not misuse the name of the Lord your God, for the Lord will not hold anyone guiltless who misuses his name.  (Exodus 20:7 NIV)
“当记念安息日,守为圣日。  (出埃及记 20:8 和合本)
“Remember the Sabbath day by keeping it holy.  (Exodus 20:8 NIV)
六日要劳碌做你一切的工,  (出埃及记 20:9 和合本)
Six days you shall labor and do all your work,  (Exodus 20:9 NIV)
但第七日是向耶和华—你 神当守的安息日。这一日你和你的儿女、仆婢、牲畜,并你城里寄居的客旅,无论何工都不可做;  (出埃及记 20:10 和合本)
but the seventh day is a sabbath to the Lord your God. On it you shall not do any work, neither you, nor your son or daughter, nor your male or female servant, nor your animals, nor any foreigner residing in your towns.  (Exodus 20:10 NIV)
因为六日之内,耶和华造天、地、海,和其中的万物,第七日便安息,所以耶和华赐福与安息日,定为圣日。 (出埃及记 20:11 和合本)
For in six days the Lord made the heavens and the earth, the sea, and all that is in them, but he rested on the seventh day. Therefore the Lord blessed the Sabbath day and made it holy.  (Exodus 20:11 NIV)
“当孝敬父母,使你的日子在耶和华—你 神所赐你的地上得以长久。 (出埃及记 20:12 和合本)
“Honor your father and your mother, so that you may live long in the land the Lord your God is giving you.  (Exodus 20:12 NIV)
“不可杀人。 (出埃及记 20:13 和合本)
“You shall not murder.  (Exodus 20:13 NIV)
“不可奸淫。 (出埃及记 20:14 和合本)
“You shall not commit adultery.  (Exodus 20:14 NIV)
“不可偷盗。 (出埃及记 20:15 和合本)
“You shall not steal.  (Exodus 20:15 NIV)
“不可作假见证陷害人。 (出埃及记 20:16 和合本)
“You shall not give false testimony against your neighbor.  (Exodus 20:16 NIV)
“不可贪恋人的房屋;也不可贪恋人的妻子、仆婢、牛驴,并他一切所有的。” (出埃及记 20:17 和合本)
“You shall not covet your neighbor’s house. You shall not covet your neighbor’s wife, or his male or female servant, his ox or donkey, or anything that belongs to your neighbor.”  (Exodus 20:17 NIV)


Install nginx from source for your google compute engine vm instance (ubuntu 16.04)

Dependence Installation: zlib, pcre, openssl
sudo apt-get install openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev
( if you want to compile them from source,
get zlib source:
wget http://zlib.net/zlib-1.2.11.tar.gz
gunzip zlib-1.2.11.tar.gz
tar -xvf zlib-1.2.11.tar
mv zlib-1.2.11 zlib

get pcre source:
svn co svn://vcs.exim.org/pcre2/code/trunk pcre
)


I want to install nginx on my my google compute engine.

Use SSH Client to connect your Google Compute Engine

The easy way is via browser.


Below is use putty.exe on windows.
Other system, you can refer to offical guide.

Try free Google Cloud Platform for 12 month, Setup VPS via GCE(Google Computer Engine)

GCP official websites

1. https://cloud.google.com
2. https://cloud.google.com/free/

Always free for GCE













诸天述说 神的荣耀;穹苍传扬他的手段。 (诗篇 19:1 和合本)
 The heavens declare the glory of God; the skies proclaim the work of his hands.  (Psalms 19:1 NIV)
这日到那日发出言语;这夜到那夜传出知识。 (诗篇 19:2 和合本)
Day after day they pour forth speech; night after night they reveal knowledge.  (Psalms 19:2 NIV)
无言无语,也无声音可听。 (诗篇 19:3 和合本)
They have no speech, they use no words; no sound is heard from them.  (Psalms 19:3 NIV)
它的量带通遍天下,它的言语传到地极。 神在其间为太阳安设帐幕; (诗篇 19:4 和合本)
Yet their voice goes out into all the earth, their words to the ends of the world. In the heavens God has pitched a tent for the sun.  (Psalms 19:4 NIV)
太阳如同新郎出洞房,又如勇士欢然奔路。 (诗篇 19:5 和合本)
It is like a bridegroom coming out of his chamber, like a champion rejoicing to run his course.  (Psalms 19:5 NIV)
它从天这边出来,绕到天那边,没有一物被隐藏不得它的热气。 (诗篇 19:6 和合本)
It rises at one end of the heavens and makes its circuit to the other; nothing is deprived of its warmth.  (Psalms 19:6 NIV)
耶和华的律法全备,能苏醒人心;耶和华的法度确定,能使愚人有智慧。 (诗篇 19:7 和合本)
The law of the Lord is perfect, refreshing the soul. The statutes of the Lord are trustworthy, making wise the simple.  (Psalms 19:7 NIV)
耶和华的训词正直,能快活人的心;耶和华的命令清洁,能明亮人的眼目。 (诗篇 19:8 和合本)
The precepts of the Lord are right, giving joy to the heart. The commands of the Lord are radiant, giving light to the eyes.  (Psalms 19:8 NIV)
耶和华的道理洁净,存到永远;耶和华的典章真实,全然公义— (诗篇 19:9 和合本)
The fear of the Lord is pure, enduring forever. The decrees of the Lord are firm, and all of them are righteous.  (Psalms 19:9 NIV)
都比金子可羡慕,且比极多的精金可羡慕;比蜜甘甜,且比蜂房下滴的蜜甘甜。 (诗篇 19:10 和合本)
They are more precious than gold, than much pure gold; they are sweeter than honey, than honey from the honeycomb.  (Psalms 19:10 NIV)
况且你的仆人因此受警戒,守着这些便有大赏。 (诗篇 19:11 和合本)
By them your servant is warned; in keeping them there is great reward.  (Psalms 19:11 NIV)
谁能知道自己的错失呢?愿你赦免我隐而未现的过错。 (诗篇 19:12 和合本)
But who can discern their own errors? Forgive my hidden faults.  (Psalms 19:12 NIV)
求你拦阻仆人不犯任意妄为的罪,不容这罪辖制我,我便完全,免犯大罪。 (诗篇 19:13 和合本)
Keep your servant also from willful sins; may they not rule over me. Then I will be blameless, innocent of great transgression.  (Psalms 19:13 NIV)
耶和华—我的磐石,我的救赎主啊,愿我口中的言语、心里的意念在你面前蒙悦纳。 (诗篇 19:14 和合本)
May these words of my mouth and this meditation of my heart be pleasing in your sight, Lord , my Rock and my Redeemer.  (Psalms 19:14 NIV)


Can const_cast do change the constant in c/c++ ? No, in c/c++ const is const, and never change.

Consider below simple codes, what is the correct output ?

#include <stdio.h>

int main() {
  const int constant = 300;
  int* modifier = const_cast<int*>(&constant);
  printf("%d\n", constant);
  *modifier = 100;
  printf("%d\n", *modifier);
  printf("%d\n", constant);
  return 0;
}


Generate image dataset from one folder, label each image one by one, for machine learning via tensorflow

This is an update for previous post.
http://lengerrong.blogspot.com/2017/04/create-your-own-dataset-for-machine.html

It is hard to collect enough images for your machine traning.
So I update this post to append images once you find some to your existed dataset.
All you need to do is copy your images to a folder and run the python script.

Of cause, you have to label each image while running the python script.
Below python script just have two label, 0 means cat, 1 means dog.
You can add more labels by just modify blue codes.

How to fix tf.nn.in_top_k out of range issue: tensorflow.python.framework.errors_impl.InvalidArgumentError: targets[0] is out of range

tensorflow.python.framework.errors_impl.InvalidArgumentError: targets[0] is out of range
         [[Node: InTopK = InTopK[T=DT_INT32, k=1, _device="/job:localhost/replica:0/task:0/cpu:0"](softmax_linear/softmax_linear, Reshape_1)]]

Caused by op u'InTopK', defined at:


主的道是公平的 当回头得以存活



“恶人若回头离开所做的一切罪恶,谨守我一切的律例,行正直与合理的事,他必定存活,不致死亡。  (以西结书 18:21 和合本)
“But if a wicked person turns away from all the sins they have committed and keeps all my decrees and does what is just and right, that person will surely live; they will not die.  (Ezekiel 18:21 NIV)
他所犯的一切罪过都不被记念,因所行的义,他必存活。  (以西结书 18:22 和合本)
None of the offenses they have committed will be remembered against them. Because of the righteous things they have done, they will live.  (Ezekiel 18:22 NIV)
主耶和华说:恶人死亡,岂是我喜悦的吗?不是喜悦他回头离开所行的道存活吗?  (以西结书 18:23 和合本)
Do I take any pleasure in the death of the wicked? declares the Sovereign Lord . Rather, am I not pleased when they turn from their ways and live?  (Ezekiel 18:23 NIV)
义人若转离义行而作罪孽,照着恶人所行一切可憎的事而行,他岂能存活吗?他所行的一切义都不被记念;他必因所犯的罪、所行的恶死亡。 (以西结书 18:24 和合本)
“But if a righteous person turns from their righteousness and commits sin and does the same detestable things the wicked person does, will they live? None of the righteous things that person has done will be remembered. Because of the unfaithfulness they are guilty of and because of the sins they have committed, they will die.  (Ezekiel 18:24 NIV)
“你们还说:‘主的道不公平!’以色列家啊,你们当听,我的道岂不公平吗?你们的道岂不是不公平吗?  (以西结书 18:25 和合本)
“Yet you say, ‘The way of the Lord is not just.’ Hear, you Israelites: Is my way unjust? Is it not your ways that are unjust?  (Ezekiel 18:25 NIV)
义人若转离义行而作罪孽死亡,他是因所作的罪孽死亡。  (以西结书 18:26 和合本)
If a righteous person turns from their righteousness and commits sin, they will die for it; because of the sin they have committed they will die.  (Ezekiel 18:26 NIV)
再者,恶人若回头离开所行的恶,行正直与合理的事,他必将性命救活了。  (以西结书 18:27 和合本)
But if a wicked person turns away from the wickedness they have committed and does what is just and right, they will save their life.  (Ezekiel 18:27 NIV)
因为他思量,回头离开所犯的一切罪过,必定存活,不致死亡。  (以西结书 18:28 和合本)
Because they consider all the offenses they have committed and turn away from them, that person will surely live; they will not die.  (Ezekiel 18:28 NIV)
以色列家还说:‘主的道不公平!’以色列家啊,我的道岂不公平吗?你们的道岂不是不公平吗?” (以西结书 18:29 和合本)
Yet the Israelites say, ‘The way of the Lord is not just.’ Are my ways unjust, people of Israel? Is it not your ways that are unjust?  (Ezekiel 18:29 NIV)
所以主耶和华说:“以色列家啊,我必按你们各人所行的审判你们。你们当回头离开所犯的一切罪过。这样,罪孽必不使你们败亡。  (以西结书 18:30 和合本)
“Therefore, you Israelites, I will judge each of you according to your own ways, declares the Sovereign Lord . Repent! Turn away from all your offenses; then sin will not be your downfall.  (Ezekiel 18:30 NIV)
你们要将所犯的一切罪过尽行抛弃,自做一个新心和新灵。以色列家啊,你们何必死亡呢?  (以西结书 18:31 和合本)
Rid yourselves of all the offenses you have committed, and get a new heart and a new spirit. Why will you die, people of Israel?  (Ezekiel 18:31 NIV)
主耶和华说:我不喜悦那死人之死,所以你们当回头而存活。” (以西结书 18:32 和合本)
For I take no pleasure in the death of anyone, declares the Sovereign Lord . Repent and live!  (Ezekiel 18:32 NIV)


我们不致消灭,是出于耶和华诸般的慈爱;是因他的怜悯不致断绝。 (耶利米哀歌 3:22 和合本)
Because of the Lord ’s great love we are not consumed, for his compassions never fail.  (Lamentations 3:22 NIV)
每早晨,这都是新的;你的诚实极其广大! (耶利米哀歌 3:23 和合本)
They are new every morning; great is your faithfulness.  (Lamentations 3:23 NIV)
我心里说:耶和华是我的分,因此,我要仰望他。 (耶利米哀歌 3:24 和合本)
I say to myself, “The Lord is my portion; therefore I will wait for him.”  (Lamentations 3:24 NIV)
凡等候耶和华,心里寻求他的,耶和华必施恩给他。 (耶利米哀歌 3:25 和合本)
The Lord is good to those whose hope is in him, to the one who seeks him;  (Lamentations 3:25 NIV)
人仰望耶和华,静默等候他的救恩,这原是好的。 (耶利米哀歌 3:26 和合本)
it is good to wait quietly for the salvation of the Lord .  (Lamentations 3:26 NIV)
人在幼年负轭,这原是好的。 (耶利米哀歌 3:27 和合本)
It is good for a man to bear the yoke while he is young.  (Lamentations 3:27 NIV)


python show an image via subprocess.Popen

import tensorflow as tf
import Image
import os
import subprocess

def main(argv): 
  folder = argv[0]
  if (len(argv) > 1):
    if tf.gfile.Exists(argv[1]):
      folder = argv[1]
    else:
      print ('%s not existed' % argv[1])
      return
  else:
    print ("please input training image data folder path")
    return
  for f in tf.gfile.ListDirectory(folder):
    filepath = os.path.join(folder, f)
    try:
      im = Image.open(filepath)
      p = subprocess.Popen(["display", filepath])
      label = raw_input("please label the image, 0 means cat, 1 means dog:")
      p.kill()
    except Exception, e:
      print (e)

python Thread.join & setDaemon sample

prototype:

join([timeout]) # wait the child thread complete

setDaemon(True) # once the daemon thread complete, the child thread complete too.

from threading import Thread
from PIL import Image

    class ImageThread(Thread):
      def __init__(self, filepath):
        Thread.__init__(self)
        self.filepath = filepath
        self.openresult = 0

      def run(self):
        try:
          im = Image.open(self.filepath)
          im.show()
          self.openresult = 1
        except Exception, e:
          print (e)

    imt = ImageThread('image.gif')
    imt.setDaemon(True) # should set before start
    imt.start()
    imt.join(10) # wait 10 seconds

Solution for no image display after call Image.show via python

simple python code like:
 
from PIL import Image   
image = Image.open('image.gif' 
image.show() 

no image display while running on ubuntu system.

The easy solution is:
sudo apt-get install imagemagick

耶和华以永远的爱爱你 以慈爱吸引你



耶和华说:“那时,我必作以色列各家的 神;他们必作我的子民。”  (耶利米书 31:1 和合本)
“At that time,” declares the Lord , “I will be the God of all the families of Israel, and they will be my people.”  (Jeremiah 31:1 NIV)
耶和华如此说:脱离刀剑的就是以色列人。我使他享安息的时候,他曾在旷野蒙恩。 (耶利米书 31:2 和合本)
This is what the Lord says: “The people who survive the sword will find favor in the wilderness; I will come to give rest to Israel.”  (Jeremiah 31:2 NIV)
古时(或译:从远方) 耶和华向以色列(原文是我) 显现,说:我以永远的爱爱你,因此我以慈爱吸引你。 (耶利米书 31:3 和合本)
The Lord appeared to us in the past, saying: “I have loved you with an everlasting love; I have drawn you with unfailing kindness.  (Jeremiah 31:3 NIV)
以色列的民(原文是处女) 哪,我要再建立你,你就被建立;你必再以击鼓为美,与欢乐的人一同跳舞而出; (耶利米书 31:4 和合本)
I will build you up again, and you, Virgin Israel, will be rebuilt. Again you will take up your timbrels and go out to dance with the joyful.  (Jeremiah 31:4 NIV)
又必在撒马利亚的山上栽种葡萄园,栽种的人要享用所结的果子。 (耶利米书 31:5 和合本)
Again you will plant vineyards on the hills of Samaria; the farmers will plant them and enjoy their fruit.  (Jeremiah 31:5 NIV)
日子必到,以法莲山上守望的人必呼叫说:起来吧!我们可以上锡安,到耶和华—我们的 神那里去。 (耶利米书 31:6 和合本)
There will be a day when watchmen cry out on the hills of Ephraim, ‘Come, let us go up to Zion, to the Lord our God.’ ”  (Jeremiah 31:6 NIV)
耶和华如此说:你们当为雅各欢乐歌唱,因万国中为首的欢呼。当传扬颂赞说:耶和华啊,求你拯救你的百姓以色列所剩下的人。 (耶利米书 31:7 和合本)
This is what the Lord says: “Sing with joy for Jacob; shout for the foremost of the nations. Make your praises heard, and say, ‘Lord , save your people, the remnant of Israel.’  (Jeremiah 31:7 NIV)


fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...