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

                    require 'socket'
require 'base64'

Refresh = 1 # seconds to refresh image on server
screen_capture_command = 'screencapture -C -x tmp.png'
image = ''
latest = Time.now
server = TCPServer.new 3000

loop do
  Thread.start(server.accept) do |client|
	if Time.now-latest>=Refresh
		system(screen_capture_command)
		latest = Time.now
		File.open('tmp.png', 'rb') do |file| 
			image = 'data:image/png;base64,'+Base64.encode64(file.read) 
		end
	end
  	client.puts '<html><head>'+
				"<script>setTimeout(function(){document.location.reload();},#{Refresh*1000});</script>"+
				'</head><body style="padding:0px;margin:0px;">'+
				"<img src=\"#{image}\" style=\"height:100%;\"/>"+
				'</body></html>'
    client.close
  end
end                
                    class Integer
	def to_a
		arr = []
		tmp = self
		while tmp>0
			arr << tmp%10
			tmp /= 10
		end
		arr.reverse
	end
end

# usage
print 32455.to_a
print 433456.to_a
print 345434.to_a.sort
print 344543.to_a.join '-'                
                    class Array
	def same?
		uniq.length==1
	end
end

x = 1
y = 2
z = 2
l = 2

# old way : x==y and y==z
puts [x,y,z].same? # false
# old way : y==z and z==l
puts [y,z,l].same? # true
                
                    require 'webrick'
 
Port = 3000
Directory = Dir::pwd

WEBrick::HTTPServer.new(
	Port: Port,
	DocumentRoot: Directory
).start                
                    require 'open-uri'
require 'json'
require 'psych'

city = 'portsaid,egypt'
request = "http://api.openweathermap.org/data/2.5/weather?q=#{city}"
response = open(request).readlines.join
print Psych.dump( JSON.parse(response) )                
                    //The following example shows how to convert a chart to render an image file.
//Create a new Workbook.
Workbook workbook = new Workbook();

//Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);

//Set the name of worksheet
sheet.setName("Data");

//Get the cells collection in the sheet.
Cells cells = workbook.getWorksheets().get(0).getCells();

//Put some values into a cells of the Data sheet.
cells.get("A1").setValue("Region");
cells.get("A2").setValue("France");
cells.get("A3").setValue("Germany");
cells.get("A4").setValue("England");
cells.get("A5").setValue("Sweden");
cells.get("A6").setValue("Italy");
cells.get("A7").setValue("Spain");
cells.get("A8").setValue("Portugal");
cells.get("B1").setValue("Sale");
cells.get("B2").setValue(70000);
cells.get("B3").setValue(55000);
cells.get("B4").setValue(30000);
cells.get("B5").setValue(40000);
cells.get("B6").setValue(35000);
cells.get("B7").setValue(32000);
cells.get("B8").setValue(10000);

//Create chart
int chartIndex = sheet.getCharts().add(ChartType.COLUMN, 12, 1, 33, 12);
Chart chart = sheet.getCharts().get(chartIndex);

//Set properties of chart title
chart.getTitle().setText("Sales By Region");
chart.getTitle().getTextFont().setBold(true);
chart.getTitle().getTextFont().setSize(12);

//Set properties of nseries
chart.getNSeries().add("Data!B2:B8", true);
chart.getNSeries().setCategoryData("Data!A2:A8");

//Set the fill colors for the series's data points (France - Portugal(7 points))
ChartPointCollection chartPoints = chart.getNSeries().get(0).getPoints();

ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());

point = chartPoints.get(1);
point.getArea().setForegroundColor(Color.getBlue());

point = chartPoints.get(2);
point.getArea().setForegroundColor(Color.getYellow());

point = chartPoints.get(3);
point.getArea().setForegroundColor(Color.getRed());

point = chartPoints.get(4);
point.getArea().setForegroundColor(Color.getBlack());

point = chartPoints.get(5);
point.getArea().setForegroundColor(Color.getGreen());

point = chartPoints.get(6);
point.getArea().setForegroundColor(Color.getMaroon());

//Set the legend invisible
chart.setShowLegend(false);

//Get the Chart image
ImageOrPrintOptions imgOpts = new ImageOrPrintOptions();
imgOpts.setImageFormat(ImageFormat.getPng());

//Save the chart image file.
chart.toImage(new FileOutputStream("D:\\Files\\MyChartImage.png"), imgOpts);
                
                    //Setting the AutoFormat and PivotTableStyle Type

//Setting the PivotTable report is automatically formatted for Excel 2003 formats
pivotTable.setAutoFormat(true);
//Setting the PivotTable atuoformat type.
pivotTable.setAutoFormatType(PivotTableAutoFormatType.CLASSIC);

//Setting the PivotTable's Styles for Excel 2007/2010 formats e.g XLSX.
pivotTable.setPivotTableStyleType(PivotTableStyleType.PIVOT_TABLE_STYLE_LIGHT_1);

//Setting Format Options

