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

Отели Испании у моря

Отели Испании у моря находятся в нескольких районах:

Валенсия
http://goo.gl/ILhlOc

Канарские острова

http://goo.gl/Op1kty

Болеарские острова

http://goo.gl/WsXWBw

Ближе к центру:

Конечно же Барселона - можно нормальный отель от 2000 руб в сутки забронировать:

http://goo.gl/7Oiknz

воскресенье, 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

FOR LAZY READERS:
Just use Amazon EC2 public image ami-c21eedab (Ubuntu)

INSTALLATION VIA YUM/APT-GET
Try to install itpp using the following command:

sudo yum install libitpp-dev

Or

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.

FOR ADVANCED USERS:


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:
# FORTRAN, OPTS, NOOPT, LOADER

c) compile

make blaslib
make

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
./autogen.sh

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


make
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:
Problem:

*** 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.

Problem:

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.

Problem:

*** 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

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

Problem:

/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

Solution:
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.

Problem:

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

Solution:
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):

src/org/renpy/android/PythonActivity.java

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";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        getWindowManager().getDefaultDisplay().getMetrics(Hardware.metrics);

        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) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }

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



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

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // 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 ) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
        } catch (PackageManager.NameNotFoundException e) {
        }

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

        // Start showing an SDLSurfaceView.
        mView = new SDLSurfaceView(
                this,
                mPath.getAbsolutePath());

        Hardware.view = mView;

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

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

        adView.setLayoutParams(lp);

        RelativeLayout layout = new RelativeLayout(this);

        layout.addView(mView);
        layout.addView(adView);

        AdRequest adRequest = new AdRequest();

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

        adView.loadAd(adRequest);

        setContentView(layout);

        // Force the background window color if asked
        if ( this.mInfo.metaData.containsKey("android.background_color") ) {
            getWindow().getDecorView().setBackgroundColor(
                this.mInfo.metaData.getInt("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 {
                this.wait(1000);
            } catch (InterruptedException e) {
            }
        }
    }

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


    /**
     * 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) {
            return;
        }

        // 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);
            is.close();
        } 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.");

            recursiveDelete(target);
            target.mkdirs();

            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);
                os.write(data_version.getBytes());
                os.close();
            } catch (Exception e) {
                Log.w("python", e);
            }
        }

    }

    public void run() {

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

        System.loadLibrary("sdl");
        System.loadLibrary("sdl_image");
        System.loadLibrary("sdl_ttf");
        System.loadLibrary("sdl_mixer");
        System.loadLibrary("python2.7");
        System.loadLibrary("application");
        System.loadLibrary("sdl_main");

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

        try {
            System.loadLibrary("sqlite3");
            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() {
                mView.start();
            }
        });
    }

    @Override
    protected void onPause() {
        _isPaused = true;
        super.onPause();

        if (mView != null) {
            mView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        _isPaused = false;

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

        if (mView != null) {
            mView.onResume();
        }
    }

    public boolean isPaused() {
        return _isPaused;
    }

    @Override
    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);
        }
    }

    @Override
    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() {
        mPurchaseDatabase.close();
        mBillingService.unbind();

        if (adView != null) {
            adView.destroy();
        }

        if (mView != null) {
            mView.onDestroy();
        }
        //Log.i(TAG, "on destroy (exit1)");
        System.exit(0);
    }

    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);
        PythonActivity.mActivity.startService(serviceIntent);
    }

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

    //----------------------------------------------------------------------------
    // 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());
        this.newIntentListeners.add(listener);
    }

    public void unregisterNewIntentListener(NewIntentListener listener) {
        if ( this.newIntentListeners == null )
            return;
        this.newIntentListeners.remove(listener);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if ( this.newIntentListeners == null )
            return;
        if ( this.mView != null )
            this.mView.onResume();
        synchronized ( this.newIntentListeners ) {
            Iterator iterator = this.newIntentListeners.iterator();
            while ( iterator.hasNext() ) {
                (iterator.next()).onNewIntent(intent);
            }
        }
    }

    //----------------------------------------------------------------------------
    // 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());
        this.activityResultListeners.add(listener);
    }

    public void unregisterActivityResultListener(ActivityResultListener listener) {
        if ( this.activityResultListeners == null )
            return;
        this.activityResultListeners.remove(listener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if ( this.activityResultListeners == null )
            return;
        if ( this.mView != null )
            this.mView.onResume();
        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);
        }

        @Override
        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 ) {
                restoreDatabase();
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {
            mActivity.mBillingQueue.add(
                "purchaseStateChange|" + itemId + "|" + purchaseState.toString());
        }

        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {
            mActivity.mBillingQueue.add(
                "requestPurchaseResponse|" + request.mProductId + "|" + responseCode.toString());
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
            if (responseCode == ResponseCode.RESULT_OK) {
                mActivity.mBillingQueue.add("restoreTransaction|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);
                edit.commit();
            } else {
                if (Consts.DEBUG) {
                    Log.d(TAG, "RestoreTransactions error: " + responseCode);
                }

                mActivity.mBillingQueue.add(
                    "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) {
            mBillingService.restoreTransactions();
        }
    }

    /** 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();
        mBillingService.setContext(this);
        mPurchaseDatabase = new PurchaseDatabase(this);

        ResponseHandler.register(mPythonPurchaseObserver);
        if (!mBillingService.checkBillingSupported()) {
            //showDialog(DIALOG_CANNOT_CONNECT_ID);
            Log.w(TAG, "NO BILLING SUPPORTED");
        }
        if (!mBillingService.checkBillingSupported(Consts.ITEM_TYPE_SUBSCRIPTION)) {
            //showDialog(DIALOG_SUBSCRIPTIONS_NOT_SUPPORTED_ID);
            Log.w(TAG, "NO SUBSCRIPTION SUPPORTED");
        }
    }

    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)) {
                Log.w(TAG, "ERROR IN BILLING REQUEST PURCHASE");
            }
        } else if (mManagedType == Managed.SUBSCRIPTION) {
            if (!mBillingService.requestPurchase(mSku, Consts.ITEM_TYPE_INAPP, mPayloadContents)) {
                Log.w(TAG, "ERROR IN BILLING REQUEST PURCHASE");
            }
        }
    }

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

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

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

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

        return ownedItems;
    }


    static void billingServiceStart() {
        mActivity.billingServiceStart_();
    }

    static void billingServiceStop() {
        mActivity.billingServiceStop_();
    }

    static void billingBuy(String sku) {
        mActivity.billingBuy_(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")

https://docs.google.com/document/d/1Cr7ixoGoIxa5RDBllDotZcwzlGiH7ko5c8IahJdoL_A/edit?usp=sharing

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)

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

суббота, 9 ноября 2013 г.

8 ядер и 1 Гб оперативки + 50 Гб места на жёстком за 600 руб в месяц

Ура, linode проапгрейдил железо на серверах

Теперь минимальный план а 600 руб будет с таким железом:
  • Процессор - 8 ядер (8-ядерный процессор)
  •  1 Гб оперативной памяти (оперативки)
  • 50 Гб места на жестком диске
+ качественная поддержка (отвечают в теч. 10 мин.). Один минус - на англ.

+ удобный интерфейс, который на моём веку не отваливался.

+ обещают в скором времени поставить ssd диски, да и апгрейдятся они довольно часто - 1 раз в полгода-год.


Ссылка на хостинг: http://goo.gl/3VrDq2

вторник, 28 мая 2013 г.

ТЗ на написание текста для страниц типа "Виза в страну"


Шаблон страницы «Виза в страну»

Для каждой страны из «Приложения 1» нужно сделать страницу «Виза в страну»
(Например, для Болгарии - «Виза в Болгарию»)

На каждой такой странице будут присутствовать блоки текста.

1. Вступительный блок текста — два обзаца минимум, которые будут описывать про что будет речь идти ниже (500 симв.)
2. Для каждой страны существует список стандартных вопросов, которые задаёт получающий визу в соотв. страну. Для каждого такого вопроса (Соответствие страны и вопроса приведено в «приложении 2») нужен свой блок текста ~ 500 симв, отвечающий на вопрос.

Требования к тексту:
Это будут не просто seo-тексты (даже в меньшей степени они нужны), а нужны настоящие советы и ответы на вопросы для выезжающего.
Картинки и файлы мы приложим сами (заявление, фото и т. п.)

Совет 1.: Если человека интересует адрес посольства, то нужно описать и вывести список адресов, городов в России, где они находятся, адреса сайтов и email.
Совет 2: Вопросы, где присутствуют цены (несколько), то можно сделать в виде таблички. Также приводить цены в самом посольстве и в агентствах (среднюю цену).
Совет 3: Вопросы про фото — нужно написать требования к фото.
Совет 4. Сроки изготовления визы должны быть консульскими сроками.


Сейчас нужно сделать для 20 стран в порядке приоритета, потом потребуется ещё 20.

Тз составлено для сайта visagency.ru
Ключевые слова на визу. Например, Виза в Болгарию, Виза в Китай

Страны, для которых необходимо написать текст про визу.