понедельник, 23 ноября 2015 г.

Upload a folder to s3

from boto3.session import Session
import os

session = Session(
    region_name='eu-central-1',  # Put your region name

resource = session.resource('s3')

bucket = resource.Bucket('your_bucket_name')

from_dir = 'your_folder_name'

for fn in os.listdir(from_dir):
    file_obj = open(os.path.join(from_dir, fn), 'rb')

    to_folder = ''

        Key=os.path.join(to_folder, os.path.basename(file_obj.name)),
    print '%s loaded' % fn

воскресенье, 19 января 2014 г.

Integral Step-by-Step Calculator on Android!

I write my first android application.

I used.. python!

You can write android application on python - use python framework kivy
(write a application supported on many operation systems: mac, windows, linux, android, ios, and sony play station and other)

So, my first android application - Integral Step-by-Step Calculator (link to google play)

This app calculate a integrals:

Offline Integral Step-By-Step Calculator (without online and internet):
* A indefinite integral
* A definite integral
* A improper integral

понедельник, 6 января 2014 г.

Large Scale Machine Learning and Other Animals: Installing BLAS/Lapack/ITPP on Amazon EC2/Ubuntu L...

 Installing BLAS/Lapack/ITPP on Amazon EC2/Ubuntu Linux
BLAS/Lapack are efficient matrix math libraries. The following instructions explains how to install them for Amazon EC2 (Ubuntu maverick version, and Amazon Linux). It++ (itpp) is a popular c++ wrapper for blas/lapack.

DISLAIMER: The below instructions are for 64 bit machines. For 32 bit machines follow other instructions: http://bickson.blogspot.com/2011/06/graphlab-pmf-on-32-bit-linux.html

Just use Amazon EC2 public image ami-c21eedab (Ubuntu)

Try to install itpp using the following command:

sudo yum install libitpp-dev


sudo apt-get install libitpp-dev

TIP: You may also want to install libitpp7-dbg using the yum/apt-get command.
It is not mandatory, but it helps debugging when you link against libitpp_debug.so
(instead of libitpp.so).

If the above worked then we are done. If not, you will need to follow
instructions below. Thanks to Udi Weinsberg for this tip.


0) Start with an Ubuntu image like ami-641eed0d, or an Amazon AMI image like:

1) Install required packages. For Ubuntu:

sudo apt-get install --yes --force-yes automake autoconf libtool* gfortran

For Amazon Linux:

sudo yum install -y automake autoconf libtool* gcc-gfortran

2) Install lapack.
Here again their are two options:

The easy way is to simply (On Ububtu)

sudo apt-get install --yes --force-yes liblapack-dev

On Amazon Linux:

sudo yum install -y lapack-devel blas-devel

Thanks Akshay Bhat from Cornell for this tip!
If the liblapack setup was successful, go to step 3.

If the above command DOES NOT work for you (depends on your OS and setup) you will need to install lapack manually. The procedure is explained in steps a-c below.

a) Download and prepare the code

wget http://www.netlib.org/lapack/lapack.tgz
tar xvzf lapack.tgz
cd lapack-3.3.0  //if version number changes, change here to the right directory
mv make.inc.example make.inc

b) edit make.inc and add -m64 -fPIC flag to fortran compiler options:

c) compile

make blaslib

If everthing went OK, test will be run for a couple of minutes
and the files blas_LINUX.a and lapack_LINUX.a will be created at the main directory

3) setup LDFLAGS

export LDFLAGS="-L/usr/lib -lgfortran"

4) Download and install itpp from

wget http://sourceforge.net/projects/itpp/files/itpp/4.2.0/itpp-4.2.tar.gz
tar xvzf itpp-4.2.tar.gz
cd itpp-4.2

If you installed Lapack from yum/apt-get, you should use the following command:

./configure --without-fft --with-blas=/usr/lib64/libblas.so --with-lapack=/usr/lib64/liblapack.so --enable-debug CFLAGS=-fPIC CXXFLAGS=-fPIC CPPFLAGS=-fPIC

