DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    <script type="text/javascript">
var className = "PluginClass";
// get a reference to the class object itself
// (we've assumed the class is defined in a global scope)
var myclass = window[className];
// now you have a reference to the object, the new keyword will work:
var inst = new myclass();
// now call to the required method of your class
// alert(inst.validate("4111111111111111", "visa"));
</script>                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'open-uri'
require 'digest'

EMAIL_LIST = 'http://pastebin.com/raw.php?i=KdDrmNsX'
SAVE_TO = '/home/eelsaid/Desktop/gravatar/'

# read emails from source
emails = open(EMAIL_LIST).read.lines

# iterate over all emails, get the gravatar image
# and save it locally with the email as file name
# but i convert the @ character to a dot .
emails.each do | email |
  gravatar_id = Digest::MD5::hexdigest(email.strip.downcase)
  gravatar_url = "http://secure.gravatar.com/avatar/#{gravatar_id}"
  image_data = open(gravatar_url).read
  file_name = email.strip.downcase.gsub '@', '.'
  File.write "#{SAVE_TO}#{file_name}", image_data
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

require 'gtk2' # gem install gtk2

# lets define some constants we need
WORKING_HOURS = 8 # hours
WORKING_SECONDS = WORKING_HOURS * 60 * 60
ALERT = "Your working hours have been ended,\n go out and enjoy your life."

# we'll inherit the Gtk window
# and make our custom behaviour inside it
class WorkEndWindow < Gtk::Window

  # set some window properties
  # and insert a label with the desired text
  # then link the window destroy event with a
  # method to exit the application
  def initialize
    super

    self.title = ':D'
    self.border_width = 20
    self.window_position = Gtk::Window::POS_CENTER_ALWAYS

    add Gtk::Label.new ALERT
    signal_connect("destroy") { Gtk.main_quit }
    show_all
  end
end

# this will wait for you to finish work and 
# then pops up the amazing window that will
# tell you to go home ^_^ 
# it will create a window then start 
# the Gtk main loop
sleep WORKING_SECONDS
WorkEndWindow.new
Gtk.main                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
def swap_methods(from_obj, from_method, to_obj, to_method)
  
  from_alias  = "#{from_method}_#{rand 1000}"
  to_alias    = "#{to_method}_#{rand 1000}"

  # alias methods in both objects
  from_obj.class.class_eval do
    alias_method from_alias, from_method
  end

  to_obj.class.class_eval do
    alias_method to_alias, to_method
  end

  # override methods and call aliases in both direction
  from_obj.define_singleton_method(from_method) do |*params, &block|
    to_obj.send(to_alias, *params, &block)
  end

  to_obj.define_singleton_method(to_method) do |*params, &block|
    from_obj.send(from_alias, *params, &block)
  end

end

# calling swap between two methods on two objects
# should swap them, so if you call obj1.method1 
# will execute obj2.method2 and vice versa
obj1 = "this is my first string object"
obj2 = "this is my second string object"
swap_methods obj1, :to_s, obj2, :to_s

# this should print the second string
puts obj1.to_s
#  and this should print the first one
puts obj2.to_s

# swapping String new method with
# other class new method, so whenever
# you create a new String an instance of
# the other class
class X
  attr_accessor :value
  def initialize(value)
    @value = value
  end
end
swap_methods String, :new, X, :new
x_instance = String.new "Heeeey"
puts x_instance.class

# this code will output the following lines:
# 
# this is my second string object
# 
# this is my first string object
# 
# X
# 
# 
# it normally should be :
# 
# this is my frist string object
# 
# this is my second string object
# 
# String                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# 
# this script will get your followers count
# across socsial media, i get the user profile
# page and use Regex to grab the followers number
require 'open-uri'

# Getting github followers
def github( username )
  page = open("https://github.com/#{username}").read
  followers = page.scan(/<.+>([0-9]+)<.+>[[:space:]]+followers/i).flatten.first
  puts "Github : #{followers} Followers"
end

# get twitter followers by twitter handle
def twitter( username )
  page = open("https://twitter.com/#{username}").read
  followers = page.scan(/followers<.+>[[:space:]]+<.+>([0-9]+)<.+>/i).flatten.first
  puts "Twitter : #{followers} Followers"
end

# use them to print your followers
# using github username and
# twitter handle
github 'blazeeboy'
twitter 'blaz_boy'                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

require 'sinatra' # gem install sinatra

# specify port and environment as production
# to allow external access to server
set :port, 3000
set :environment, :production
# your media library path
MEDIA_PATH = '/Volumes/Data/Songs'

