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

                    This macro produces, from a Word document, Powerpoint slides, provided you follow a few simple rules:
- The document must be entitled,
- levels 1 and 2 produce a slide,
- level 3 produce a bulletted text box,
- paraghraph with name starting by pptInsert are inserted in slide above title,
- word fragment bookmarked (These may be images, text or tables) are inserted in slide.
The presentation is created in the same directory of the Word document and whit the same name. 
Sub genPowerPoint()
' aStruct: level,start paragraphe, end paragraph
' for level 1 and 2
Dim aStruct(200) As String
nEl = 0
sep = ","   ' Chr$(255)
maxLevel = 3    ' max level listed in slide text box
titleLevel = 2  ' max level in titles
iParCount = ActiveDocument.Paragraphs.Count
For i = 1 To iParCount
    Style = ActiveDocument.Paragraphs(i).Range.Style
    If Left(Style, 6) = "Titolo" Or Left(Style, 7) = "Heading" Then
        Level = ActiveDocument.Paragraphs(i).Range.ListFormat.ListLevelNumber
        If Level <= titleLevel Then
            nEl = nEl + 1
            txt = ActiveDocument.Paragraphs(i).Range.FormattedText
            aStruct(nEl) = Level & sep & i
            If nEl > 1 Then aStruct(nEl - 1) = aStruct(nEl - 1) & "," & i - 1
        End If
    End If
Next
aStruct(nEl) = aStruct(nEl) & "," & i - 1
sFile = Application.ActiveDocument
sFile = Application.ActiveDocument.Path & "\" & Left(sFile, Len(sFile) - 4) & ".ppt"
Set oPA = CreateObject("PowerPoint.Application")
oPA.Visible = True
ppLayoutTitle = 1
ppLayoutText = 2
ppLayoutTextAndObject = 13
ppLayoutObject = 16
ppLayoutTitleOnly = 11
ppAutoSizeShapeToFitText = 1
Set oRg = ActiveDocument.Range
Set oPP = oPA.Presentations.Add(msoTrue)
With oPP.PageSetup
    hSlide = .SlideHeight
    wSlide = .SlideWidth