//The code sample that follows illustrates how to set a number of pivot table formatting options, including adding grand totals for rows and columns.

//Dragging the third field to the data area.
 pivotTable.addFieldToArea(PivotFieldType.DATA,2);

//Show grand totals for rows.
 pivotTable.setRowGrand(true);

//Show grand totals for columns.
pivotTable.setColumnGrand(true);

//Display a custom string in cells that contain null values.
pivotTable.setDisplayNullString(true);
pivotTable.setNullString("null");

//Setting the layout
pivotTable.setPageFieldOrder(PrintOrderType.DOWN_THEN_OVER);

//Setting Row, Column, and Page Fields Format

//The code example that follows shows how to access row fields, access a particular row, set subtotals, apply automatic sorting, and using the autoShow option.

//Accessing the row fields.
PivotFieldCollection pivotFields = pivotTable.getRowFields();

//Accessing the first row field in the row fields.
PivotField pivotField = pivotFields.get(0);

//Setting Subtotals.
pivotField.setSubtotals(PivotFieldSubtotalType.SUM,true);
pivotField.setSubtotals(PivotFieldSubtotalType.COUNT,true);

//Setting autosort options.
//Setting the field auto sort.
pivotField.setAutoSort(true);

//Setting the field auto sort ascend.
pivotField.setAscendSort(true);

//Setting the field auto sort using the field itself.
pivotField.setAutoSortField(-1);

//Setting autoShow options.
//Setting the field auto show.
pivotField.setAutoShow(true);

//Setting the field auto show ascend.
pivotField.setAscendShow(false);

//Setting the auto show using field(data field).
pivotField.setAutoShowField(0);

//The following lines of code illustrate how to format data fields.

//Accessing the data fields.
PivotFieldCollection pivotFields = pivotTable.getDataFields();

//Accessing the first data field in the data fields.
PivotField pivotField = pivotFields.get(0);

//Setting data display format
pivotField.setDataDisplayFormat(PivotFieldDataDisplayFormat.PERCENTAGE_OF);

//Setting the base field.
pivotField.setBaseField(1);

//Setting the base item.
pivotField.setBaseItem(PivotItemPosition.NEXT);

//Setting number format
pivotField.setNumber(10);

//Modify a Pivot Table Quick Style

//The code examples that follow show how to modify the quick style applied to a pivot table.

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Open the template file containing the pivot table.
Workbook wb = new Workbook(sdPath + "/Template.xlsx");

//Add pivot table style
Style style1 = wb.createStyle();
com.aspose.cells.Font font1 = style1.getFont();
font1.setColor(Color.getRed());
Style style2 = wb.createStyle();
com.aspose.cells.Font font2 = style2.getFont();
font2.setColor( Color.getBlue());
int i = wb.getWorksheets().getTableStyles().addPivotTableStyle("tt");

//Get and Set the table style for different categories
TableStyle ts = wb.getWorksheets().getTableStyles().get(i);
int index = ts.getTableStyleElements().add(TableStyleElementType.FIRST_COLUMN);
TableStyleElement e = ts.getTableStyleElements().get(index);
e.setElementStyle(style1);
index = ts.getTableStyleElements().add(TableStyleElementType.GRAND_TOTAL_ROW);
e = ts.getTableStyleElements().get(index);
e.setElementStyle(style2);

//Set Pivot Table style name
PivotTable pt = wb.getWorksheets().get(0).getPivotTables().get(0);
pt.setPivotTableStyleName ("tt");

//Save the file.
wb.save(sdPath + "/OutputFile.xlsx");

//Clearing PivotFields