# get all mp3 files in my media library and sort
# then by file name
mp3s = Dir.glob("#{MEDIA_PATH}/**/*.mp3")
data = mp3s.map do |mp3|
  {
    path: mp3,
    filename: File.basename(mp3, '.mp3')
  }
end

# render the index page as set if files names
# and a player beside it, player will sent file index in data variable
# and another path will read file to stream it
get '/' do
  media_partial = data.map.with_index do |d, i| 
    '<audio src="/play/'+i.to_s+'" controls preload="none"></audio> '+
    '<a href="/play/'+i.to_s+'">'+d[:filename]+'</a>'
  end.join '</br>'
<<-EOT
<!DOCTYPE html>
<html>
  <head>
    <style>
      body{
        font: 14px Tahoma;
        line-height: 150%;
      }
    </style>
    <title>Shared Media Center</title>
  </head>
  <body>
    #{media_partial}
    <hr>
    #{data.size} Media files found.
  </body>
</html>
EOT
end

# this path will catch any url starts with "play"
# and will stream media to user, so when
# user hit the play button it'll start playing
# the mp3 file
get '/play/:id' do
  send_file data[params[:id].to_i][:path]
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# 
# autochanging wallpaper from reddit images
# you have to point the script to your existing
# file you set it as a wallpaper and it will override
# it with a new image every 5 minutes.
# 
# this script works on centos 6 with GNOME/GTK2 interface
require 'open-uri' # we'll need to download image with that
require 'ruby_reddit_api' # gem install ruby_reddit_api

# class will be initialized with
# a subreddit to monitor and a 
# destination file to write the
# downloaded image to it
class RedditWallpaper

  def initialize( subreddit, destination_file = 'bg.jpg' )
    @subreddit = subreddit
    @path = destination_file
    @downloaded = []
    @not_downloaded = []
  end

  # download the url to destination
  def download( url )
    image = open( "#{url}.jpg" ).read
    File.write  @path, image
  end

  # update wallpaper and update images cache
  def update
    # make me a reddit client please
    r = Reddit::Api.new

    # update earth
    posts = r.browse @subreddit
    posts.each do |r|
      @not_downloaded << r.url if r.url.include?('imgur') and !@downloaded.include?(r.url)
    end

    image = @not_downloaded.shift
    download image

  end

end

# i'll get images from earthporn
# they have lots of great images of
# nature places
# and then i'll update it every 5 minutes
downloader = RedditWallpaper.new 'earthPorn', '/home/eelsaid/Pictures/bg.jpg'
loop do
  downloader.update
  sleep 5*60 # wait for 5 minutes
end

                
                    //MainActivity.java

public class MainActivity extends ActionBarActivity {
  // ...

  protected static final int REQUEST_IMAGE_CAPTURE = 1;
  File tmpfile;

  public void captureImage(View view) {
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (i.resolveActivity(getPackageManager()) != null) {
    try {
      tmpfile = File.createTempFile("Photo", ".jpg",
          Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
    } catch (IOException x) {
      // We are lost :)
      throw new RuntimeException(x);
    }
    i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tmpfile));
    startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
    }
  }
  
  // ...

}

//We don't know when the camera activity will complete and our application will resume its normal operation. So we shall wait and listen to the results in background. Android provides onActivityResult method for this purpose. We shall add it to our MainActivity class as specified in Android documentation.

//MainActivity.java

public class MainActivity extends ActionBarActivity {

  // ...

  @Override
  protected void onActivityResult(int request, int result, Intent data) {
    if (request == REQUEST_IMAGE_CAPTURE && result == RESULT_OK) {
      if (tmpfile == null) {
        Log.e("onActivityResult", "Photo was not saved. Doing nothing");
        return;
      }

      new OcrTask().execute(tmpfile);
      displayTextResults("Uploading photo and recognizing text. This may take a few seconds.");
    }
  }

  // ...

}

//Here in onActivityResult we have used REQUEST_IMAGE_CAPTURE and tmpfile from captureImage. We also have used OcrTask and displayTextResults, which are our next topic.

//MainActivity.java

public class MainActivity extends ActionBarActivity {
  // ...
  public class OcrTask extends AsyncTask<File, Void, String> {
    String requestUrl;
    String appSID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    String appKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
	  // Our implementation goes here...
	}

    @Override
    protected String doInBackground(File... params) {
      // Our implementation goes here...
    }

    @Override
    protected void onPostExecute(String result) {
      super.onPostExecute(result);
      // Our implementation goes here...
    }
  }
}

//We have three methods here. onPreExecute is called before the asynchronous operation is started. It has no parameters. We perform some initial operation in here and prepare a signed request URL. A signed URL means to make sure that we are authorized to make that API call. We require appSID and appKey for this purpose which can be obtained by signing up for free at http://cloud.aspose.com/.

