Rectangle 27 2

android downloading multiple files one by one using asynctask?


package com.example.androidhive;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidDownloadFileByProgressBarActivity extends Activity {

    // button to show progress dialog
    Button btnShowProgress;

    // Progress Dialog
    private ProgressDialog pDialog;
    ImageView my_image;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;

    // File url to download
    String[] ur = {
            "http://www.funrocker.com/blog/wp-content/uploads/2010/04/Animals-Wild-Life-Jungle-FunRocker.Com-03.jpg",
            "http://2.bp.blogspot.com/-j56yaqpfjVE/TnzTjcqnCjI/AAAAAAAAGPM/MzqmczFkC30/s1600/natural-pictures.jpg",
            "http://www.fantasy-and-art.com/wp-content/gallery/nature-wallpapers/red-tree-wallpaper-hd.jpg" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(ur);
            }
        });
    }

    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type:
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {

                for (int i = 0; i < f_url.length; i++) {
                    URL url = new URL(f_url[i]);
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    // getting file length
                    int lenghtOfFile = conection.getContentLength();

                    // input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(
                            url.openStream(), 8192);
                    System.out.println("Data::" + f_url[i]);
                    // Output stream to write file
                    OutputStream output = new FileOutputStream(
                            "/sdcard/downloaded" + i + ".jpg");

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress(""
                                + (int) ((total * 100) / lenghtOfFile));

                        // writing data to file
                        output.write(data, 0, count);
                    }

                    // flushing output
                    output.flush();

                    // closing streams
                    output.close();
                    input.close();
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory()
                    .toString() + "/downloaded.jpg";
            // setting downloaded into image view
            // my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }
}
Note
Rectangle 27 1

if else conditions in mysql query php?


SELECT *
FROM user
where usertype =1 group by jobid
union
SELECT *
FROM user
where usertype =2 group by experienceId

You can try like this..

Note
Rectangle 27 2

excel vba: adding distinct values in a range to a new range?


Dim dic As Dictionary
Set dic = New Dictionary
Dim srcRng As Range
Dim lastRow As Integer

Dim ws As Worksheet
Set ws = Sheets("Sheet1")

lastRow = ws.Cells(1, 1).End(xlDown).Row
Set srcRng = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, 1))

Dim cell As Range

For Each cell In srcRng
    If Not dic.Exists(cell.Value) Then
        dic.Add cell.Value, cell.Value   'key, value
    End If
Next cell

Set ws = Sheets("Sheet2")    

Dim destRow As Integer
destRow = 1
Dim entry As Variant

'the Transpose function is essential otherwise the first key is repeated in the vertically oriented range
ws.Range(ws.Cells(destRow, 1), ws.Cells(dic.Count, 1)) = Application.Transpose(dic.Items)

I really like the dictionary object in VBA. It's not natively available but it's very capable. You need to add a reference to Microsoft Scripting Runtime then you can do something like this:

You can transpose the array of dictionary keys to the range in one step using dic.keys. Try it out :)

Note
Rectangle 27 2

encoding url parameter in ruby, and correctly decoding it with php?


CGI::escape
url_encoded_string = CGI::escape("'Stop!' said Fred")
   # => "%27Stop%21%27+said+Fred"
Note
Rectangle 27 1

how to mock localstorage in javascript unit tests?


beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(localStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});

you could do this with sinon as well. The key is why bother tying to mock the entire localStorage object, just mock the methods (getItem and/or setItem) you are interested in.

If you want to mock the local storage in all your tests, declare the beforeEach() function shown above in the global scope of your tests (the usual place is a specHelper.js script).

Note local storage unittest JavaScript
Rectangle 27 1

java api to convert jpeg to tiff?


The javax.imageio package has built-in writers for most of the popular image types, including jpg and tiff. Here's Sun's page on imageio.

javax.imageio does not support TIF.

Note
Rectangle 27 2

java javafx tabpane change one tab, update the others?


The easiest way would be to hold the categories in an ObservableList at some top level (say in your Application sub class) and have all the tables share a reference to that list (table.setItems(yourList)). Whenever a change is made in the categories tab, the other tabs will automatically reflect the change.

Note
Rectangle 27 2

Nginx rate limiting simplyfied


Config in nginx. conf > html section

html{
geo $limit {
default 1;
10.0.0.0/8 0;
192.168.0.0/24 0;
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=req_zone:10m rate=10r/s;
server {
location / {
limit_req zone=req_zone burst=20 nodelay;
limit_req_log_level warn;
limit_req_status 444;
# ...
}
} }

Installation of Siege on AMI/Centos.

sudo yum-config-manager --enable epel
sudo yum install siege
siege -b -r 1 -c25 http://localhost/parentune-framework/public/

Download and Configure Siege on Ubuntu:

sudo apt-get update && sudo apt-get upgrade --show-upgraded
wget http://download.joedog.org/siege/siege-latest.tar.gz
tar -zxvf siege-latest.tar.gz
cd siege-*/
sudo apt-get install build-essential
./configure
make
sudo make install
siege.config
Article nginx rate limiting siege
Rectangle 27 1

Log with morgan in Express


To use the new HTTP logger (called morgan) from Express 4.0 you need to install:

npm install morgan

And import it:

var morgan = require('morgan');

When creating a new morgan logger middleware a format must be specified, followed by desired options (which are optional) :

app.use(morgan('tiny'));

The format can be a string or a function that will produce a log entry (tokens are of help here). Predefined names include dev, combined, short etc.

Options worth mentioning are:

  • immediate that will write log lines on request instead of response (requests will be logged even when server has crashed)
  • skip that determines when logging should be skipped.

To only log error responses:

morgan('combined', { skip: function (req, res) { return res.statusCode < 400 } });

Custom tokens can be also defined using morgan.token function.

Note express logging Node.js
Rectangle 27 1

Easy way to deliver HTML pages with Express


Displaying basic HTML pages can be achieved in many ways using Node's core API, yet the easiest way is by using the Express framework.

The serve-static module will be used to deliver the page:

var express = require('express'); var serveStatic = require('serve-static'); var app = express();

Display index.html:

app.use(serveStatic('public/',{'index': ['index.html', `index.htm`]})); app.listen(3000);

Multiple roots:

app.use(serveStatic(__dirname+ '/first')); app.use(serveStatic(__dirname+ '/second'));

Files will be firstly looked for in /first then in /second as a fallback.

Note express Node.js HTML