End With
For J = 1 To nEl
    aData = Split(aStruct(J), ",")
    aRes = searchData(aData, maxLevel)
    intSlides = 0   ' to find layout type
    If aRes(0) <> "" Then intSlides = intSlides + 1
    If aRes(1) <> "" Then intSlides = intSlides + 2
    If aRes(2) > 0 Then intSlides = intSlides + 4
    oPP.Slides.Add oPP.Slides.Count + 1, ppLayoutTitleOnly
    Set oPS = oPP.Slides(oPP.Slides.Count)
    hNewTextbox = oPS.Shapes("Rectangle 2").Top + oPS.Shapes("Rectangle 2").Height '   follow text boxes
    oPS.Shapes("Rectangle 2").TextFrame.TextRange.Text = removeLastByte(ActiveDocument.Paragraphs(aData(1)).Range.FormattedText)
    If (aRes(1) <> "") Then
        Set oShape = oPS.Shapes.AddTextbox(msoTextOrientationHorizontal, 50#, hNewTextbox + 10, wSlide - 100, 100)
        Set shapetext = oShape.TextFrame.TextRange
        shapetext.Text = removeLastByte(aRes(1))
        shapetext.Font.Name = aRes(3)
        oShape.TextFrame.AutoSize = ppAutoSizeShapeToFitText
        hNewTextbox = oShape.Top + oShape.Height
    End If
    If aRes(0) <> "" Then
        wtextBox = IIf(aRes(2) > 0, (wSlide - 100) / 2, wSlide - 100)
        Set oShape = oPS.Shapes.AddTextbox(msoTextOrientationHorizontal, 50#, hNewTextbox + 10, wtextBox, 100)
        Set shapetext = oShape.TextFrame.TextRange
        shapetext.Text = removeLastByte(aRes(0))
        shapetext.ParagraphFormat.Bullet.Visible = msoTrue
        ' this is not working
        oShape.TextFrame.AutoSize = True    'ppAutoSizeShapeToFitText
    End If
    If aRes(2) > 0 Then
        nTextBoxAfter = oPP.Slides(oPP.Slides.Count).Shapes.Count
        Set oBookMark = ActiveDocument.Paragraphs(aRes(2)).Range.Bookmarks(1)
        oBookMark.Select
        oBookMark.Range.CopyAsPicture
        oPP.Slides(oPP.Slides.Count).Shapes.Paste
        nTextBox = oPP.Slides(oPP.Slides.Count).Shapes.Count
        For i = nTextBoxAfter + 1 To nTextBox
            With oPP.Slides(oPP.Slides.Count).Shapes(i)
                .Top = hNewTextbox + 10
                .Left = IIf(aRes(0) = "", 50, 50 + (wSlide - 100) / 2)
                .Width = IIf(aRes(0) = "", wSlide - 100, (wSlide - 100) / 2)
            End With
        Next
    End If
Next
oPP.SaveAs sFile
oPP.Close
oPA.Quit
End Sub
Public Function searchData(aEl, maxLevel)   ' search sub levels, pptInsert text and table
Dim aRet(4)
aRet(0) = "" ' list of headings
aRet(1) = "" ' list of pptInsert
aRet(2) = 0 ' paragraph with table
aRet(3) = "" ' Font type of pptInsert
For J = aEl(1) + 1 To aEl(2)
    Style = ActiveDocument.Paragraphs(J).Range.Style    ' ActiveDocument.Paragraphs(i).Range.ListFormat.ListLevelNumber
    If (Left(Style, 6) = "Titolo" Or Left(Style, 7) = "Heading") _
        And ActiveDocument.Paragraphs(J).Range.ListFormat.ListLevelNumber <= maxLevel Then
        aRet(0) = aRet(0) & " " & removeLastByte(ActiveDocument.Paragraphs(J).Range.FormattedText) & Chr(13)
    End If
    If Left(Style, 9) = "pptInsert" Then
        aRet(1) = aRet(1) & removeLastByte(ActiveDocument.Paragraphs(J).Range.FormattedText) & Chr(13)
        aRet(3) = ActiveDocument.Paragraphs(J).Range.FormattedText.Font.Name
    End If
    If ActiveDocument.Paragraphs(J).Range.Bookmarks.Count > 0 Then aRet(2) = J ' paragraph with table
Next
searchData = aRet
End Function
Public Function removeLastByte(txt)
If Len(txt) > 1 Then
    removeLastByte = Left(txt, Len(txt) - 1)
Else
    removeLastByte = ""
End If
End Function
                
                    // This class can be used to generate SQL.
Usage:
Query q = Query.Instance().Select("Associates.AID", "Associates.City", "Associates.Country", "Associates.Created_By", "Entities.Name")
                            .From("Associates", "Entities")
                            .Where("Associates.AID", Operator.Equals, "Entities.AID")
                            .And("Associates.AID", Operator.Equals, "12345")
                            .GroupBy("Associates.AID", "Entities.EID");
public class Query
    {
        private StringBuilder _sql = new StringBuilder(1024);
        private string[] _selectParams;
        private string[] _tableParams;
        private string[] _groupByParams;
        private List<string> _filterParams = new List<string>();

        public Query Select(params string[] selectParams)
        {
            _selectParams = selectParams;
            return this;
        }

        public static Query Instance()
        {
            return new Query();
        }

        public Query Where(string key, Operator op, string value)
        {
            _filterParams.Add(string.Format("{0} {1} {2}", key, GetOperator(op), value));
            return this;
        }

        public Query From(params string[] tableParams)
        {
            _tableParams = tableParams;
            return this;
        }

        private string GetOperator(Operator op)
        {
            switch (op)
            {
                case Operator.Equals: return "=";
                case Operator.GreaterThan: return ">";
                case Operator.GreaterThanEqualTo: return ">=";
                case Operator.LessThan: return "<";
                case Operator.LessThanEqualTo: return "<=";
                default: return "";
            }
        }

        public Query And(string key, Operator op, string value)
        {
            _filterParams.Add(string.Format("{0} {1} {2}", key, GetOperator(op), value));
            return this;
        }

        public Query GroupBy(params string[] groupByParams)
        {
            _groupByParams = groupByParams;
            return this;
        }

        public string ToSql()
        {
            _sql.Append(string.Format(" SELECT {0}", string.Join(", ", _selectParams)));
            _sql.Append("\r\n");
            _sql.Append(" FROM " + string.Join(", ", _tableParams));
            _sql.Append("\r\n");
            _sql.Append(" WHERE ");
            _sql.Append(string.Join(" AND ", _filterParams.ToArray()));
            _sql.Append("\r\n");
            _sql.Append(" GROUP BY " + string.Join(", ", _groupByParams));
            return _sql.ToString();
        }
    }

public enum Operator
    {
        Equals,
        LessThan,
        LessThanEqualTo,
        GreaterThan,
        GreaterThanEqualTo
    }
                
                    // AWS inventory to relational database


#!/bin/sh

db_name="aws_inventory"
mysql -e"drop database $db_name"
mysql -e"create database $db_name"

grep -w ^INSTANCE /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/instance_list.txt
grep -w ^TAG /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/instance_tag.txt
grep -w ^VOLUME /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/volume_list.txt
grep -w ^ATTACHMENT /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/volume_attachment.txt
grep -w ^IMAGE /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/image_list.txt
grep -w ^BLOCKDEVICE /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/blockdevice.txt
grep -w ^SNAPSHOT /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/snapshot_list.txt
grep -w ^AVAILABILITYZONE /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/zone_list.txt
grep -w ^ADDRESS /home/vserv/ec2_audit.txt > /var/lib/mysql/$db_name/address_list.txt


mysql $db_name << "my_heredoc"
set foreign_key_checks=0;

create table volume_attachment (
volume_name varchar(100),
volume_id varchar(100),
volume_instance varchar(100),
volume_mount varchar(100),
volume_status varchar(100),
volume_date varchar(100),
primary key (volume_id, volume_instance),
key (volume_instance),
constraint volume_attach_id foreign key (volume_id) references volume_list(volume_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE instance_list (
  instance_name varchar(100) DEFAULT NULL,
  instance_id varchar(100) DEFAULT NULL,
  image_id varchar(100) DEFAULT NULL,
  instance_ip varchar(100) DEFAULT NULL,
  instance_private_zone varchar(100) DEFAULT NULL,
  instance_status varchar(100) DEFAULT NULL,
  instance_keypair varchar(100) DEFAULT NULL,
  filler1 varchar(100) DEFAULT NULL,
  filler2 varchar(100) DEFAULT NULL,
  instance_type varchar(100) DEFAULT NULL,
  instance_date varchar(100) DEFAULT NULL,
  instance_zone varchar(100) DEFAULT NULL,
  instance_kernel varchar(100) DEFAULT NULL,
  instance_r varchar(100) DEFAULT NULL,
  filler3 varchar(100) DEFAULT NULL,
  instance_monitoring varchar(100) DEFAULT NULL,
  instance_ip_public varchar(100) DEFAULT NULL,
  instance_private varchar(100) DEFAULT NULL,
  filler4 varchar(100) DEFAULT NULL,
  filler5 varchar(100) DEFAULT NULL,
  instance_ebs varchar(100) DEFAULT NULL,
  instance_spot varchar(100) DEFAULT NULL,
  instance_code varchar(100) DEFAULT NULL,
  filer6 varchar(100) DEFAULT NULL,
  filler7 varchar(100) DEFAULT NULL,
  filler8 varchar(100) DEFAULT NULL,
  instance_details varchar(100) DEFAULT NULL,
  primary key (instance_id),
  key (instance_zone),
  key(image_id),
constraint volume_attachment_instance foreign key (instance_id) references volume_attachment (volume_instance),
constraint image_list_id foreign key (image_id) references image_list(image_id),
constraint zone_list foreign key (instance_zone) references zone_list(zone_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE instance_tag (
  tag_name varchar(100) DEFAULT NULL,
  tag_type varchar(100) DEFAULT NULL,
  tag_instance varchar(100) DEFAULT NULL,
  tag_status varchar(100) DEFAULT NULL,
  tag_details varchar(100) DEFAULT NULL,
  key (tag_instance),
constraint instance_tag_name foreign key (tag_instance) references instance_list(instance_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


create table snapshot_list (
snap_name varchar(100), 
snap_id varchar(100), 
snap_vol varchar(100), 
snap_status varchar(100), 
snap_date varchar(100), 
snap_percent varchar(100), 
snap_owner varchar(100), 
snap_filler varchar(100), 
snap_created varchar(100),
primary key (snap_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


create table volume_list (
volume_name varchar(100),
volume_id varchar(100),
volume_filler varchar(100),
volume_snap varchar(100),
volume_zone varchar(100),
volume_status varchar(100),
volume_date varchar(100),
primary key (volume_id), 
key (volume_zone),
key (volume_snap),
constraint volume_list_id foreign key (volume_zone) references instance_list(instance_zone),
constraint volume_list_snap foreign key (volume_snap) references snapshot_list(snap_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 

create table image_list (
image_name varchar(100), 
image_id varchar(100), 
image_details varchar(100), 
image_owner varchar(100), 
image_status varchar(100), 
image_private varchar(100), 
image_filler varchar(100),
image_bit varchar(100), 
image_machine varchar(100),
image_kernel varchar(100), 
image_filler1 varchar(100),
image_filler2 varchar(100),
image_ebs varchar(100), 
image_paravirtual varchar(100) ,
primary key(image_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


create table blockdevice (
block_name varchar(100), 
block_mount varchar(100), 
block_id varchar(100), 
block_filler varchar(100) ,
primary key(block_id),
constraint blockdevice_id foreign key (block_id) references volume_attachment(volume_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE zone_list (
  filler varchar(100) DEFAULT NULL,
  zone_id varchar(100) DEFAULT NULL,
  filler1 varchar(100) DEFAULT NULL,
  region varchar(100) DEFAULT NULL,
  primary key (zone_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE address_list (
  filler varchar(100) DEFAULT NULL,
  public_ip varchar(100) DEFAULT NULL,
  instance_id varchar(100) DEFAULT NULL,
  primary key (public_ip), 
  key (instance_id),
constraint address_list_instance_id foreign key (instance_id) references instance_list(instance_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


load data infile 'instance_list.txt' into table instance_list fields terminated by '\t';
load data infile 'instance_tag.txt' into table instance_tag fields terminated by '\t';
load data infile 'volume_list.txt' into table volume_list fields terminated by '\t';
load data infile 'volume_attachment.txt' into table volume_attachment fields terminated by '\t';
load data infile 'image_list.txt' into table image_list fields terminated by '\t';
load data infile 'blockdevice.txt' into table blockdevice fields terminated by '\t';
load data infile 'snapshot_list.txt' into table snapshot_list fields terminated by '\t';
load data infile 'zone_list.txt' into table zone_list fields terminated by '\t';
load data infile 'address_list.txt' into table address_list fields terminated by '\t';

my_heredoc


                
                    
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
 <property name="dataSource" ref="dataSource" />
 <property name="transactionManager" ref="jobTransactionManager" />
 <property name="isolationLevelForCreate" value="ISOLATION_READ_COMMITTED" />
 <property name="lobHandler">
  <bean class="org.springframework.jdbc.support.lob.OracleLobHandler">
   <property name="nativeJdbcExtractor">
    <bean class="org.springframework.jdbc.support.nativejdbc.JBossNativeJdbcExtractor"/>
   </property>
  </bean>
 </property>
</bean>
                
                    // Iterate two arrays simultaneously in Ruby

array1.zip(array2).each do |v1, v2|
  # iterates over array1 and array2
end
                
                    At the beginnig of spec/spec_helper.rb:
require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
  add_filter '/config/'
  add_filter '/lib/'
  add_filter '/vendor/'

  add_group 'Controllers', 'app/controllers'
  add_group 'Models', 'app/models'
  add_group 'Helpers', 'app/helpers'
  add_group 'Mailers', 'app/mailers'
  add_group 'Views', 'app/views'
end if ENV["COVERAGE"]

And add rake task spec:coverage to lib/tasks/coverage.rake:
namespace :spec do
  desc "Create rspec coverage"
  task :coverage do
    ENV['COVERAGE'] = 'true'
    Rake::Task["spec"].execute
  end
end
                
                    
// ==UserScript==
// @name          get rid of amg crap
// @namespace     polestar
// @include       *allmusic.com*

// ==/UserScript==

(function()
{
    inner = 'AMG blocker';
    amgCrap = document.getElementById( 'adverttop' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'header' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'NR' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right-sidebar' );
    amgCrap.innerHTML = inner;
})();
                
                    
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
                
                    If you want to arrange Firefox tabs in multiple rows.
add the following code to your userChrome.css.

.tabbrowser-tabs > hbox {
  display: block !important;
}

.tabbrowser-tabs tab {
  -moz-appearance: none !important;
  display: inline !important;
  width: 16% !important;
  min-width: 16% !important;
  max-width: 16% !important;
}
                
                    Here's a little shell snippet for finding and replacing text in multiple files:

for fl in *.txt; do
mv $fl $fl.old
sed 's/find/replace/g' $fl.old > $fl
done