//PivotFieldCollection has a method named clear() for the task. When you want to clear all the PivotFields in the areas e.g., page, column, row or data, you can use it.
The code sample below shows how to clear all the PivotFields in data area.

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Open the template file containing the pivot table.
Workbook workbook = new Workbook(sdPath + "/PivotTable.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Get the pivot tables in the sheet
PivotTableCollection pivotTables = sheet.getPivotTables();

//Get the first PivotTable
PivotTable pivotTable = pivotTables.get(0);

//Clear all the data fields
pivotTable.getDataFields().clear();

//Add new data field
pivotTable.addFieldToArea(PivotFieldType.DATA, "Betrag Netto FW");

//Set the refresh data flag on
pivotTable.setRefreshDataFlag(false);

//Refresh and calculate the pivot table data
pivotTable.refreshData();
pivotTable.calculateData();

//Save the Excel file
workbook.save(sdPath + "/out1.xlsx");
                
                    AsposeApp.AppSID  = "77***********************************";
AsposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split workbook
string strURI = "http://api.aspose.com/v1.1/cells/Sample.xlsx/split?format=png";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitWorkbookResponse responseStream = JsonConvert.DeserializeObject<SplitWorkbookResponse>(parsedJSON.ToString());


foreach (DocumentResponse splitSheet in responseStream.Result.Documents)
{
    string splitFileName = System.IO.Path.GetFileName(splitSheet.link.Href);
    //build URI to download split worksheets
    strURI = "http://api.aspose.com/v1.1/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split worksheets
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}

    // class definitions
    public class SplitWorkbookResponse : Aspose.Cloud.Common.BaseResponse
    {
        public SplitWorkbook Result { get; set; }
    }
    public class SplitWorkbook
    {
        public DocumentResponse[] Documents { get; set; }
    }
    public class DocumentResponse
    {
        public int Id { get; set; }
        public LinkResponse link { get; set; }
    }
    /// <summary>
    /// represents link part of the response
    /// </summary>
    public class LinkResponse
    {
        public string Href { get; set; }
        public string Rel { get; set; }
        public string Title { get; set; }
        public string Type { get; set; }
    }

Split selected worksheets to TIFFs 
 
AsposeApp.AppSID  = "77***********************************";
AsposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split workbook
string strURI = "http://api.aspose.com/v1.1/cells/Sample.xlsx/split?from=1&to=2&format=tiff";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitWorkbookResponse responseStream = JsonConvert.DeserializeObject<SplitWorkbookResponse>(parsedJSON.ToString());


foreach (DocumentResponse splitSheet in responseStream.Result.Documents)
{
    string splitFileName = System.IO.Path.GetFileName(splitSheet.link.Href);
    //build URI to download split worksheets
    strURI = "http://api.aspose.com/v1.1/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split worksheets
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}

    // class definitions
    public class SplitWorkbookResponse : Aspose.Cloud.Common.BaseResponse
    {
        public SplitWorkbook Result { get; set; }
    }
    public class SplitWorkbook
    {
        public DocumentResponse[] Documents { get; set; }
    }
    public class DocumentResponse
    {
        public int Id { get; set; }
        public LinkResponse link { get; set; }
    }
    /// <summary>
    /// represents link part of the response
    /// </summary>
    public class LinkResponse
    {
        public string Href { get; set; }
        public string Rel { get; set; }
        public string Title { get; set; }
        public string Type { get; set; }
    } 
                
                    //Mail Merge using PHP REST

// Build URI to execute mail merge
$strURI = 'http://api.aspose.com/v1.1/words/Sample.docx/executeMailMerge?withRegions=true&mailMergeDataFile=Data.xml';
// Use the following URI if you want to remove EmptyParagraphs,UnusedRegions,UnusedFields and ContainingFields during mail merge
// $strURI = 'http://api.aspose.com/v1.1/words/Sample.docx/executeMailMerge?mailMergeDataFile=Data.xml&cleanup=EmptyParagraphs,UnusedRegions,UnusedFields,ContainingFields';
/**** End Section 1 ****/

/**** Section 2 ****/
$appSID  = "77****-****-****-****-80*********";
$appKey = "****************";

// Sign URI
$signedURI = Sign($strURI, $appSID, $appKey);
/**** End Section 2 ****/

/**** Section 3 ****/
$responseStream = ProcessCommand($signedURI, "POST", "", "");
/**** End Section 3 ****/

/**** Section 4 ****/
$json = json_decode($responseStream);
//build URI to download output DOC
$outputFileName = $json->Document->FileName;
/**** End Section 4 ****/

//Mail Merge using PHP SDK

/**** Section 1 ****/

// Specify product URI Product::$baseProductUri = "http://api.aspose.com/v1.1"; //sepcify App SID AsposeApp::$appSID = "xxxxxxxxxxxxxxxxxxxxxxxx"; //sepcify App Key AsposeApp::$appKey = "xxxxxxxxxxxxxxxxxxxxxxxx";

/**** End Section 1 ****/

try{

/**** Section 2 ****/
AsposeApp::$outPutLocation = getcwd() . "/Output/";   $mainDocumentFile = getcwd() . "/Input/SimpleMerge.doc";   $mainDocument = basename($mainDocumentFile);   $xml = simplexml_load_file(getcwd() . "/Input/SimpleMerge.xml");
/**** End Section 2 ****/

/**** Section 3 ****/
//upload main document   echo "Uploading main document...<br />";   $folder = new Folder();   $folder->uploadFile($mainDocumentFile, "");   echo "Main document uploaded <br />";
/**** End Section 3 ****/

/**** Section 4 ****/
echo "Executing mail merge... <br />";   //create MailMerge object   $doc = new MailMerge();   $result = $doc->executeMailMerge($mainDocument, $xml->asXML());
/**** End Section 4 ****/ }

catch (Exception $e)
  {
    throw new Exception($e->getMessage());
  }

//«TableStart:TableName»«TableEnd:TableName» regions, use the following XML structure to send in the request body.

<?xml version="1.0" encoding="utf-8"?>
<CollectionName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ItemName>
        <field1>Value1</field1>
        <field2>Value2</field2>
    </ItemName>
    <ItemName>
        <field1>Value1</field1>
        <field2>Value2</field2>
    </ItemName>
</CollectionName>