//OcrTask.onPreExecute

@Override
protected void onPreExecute() {
  super.onPreExecute();

  requestUrl = "https://api.aspose.com/v1.1/ocr/recognize?appSID=" + appSID;
  try {
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(new SecretKeySpec(appKey.getBytes(), "HmacSHA1"));
    mac.update(requestUrl.getBytes());
    String signature = Base64.encodeToString(mac.doFinal(), Base64.NO_PADDING);
    requestUrl += "&signature=" + signature;

    Log.i("onPreExecute", "Signed request URL: " + requestUrl);
  } catch (Exception x) {
    throw new RuntimeException(x);
  }
}

//The doInBackground will do the actual API call. We are using HttpUrlConnection as Http client. We shall upload our captured image file. The returned response is in JSON format and HTTP request method is POST. So we shall setup the connection parameters accordingly.

//OcrTask.doInBackground

@Override
protected String doInBackground(File... params) {
  File file = params[0];
  HttpURLConnection connection = null;
  try {
    FileInputStream fstream = new FileInputStream(file);
    int fsize = fstream.available();

    connection = (HttpURLConnection) new URL(requestUrl).openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Length", String.valueOf(fsize));

    OutputStream upload = connection.getOutputStream();
    byte[] buffer = new byte[10240];
    int len;
    while ((len = fstream.read(buffer)) != -1) {
      upload.write(buffer, 0, len);
    }
    upload.close();
    fstream.close();

    InputStream i = connection.getInputStream();
    String text = new Scanner(i).useDelimiter("\\A").next();
    i.close();

    //file.delete();
    Log.i("doInBackground", text);
    return text;
  } catch (FileNotFoundException fnfx) {
    InputStream e = connection.getErrorStream();
    String text = new Scanner(e).useDelimiter("\\A").next();

    Log.i("doInBackground", text);
    return text;
  } catch (Exception x) {
    throw new RuntimeException(x);
  }
}

//After we have retrieved the results from Aspose.Ocr for Cloud API, we need a little bit manipulation. As the response is JSON, should now read the recognized text and also check for error, if any. We shall do the manipulation in onPostExecute method.

//OcrTask.onPostExecute

@Override
protected void onPostExecute(String result) {
  super.onPostExecute(result);

  String text = "";
  try {
    JSONObject json = new JSONObject(result);
    if (json.has("Status") && json.getString("Status").equals("OK")) {
      text = json.getString("Text");
    } else if (json.has("Message")) {
      text = "Error: " + json.getString("Message");
    }
  } catch (JSONException x) {
    throw new RuntimeException(x);
  }

  displayTextResults(text);
}

//Now comes the simplest and yet important part of our application i.e. display the recognized text results. 

//MainActivity.java

public class MainActivity extends ActionBarActivity {
  // ...

  public void displayTextResults(String text) {
    TextView t = (TextView) findViewById(R.id.text_results);
    t.setText(text);
  }

  // ...
}
                
                    <?php
$postText = '..includes html + image tags';
 
// find first image and redo it
preg_match_all('/<img[^>]+>/i', $postText, $images);
$postThumbnail = isset($images[0][0]) ? $images[0][0] : '';
$postThumbnail = preg_replace('/(width|height|style)="*"/', '', $postThumbnail);
$postThumbnail = preg_replace('/<img/', '<img class="blog-post-thumbnail"', $postThumbnail);
 
echo $postThumbnail;
echo $postText;
?>                
                    <?php
 
// prepare reload to local version according by first visit        
session_start();            
$location_reload = isset($_SESSION["loc_reload"]) ? (bool)$_SESSION["loc_reload"] : false;
// prepare reload to local version according by first visit
if(!$location_reload){
    $location = visitor_location();
    if(in_array($location["country"], array("RU", "BY", "UA"))){
        $_SESSION["loc_reload"] = true;
        header("location: ru/index.php");
        exit;
    }else if(in_array($location["country"], array("IL"))){
        $_SESSION["loc_reload"] = true;
        header("location: he/index.php");
        exit;
    }        
}
 
function visitor_location(){
    $client  = @$_SERVER["HTTP_CLIENT_IP"];
    $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
    $remote  = @$_SERVER["REMOTE_ADDR"];
    $result  = array("country"=>"", "city"=>"");
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    $ip_data = @json_decode
(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
    if($ip_data && $ip_data->geoplugin_countryName != null){
        $result["country"] = $ip_data->geoplugin_countryCode;
        $result["city"] = $ip_data->geoplugin_city;
    }
    return $result;
}

//source: http://www.apphp.com/index.php?snippet=php-change-language-according-to-visitor-country
?>