Where /usr/lib64/ is the place where lapack was installed.

If you installed lapack from source, use the following command

./configure --without-fft --with-blas=/home/ubuntu/lapack-3.3.0/blas_LINUX.a --with-lapack=/home/ubuntu/lapack-3.3.0/lapack_LINUX.a CFLAGS=-fPIC CXXFLAGS=-fPIC CPPFLAGS=-fPIC

sudo make install

Note: If you installed lapack from yum/apt-get, don't forget to add the -lblas -llapack linker flag when you compile against lapack/blas.

Verifying installation
To verify that installation went Ok, run the following commands:

itpp-config --cflags
itpp-config --libs

1) The command itpp-config should be available from shell.
2) The right installation path should appear as output.

Known issues you may encounter:

*** Warning: Linking the shared library libitpp.la against the^M
*** static library /usr/lib64/libblas.a is not portable!^M
libtool: link: g++ -shared -nostdlib /usr/lib/gcc/x86_64-amazon-linux/4.4.4/../../../../lib64/crti.o /usr/lib/gcc/x86_64-amazon-linux/4.4.4/crtbeginS.o  -Wl,--whole-archive ../itpp/base/.libs/libbase.a ../itpp/stat/.libs/libstat.a ../itpp/comm/.libs/libcomm.a ../itpp/fixed/.libs/libfixed.a ../itpp/optim/.libs/liboptim.a ../itpp/protocol/.libs/libprotocol.a ../itpp/signal/.libs/libsignal.a ../itpp/srccode/.libs/libsrccode.a -Wl,--no-whole-archive  -L/usr/lib64/ /usr/lib64/liblapack.a /usr/lib64/libblas.a -lgfortranbegin -lgfortran -L/usr/lib/gcc/x86_64-amazon-linux/4.4.4 -L/usr/lib/gcc/x86_64-amazon-linux/4.4.4/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-amazon-linux/4.4.4/../../.. -lstdc++ -lm -lc -lgcc_s /usr/lib/gcc/x86_64-amazon-linux/4.4.4/crtendS.o /usr/lib/gcc/x86_64-amazon-linux/4.4.4/../../../../lib64/crtn.o    -Wl,-soname -Wl,libitpp.so.7 -o .libs/libitpp.so.7.0.0^M
/usr/bin/ld: /usr/lib64/liblapack.a(dgees.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC^M
/usr/lib64/liblapack.a: could not read symbols: Bad value^M
collect2: ld returned 1 exit status^M
make[2]: *** [libitpp.la] Error 1^M

Solution: it seems that lapack was statically compiled without the -fPIC option and thus itpp refuses to link against it. Follow step 2a to install lapack manaually with the -fPIC option.


make[1]: *** Waiting for unfinished jobs....
[ 83%] Building CXX object src/graphlab/CMakeFiles/
graphlab_pic.dir/distributed2/distributed_scheduler_list.o /usr/local/lib/libitpp.so: undefined reference to `zgesv_' /usr/local/lib/libitpp.so: undefined reference to `dorgqr_' /usr/local/lib/libitpp.so: undefined reference to `dswap_' /usr/local/lib/libitpp.so: undefined reference to `dgeqp3_' /usr/local/lib/libitpp.so: undefined reference to `dpotrf_' /usr/local/lib/libitpp.so: undefined reference to `dgemm_' /usr/local/lib/libitpp.so: undefined reference to `zungqr_' /usr/local/lib/libitpp.so: undefined reference to `zscal_' /usr/local/lib/libitpp.so: undefined reference to `dscal_' /usr/local/lib/libitpp.so: undefined reference to `dgesv_' /usr/local/lib/libitpp.so: undefined reference to `dgetri_' /usr/local/lib/libitpp.so: undefined reference to `zgemm_' /usr/local/lib/libitpp.so: undefined reference to `zposv_' /usr/local/lib/libitpp.so: undefined reference to `zgetri_' /usr/local/lib/libitpp.so: undefined reference to `dgeev_' /usr/local/lib/libitpp.so: undefined reference to `zgemv_' /usr/local/lib/libitpp.so: undefined reference to `zgeqrf_' /usr/local/lib/libitpp.so: undefined reference to `zgerc_' /usr/local/lib/libitpp.so: undefined reference to `zswap_' /usr/local/lib/libitpp.so: undefined reference to `zgeev_' /usr/local/lib/libitpp.so: undefined reference to `daxpy_' /usr/local/lib/libitpp.so: undefined reference to `dgetrf_' /usr/local/lib/libitpp.so: undefined reference to `zgels_' /usr/local/lib/libitpp.so: undefined reference to `zgetrf_' /usr/local/lib/libitpp.so: undefined reference to `dgees_' /usr/local/lib/libitpp.so: undefined reference to `dcopy_' /usr/local/lib/libitpp.so: undefined reference to `dger_' /usr/local/lib/libitpp.so: undefined reference to `dgels_' /usr/local/lib/libitpp.so: undefined reference to `dgeqrf_' /usr/local/lib/libitpp.so: undefined reference to `zpotrf_' /usr/local/lib/libitpp.so: undefined reference to `zgees_' /usr/local/lib/libitpp.so: undefined reference to `dgesvd_' /usr/local/lib/libitpp.so: undefined reference to `zgeru_' /usr/local/lib/libitpp.so: undefined reference to `dsyev_' /usr/local/lib/libitpp.so: undefined reference to `zaxpy_' /usr/local/lib/libitpp.so: undefined reference to `ddot_' /usr/local/lib/libitpp.so: undefined reference to `zgesvd_' /usr/local/lib/libitpp.so: undefined reference to `zgeqp3_' /usr/local/lib/libitpp.so: undefined reference to `zcopy_' /usr/local/lib/libitpp.so: undefined reference to `dgemv_' /usr/local/lib/libitpp.so: undefined reference to `dposv_' /usr/local/lib/libitpp.so: undefined reference to `zheev_' collect2: ld returned 1 exit status make[2]: *** [tests/anytests] Error 1 make[1]: *** [tests/CMakeFiles/anytests.dir/all] Error 2

Solution: itpp was compiled using dynamic libraries, but your application did not include the -lblas and -llapack link flags.


*** Error: You must have "autoconf" installed to compile IT++ SVN sources
*** Error: You must have "automake" installed to compile IT++ SVN sources
*** Error: You must have "libtoolize" installed to compile IT++ SVN sources

Need to install the packages autoconf, automake and libtoolize. See yum/apt-get documentation.


/usr/bin/ld: /home/bickson/lapack-3.3.1/lapack_LINUX.a(dgees.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/home/bickson/lapack-3.3.1/lapack_LINUX.a: could not read symbols: Bad value
collect2: ld returned 1 exit status

It seem you forgot to follow section 2b.

TIP: It is useful to enable also itpp_debug library which is very useful when debugging your code. This is done by adding the flag --enable-debug to the configure script.


*** Error in ../../../itpp/base/algebra/ls_solve.cpp on line 271:
LAPACK library is needed to use ls_solve() function

It seems that itpp is not installed properly -it did not link to lapack.

воскресенье, 15 декабря 2013 г.

Worked solution for Kivy + Admob on android

This solution: with the few steps:

1. Edit src/org/renpy/android/PythonActivity.java (Paste your ad_unit_id and TEST_DEVICE_ID)
2. Edit AndroidManifest.xml (your comment manifest autogenerator on build.py)
3. Edit YourApp on main.py
4. Start for generate your app.

1. Edit source file on python-for-android/dist/defaults (git version of is ca369d774e276fe2e9444c6021ec2559d0527c1d):


Replace with:

package org.renpy.android;

import android.R;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.util.Log;
import android.content.pm.PackageManager;
import android.content.pm.ApplicationInfo;

import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;

// Billing
import org.renpy.android.Configuration;
import org.renpy.android.billing.BillingService.RequestPurchase;
import org.renpy.android.billing.BillingService.RestoreTransactions;
import org.renpy.android.billing.Consts.PurchaseState;
import org.renpy.android.billing.Consts.ResponseCode;
import org.renpy.android.billing.PurchaseObserver;
import org.renpy.android.billing.BillingService;
import org.renpy.android.billing.PurchaseDatabase;
import org.renpy.android.billing.Consts;
import org.renpy.android.billing.ResponseHandler;
import org.renpy.android.billing.Security;
import android.os.Handler;
import android.database.Cursor;
import java.util.List;
import java.util.ArrayList;
import android.content.SharedPreferences;
import android.content.Context;

import com.google.ads.AdView;
import com.google.ads.AdSize;
import com.google.ads.AdRequest;
import android.widget.RelativeLayout;

public class PythonActivity extends Activity implements Runnable {
    private static String TAG = "Python";

    private AdView adView;

    // The audio thread for streaming audio...
    private static AudioThread mAudioThread = null;

    // The SDLSurfaceView we contain.
    public static SDLSurfaceView mView = null;
    public static PythonActivity mActivity = null;
    public static ApplicationInfo mInfo = null;

    // Did we launch our thread?
    private boolean mLaunchedThread = false;

    private ResourceManager resourceManager;

    // The path to the directory contaning our external storage.
    private File externalStorage;

    // The path to the directory containing the game.
    private File mPath = null;

    boolean _isPaused = false;

    private static final String DB_INITIALIZED = "db_initialized";

    protected void onCreate(Bundle savedInstanceState) {

        Hardware.context = this;
        Action.context = this;
        this.mActivity = this;


        resourceManager = new ResourceManager(this);
        externalStorage = new File(Environment.getExternalStorageDirectory(), getPackageName());

        // Figure out the directory where the game is. If the game was
        // given to us via an intent, then we use the scheme-specific
        // part of that intent to determine the file to launch. We
        // also use the android.txt file to determine the orientation.
        // Otherwise, we use the public data, if we have it, or the
        // private data if we do not.
        if (getIntent() != null && getIntent().getAction() != null &&
                getIntent().getAction().equals("org.renpy.LAUNCH")) {
            mPath = new File(getIntent().getData().getSchemeSpecificPart());

            Project p = Project.scanDirectory(mPath);

            if (p != null) {
                if (p.landscape) {
                } else {

            // Let old apps know they started.
            try {
                FileWriter f = new FileWriter(new File(mPath, ".launch"));
            } catch (IOException e) {
                // pass

        } else if (resourceManager.getString("public_version") != null) {
            mPath = externalStorage;
        } else {
            mPath = getFilesDir();


        // go to fullscreen mode if requested
        try {
            this.mInfo = this.getPackageManager().getApplicationInfo(
                    this.getPackageName(), PackageManager.GET_META_DATA);
            Log.v("python", "metadata fullscreen is" + this.mInfo.metaData.get("fullscreen"));
            if ( (Integer)this.mInfo.metaData.get("fullscreen") == 1 ) {
        } catch (PackageManager.NameNotFoundException e) {

        if ( Configuration.use_billing ) {
            mBillingHandler = new Handler();

        // Start showing an SDLSurfaceView.
        mView = new SDLSurfaceView(

        Hardware.view = mView;

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

        adView = new AdView(this, AdSize.BANNER, "YOU_AD_UNIT_ID");


        RelativeLayout layout = new RelativeLayout(this);


        AdRequest adRequest = new AdRequest();

        adRequest.addTestDevice("TEST_DEVICE_ID"); // Replace with your test device id



        // Force the background window color if asked
        if ( this.mInfo.metaData.containsKey("android.background_color") ) {

     * Show an error using a toast. (Only makes sense from non-UI
     * threads.)
    public void toastError(final String msg) {

        final Activity thisActivity = this;

        runOnUiThread(new Runnable () {
            public void run() {
                Toast.makeText(thisActivity, msg, Toast.LENGTH_LONG).show();

        // Wait to show the error.
        synchronized (this) {
            try {
            } catch (InterruptedException e) {

    public void recursiveDelete(File f) {
        if (f.isDirectory()) {
            for (File r : f.listFiles()) {

     * This determines if unpacking one the zip files included in
     * the .apk is necessary. If it is, the zip file is unpacked.
    public void unpackData(final String resource, File target) {

        // The version of data in memory and on disk.
        String data_version = resourceManager.getString(resource + "_version");
        String disk_version = null;

        // If no version, no unpacking is necessary.
        if (data_version == null) {

        // Check the current disk version, if any.
        String filesDir = target.getAbsolutePath();
        String disk_version_fn = filesDir + "/" + resource + ".version";

        try {
            byte buf[] = new byte[64];
            InputStream is = new FileInputStream(disk_version_fn);
            int len = is.read(buf);
            disk_version = new String(buf, 0, len);
        } catch (Exception e) {
            disk_version = "";

        // If the disk data is out of date, extract it and write the
        // version file.
        if (! data_version.equals(disk_version)) {
            Log.v(TAG, "Extracting " + resource + " assets.");


            AssetExtract ae = new AssetExtract(this);
            if (!ae.extractTar(resource + ".mp3", target.getAbsolutePath())) {
                toastError("Could not extract " + resource + " data.");

            try {
                // Write .nomedia.
                new File(target, ".nomedia").createNewFile();

                // Write version file.
                FileOutputStream os = new FileOutputStream(disk_version_fn);
            } catch (Exception e) {
                Log.w("python", e);


    public void run() {

        unpackData("private", getFilesDir());
        unpackData("public", externalStorage);


        System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_io.so");
        System.load(getFilesDir() + "/lib/python2.7/lib-dynload/unicodedata.so");

        try {
            System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_sqlite3.so");
        } catch(UnsatisfiedLinkError e) {

        try {
            System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imaging.so");
            System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingft.so");
            System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingmath.so");
        } catch(UnsatisfiedLinkError e) {

        if ( mAudioThread == null ) {
            Log.i("python", "Starting audio thread");
            mAudioThread = new AudioThread(this);

        runOnUiThread(new Runnable () {
            public void run() {

    protected void onPause() {
        _isPaused = true;

        if (mView != null) {

    protected void onResume() {
        _isPaused = false;

        if (!mLaunchedThread) {
            mLaunchedThread = true;
            new Thread(this).start();

        if (mView != null) {

    public boolean isPaused() {
        return _isPaused;

    public boolean onKeyDown(int keyCode, final KeyEvent event) {
        //Log.i("python", "key2 " + mView + " " + mView.mStarted);
        if (mView != null && mView.mStarted && SDLSurfaceView.nativeKey(keyCode, 1, event.getUnicodeChar())) {
            return true;
        } else {
            return super.onKeyDown(keyCode, event);

    public boolean onKeyUp(int keyCode, final KeyEvent event) {
        //Log.i("python", "key up " + mView + " " + mView.mStarted);
        if (mView != null && mView.mStarted && SDLSurfaceView.nativeKey(keyCode, 0, event.getUnicodeChar())) {
            return true;
        } else {
            return super.onKeyUp(keyCode, event);

    protected void onDestroy() {

        if (adView != null) {

        if (mView != null) {
        //Log.i(TAG, "on destroy (exit1)");

    public static void start_service(String serviceTitle, String serviceDescription,
            String pythonServiceArgument) {
        Intent serviceIntent = new Intent(PythonActivity.mActivity, PythonService.class);
        String argument = PythonActivity.mActivity.getFilesDir().getAbsolutePath();
        String filesDirectory = PythonActivity.mActivity.mPath.getAbsolutePath();
        serviceIntent.putExtra("androidPrivate", argument);
        serviceIntent.putExtra("androidArgument", filesDirectory);
        serviceIntent.putExtra("pythonHome", argument);
        serviceIntent.putExtra("pythonPath", argument + ":" + filesDirectory + "/lib");
        serviceIntent.putExtra("serviceTitle", serviceTitle);
        serviceIntent.putExtra("serviceDescription", serviceDescription);
        serviceIntent.putExtra("pythonServiceArgument", pythonServiceArgument);

    public static void stop_service() {
        Intent serviceIntent = new Intent(PythonActivity.mActivity, PythonService.class);

    // Listener interface for onNewIntent

    public interface NewIntentListener {
        void onNewIntent(Intent intent);

    private List newIntentListeners = null;

    public void registerNewIntentListener(NewIntentListener listener) {
        if ( this.newIntentListeners == null )
            this.newIntentListeners = Collections.synchronizedList(new ArrayList());

    public void unregisterNewIntentListener(NewIntentListener listener) {
        if ( this.newIntentListeners == null )

    protected void onNewIntent(Intent intent) {
        if ( this.newIntentListeners == null )
        if ( this.mView != null )
        synchronized ( this.newIntentListeners ) {
            Iterator iterator = this.newIntentListeners.iterator();
            while ( iterator.hasNext() ) {

    // Listener interface for onActivityResult

    public interface ActivityResultListener {
        void onActivityResult(int requestCode, int resultCode, Intent data);

    private List activityResultListeners = null;

    public void registerActivityResultListener(ActivityResultListener listener) {
        if ( this.activityResultListeners == null )
            this.activityResultListeners = Collections.synchronizedList(new ArrayList());

    public void unregisterActivityResultListener(ActivityResultListener listener) {
        if ( this.activityResultListeners == null )

    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if ( this.activityResultListeners == null )
        if ( this.mView != null )
        synchronized ( this.activityResultListeners ) {
            Iterator iterator = this.activityResultListeners.iterator();
            while ( iterator.hasNext() )
                (iterator.next()).onActivityResult(requestCode, resultCode, intent);

    // Billing
    class PythonPurchaseObserver extends PurchaseObserver {
        public PythonPurchaseObserver(Handler handler) {
            super(PythonActivity.this, handler);

        public void onBillingSupported(boolean supported, String type) {
            if (Consts.DEBUG) {
                Log.i(TAG, "supported: " + supported);

            String sup = "1";
            if ( !supported )
                sup = "0";
            if (type == null)
                type = Consts.ITEM_TYPE_INAPP;

            // add notification for python message queue
            mActivity.mBillingQueue.add("billingSupported|" + type + "|" + sup);

            // for managed items, restore the database
            if ( type == Consts.ITEM_TYPE_INAPP && supported ) {

        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {
                "purchaseStateChange|" + itemId + "|" + purchaseState.toString());

        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {
                "requestPurchaseResponse|" + request.mProductId + "|" + responseCode.toString());

        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
            if (responseCode == ResponseCode.RESULT_OK) {
                if (Consts.DEBUG) {
                    Log.d(TAG, "completed RestoreTransactions request");
                // Update the shared preferences so that we don't perform
                // a RestoreTransactions again.
                SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putBoolean(DB_INITIALIZED, true);
            } else {
                if (Consts.DEBUG) {
                    Log.d(TAG, "RestoreTransactions error: " + responseCode);

                    "restoreTransaction|error|" + responseCode.toString());

     * If the database has not been initialized, we send a
     * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
     * for this user. This happens if the application has just been installed
     * or the user wiped data. We do not want to do this on every startup, rather, we want to do
     * only when the database needs to be initialized.
    private void restoreDatabase() {
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
        if (!initialized) {

    /** An array of product list entries for the products that can be purchased. */

    private enum Managed { MANAGED, UNMANAGED, SUBSCRIPTION }

    private PythonPurchaseObserver mPythonPurchaseObserver;
    private Handler mBillingHandler;
    private BillingService mBillingService;
    private PurchaseDatabase mPurchaseDatabase;
    private String mPayloadContents;
    public List mBillingQueue;

    public void billingServiceStart_() {
        mBillingQueue = new ArrayList();

        // Start the billing part
        mPythonPurchaseObserver = new PythonPurchaseObserver(mBillingHandler);
        mBillingService = new BillingService();
        mPurchaseDatabase = new PurchaseDatabase(this);

        if (!mBillingService.checkBillingSupported()) {
            Log.w(TAG, "NO BILLING SUPPORTED");
        if (!mBillingService.checkBillingSupported(Consts.ITEM_TYPE_SUBSCRIPTION)) {

    public void billingServiceStop_() {

    public void billingBuy_(String mSku) {
        Managed mManagedType = Managed.MANAGED;
        if (Consts.DEBUG) {
            Log.d(TAG, "buying sku: " + mSku);

        if (mManagedType == Managed.MANAGED) {
            if (!mBillingService.requestPurchase(mSku, Consts.ITEM_TYPE_INAPP, mPayloadContents)) {
        } else if (mManagedType == Managed.SUBSCRIPTION) {
            if (!mBillingService.requestPurchase(mSku, Consts.ITEM_TYPE_INAPP, mPayloadContents)) {

    public String billingGetPurchasedItems_() {
        String ownedItems = "";
        Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems();
        if (cursor == null)
            return "";

        try {
            int productIdCol = cursor.getColumnIndexOrThrow(
            int qtCol = cursor.getColumnIndexOrThrow(
            while (cursor.moveToNext()) {
                String productId = cursor.getString(productIdCol);
                String qt = cursor.getString(qtCol);

                productId = Security.unobfuscate(this, Configuration.billing_salt, productId);
                if ( productId == null )

                if ( ownedItems != "" )
                    ownedItems += "\n";
                ownedItems += productId + "," + qt;
        } finally {

        return ownedItems;

    static void billingServiceStart() {

    static void billingServiceStop() {

    static void billingBuy(String sku) {

    static String billingGetPurchasedItems() {
        return mActivity.billingGetPurchasedItems_();

    static String billingGetPendingMessage() {
        if (mActivity.mBillingQueue.isEmpty())
            return null;
        return mActivity.mBillingQueue.remove(0);


2. Your AndroidManifest.xml: (on AdActivity add android:process=":python")


3. class YourApp(App):
        def on_pause(self):
            return True

4. Generate your app for android

It bad solution, but is work.Any ideas?

четверг, 5 декабря 2013 г.

kivy: How to i get google admob android source code?

I want to create (or migrate) google admob for android to kivy project,
Please, leave url to source code of admob or admob source code file here.
It need, because i not understand mechanizm of admob for android (admob url api)

Admob is not open-source, so I don't think you will be able to get this source code.

четверг, 2 мая 2013 г.

Про то, как прикрутить купленный ssl

Расскажу, как прикрутить ssl + nginx + django с примерами.

Поэтапно - самого начала.

Покупаем дешёвый (просто для безопасности сайта - можно купить за 600 руб )

или подороже - для организации (тогда появится зелёненькая штука)

После покупки вам сразу в интерфейсе хостинга выдают private key

После небольшого ожидания - вам вышлют public ключ на почту.

Далее, настройки на сервере nginx

server {

    listen 443;

    ssl on;
    ssl_certificate /etc/ssl/SSL.crt;
    ssl_certificate_key /etc/ssl/visa.key;

    server_name visagency.ru;

    location / {


        charset  utf8;
        access_log /var/log/nginx/visa.log;


где /etc/ssl/SSL.crt - public key - собранный из двух сертификатов (почитайте на сайте поддержки сертификатов),
/etc/ssl/visa.conf - private key

релоадим nginx - должно работать норм.

sudo service nginx reload

Вот ещё конфиг на redirect на https:

server {
    listen 80;

    server_name visagency.ru;

    location / {
        rewrite ^ https://visagency.ru$request_uri? permanent;

вторник, 11 декабря 2012 г.

django request meta HTTP_COOKIE get expires - get max_age

Оказывается из браузера нельзя на сервере достать expires и max_age у cookie,

поэтому нельзя сказать в django так

import Cookie

cookie = Cookie.SimpleCookie(request.META['HTTP_COOKIE']);

cobj = cookie['some_cookie_name']['expires'] # Empty ""

и получить значение

Прийдется самостоятельно кастомизировать время сервера в другую куку.

Например, так:

cookie['set_cookie_time'] = datetime.date.today().strftime('%F')