Instagram & Processing - Real time view - api

I'm working on a small app similar to instaprint and need some help. I'm using the source code from Globalgram by Andrew Haskin, it searches instagram for a particular hashtag and displays the most recent image posted with that hashtag. The problem is it only does it once, I need it to continuously search for the hashtag and display an image when a new one is added, so a refresh, I've been tinkering with it but to no avail. Any help would be greatly appreciated
Code Below :
import com.francisli.processing.http.*;
PFont InstagramFont;
PImage backgroundimg;
PImage brand;
PImage userphoto;
PImage profilepicture;
String username;
String tag;
String[] tagStrings;
com.francisli.processing.http.HttpClient client;
void setup() {
size(580, 900);
smooth();
backgroundimg = loadImage("iso_background.jpg");
brand = loadImage("iso.jpg");
InstagramFont = loadFont("Helvetica-Bold-36.vlw");
client = new com.francisli.processing.http.HttpClient(this, "api.instagram.com");
client.useSSL = true;
//// instantiate a new HashMap
HashMap params = new HashMap();
//// put key/value pairs that you want to send in the request
params.put("access_token", "------ACCESS TOKEN HERE------");
params.put("count", "1");
client.GET("/v1/tags/coffee/media/recent.json", params);
}
void responseReceived(com.francisli.processing.http.HttpRequest request, com.francisli.processing.http.HttpResponse response) {
println(response.getContentAsString());
//// we get the server response as a JSON object
com.francisli.processing.http.JSONObject content = response.getContentAsJSONObject();
//// get the "data" value, which is an array
com.francisli.processing.http.JSONObject data = content.get("data");
//// get the first element in the array
com.francisli.processing.http.JSONObject first = data.get(0);
//// the "user" value is another dictionary, from which we can get the "full_name" string value
println(first.get("user").get("full_name").stringValue());
//// the "caption" value is another dictionary, from which we can get the "text" string value
//println(first.get("caption").get("text").stringValue());
//// get profile picture
println(first.get("user").get("profile_picture").stringValue());
//// the "images" value is another dictionary, from which we can get different image URL data
println(first.get("images").get("standard_resolution").get("url").stringValue());
com.francisli.processing.http.JSONObject tags = first.get("tags");
tagStrings = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
tagStrings[i] = tags.get(i).stringValue();
}
username = first.get("user").get("full_name").stringValue();
String profilepicture_url = first.get("user").get("profile_picture").stringValue();
profilepicture = loadImage(profilepicture_url, "png");
String userphoto_url = first.get("images").get("standard_resolution").get("url").stringValue();
userphoto = loadImage(userphoto_url, "png");
//noLoop();
}
void draw() {
background(255);
imageMode(CENTER);
image(brand, 100, height/1.05);
if (profilepicture != null) {
image(profilepicture, 60, 70, 90, 90);
}
imageMode(CENTER);
if (userphoto != null) {
image(userphoto, width/2, height/2.25, 550, 550);
}
textFont(InstagramFont, 20);
if (username != null) {
text(username, 110, 115);
fill(0);
}
textFont(InstagramFont, 15);
if ((tagStrings != null) && (tagStrings.length > 0)) {
String line = tagStrings[0];
for (int i = 1; i < tagStrings.length; i++) {
line += ", " + tagStrings[i];
}
text(line, 25, 720, 550, 50);
fill(0);
}
}

AFAIK it should be the
client.GET("/v1/tags/coffee/media/recent.json", params);
line that actually polls Instagram. Try wrapping that in a function like this:
void getGrams() {
client.GET("/v1/tags/coffee/media/recent.json", params);
}
then call that once in setup() and then again when you want to ...
I'd start with trying to do it on mousePressed() or keyPressed(), so that it only fires once when you really want it to
Don't try to do it in draw() without a timer (something like if(frameCount % 5000 == 0) which will fire every five seconds ((which may be too fast still but you get the idea))

Related

JavaFx Problem with Service and Task with different Parameters and multiple calls

i need to create a Service and a Task to calculate the Mandelbrot and JuliaSet.
The calculation is working pretty good and now we need to give it into a Service and call it inside the task.
I have now the Problem, that every Time the task is executed, the Parameters are different.
I wrote a little Setter Function to parse those Arguments to the Service first.
But i'm not sure if this is the right Way?!
I'm also not sure how to correctly call the service in the main Function?
Now it works like this:
First time the service is executed, everything seems to work, but when i call it a secound Time, nothing seems to happen.....
Just to make sure: A Service can execute the Task multiple Times at the same Time?
Is it also posible with different Parameters?
Code Task:
private MandelbrotRenderOptions mandelbrot;
private JuliaRenderOptions juliaset;
private Canvas leftCanvas;
private Canvas rightCanvas;
//Constructor
public RenderTask(Canvas leftCanvas, Canvas rightCanvas) {
this.leftCanvas = leftCanvas;
this.rightCanvas = rightCanvas;
}
public void setOptions(MandelbrotRenderOptions mandelbrot, JuliaRenderOptions juliaset) {
this.mandelbrot = mandelbrot;
this.juliaset = juliaset;
}
#Override
protected Void call() throws Exception {
try {
System.out.println("HALLO SERVICE");
// instances for rendering the left canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
// creates an writable image which contains the dimensions of the canvas
WritableImage wimLeftCanvas = new WritableImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
// instance which can write data into the image (instance above)
PixelWriter pwLeftCanvas = wimLeftCanvas.getPixelWriter();
// instance which fills the canvas
GraphicsContext gcLeftCanvas = leftCanvas.getGraphicsContext2D();
// instances for rendering the right canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
WritableImage wimRightCanvas = new WritableImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
PixelWriter pwRight = wimRightCanvas.getPixelWriter();
GraphicsContext gcRightCanvas = rightCanvas.getGraphicsContext2D();
gcLeftCanvas.clearRect(0, 0, leftCanvas.getWidth(), leftCanvas.getHeight());
//Pixel[][] pixels; // contains pixel data for rendering canvas
// instances for logging the rendered data
SimpleImage simpleImageLeftCanvas = new SimpleImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
SimpleImage simpleImageRightCanvas = new SimpleImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
short dataSimpleImage[] = new short[3]; // contains pixel data for logging rendered data
// fills left canvas (mandelbrot) PixelWriter instance with data
Pixel[][] pixels = mandelbrot.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) leftCanvas.getHeight(); y++) {
for (int x = 0; x < (int) leftCanvas.getWidth(); x++) {
// parses color data to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwLeftCanvas.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageLeftCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of mandelbrot is finished
FractalLogger.logRenderFinished(FractalType.MANDELBROT, simpleImageLeftCanvas);
// fills left canvas (juliaset) PixelWriter instance with data
pixels = juliaset.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) rightCanvas.getHeight(); y++) {
for (int x = 0; x < (int) rightCanvas.getWidth(); x++) {
// pareses color to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwRight.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageRightCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of juliaset is finished
FractalLogger.logRenderFinished(FractalType.JULIA, simpleImageRightCanvas);
// writes data from WriteableImage instance to GraphicsContext instance, which finally parses renders it into the canvas
gcLeftCanvas.drawImage(wimLeftCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.MANDELBROT);
gcRightCanvas.drawImage(wimRightCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.JULIA);
return null;
} catch (Exception e) {
System.out.println("ERROR");
System.out.println(e);
return null;
}
}
#Override
protected void cancelled()
{
super.cancelled();
updateMessage("The task was cancelled.");
}
#Override
protected void failed()
{
super.failed();
updateMessage("The task failed.");
}
#Override
public void succeeded()
{
super.succeeded();
updateMessage("The task finished successfully.");
} ```
And i call it like this in the main:
``` Service service = new Service() {
#Override
protected Task createTask() {
return new RenderTask(leftCanvas, rightCanvas);
}
};
task.setOptions(mandelbrot, juliaset);
service.restart(); ```

Screenshot using SharpDX and EasyHook transparent

I have been struggling in taking screenshots with DirectX, the problem is, it's working but seems to be missing some colors (black outline is missing for example), and some stuff that is also rendered by DX doesn't show.
I have uploaded the images (how the image should render and the rendered one) and also the code, what might be the issue?
Correct Image
Rendered Image
Greetings
public class Screenshot
{
public static void TakeScreenshot(string name = null)
{
var t = new Thread((ThreadStart) delegate
{
// destination folder
var destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.Create) + "\\My Software\\Screenshots";
if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
// file name
string filename = name;
if (string.IsNullOrEmpty(name))
filename = "image-" + (Directory.GetFiles(destinationFolder, "*.png").Count() + 1).ToString("000") + ".png";
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width;
int height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Save the output
bitmap.Save(destinationFolder + Path.DirectorySeparatorChar + filename);
// Send Message
Main.Chat.AddMessage(null, "~b~Screenshot saved as " + filename);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
throw e;
}
}
}
});
t.IsBackground = true;
t.Start();
}
}

How to create a single-color Bitmap to display a given hue?

I have a requirement to create an image based on a certain color. The color will vary and so will the size of the output image. I want to create the Bitmap and save it to the app's temporary folder. How do I do this?
My initial requirement came from a list of colors, and providing a sample of the color in the UI. If the size of the image is variable then I can create them for certain scenarios like result suggestions in the search pane.
This isn't easy. But it's all wrapped in this single method for you to use. I hope it helps. ANyway, here's the code to create a Bitmap based on a given color & size:
private async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CreateThumb(Windows.UI.Color color, Windows.Foundation.Size size)
{
// create colored bitmap
var _Bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)size.Width, (int)size.Height);
byte[] _Pixels = new byte[4 * _Bitmap.PixelWidth * _Bitmap.PixelHeight];
for (int i = 0; i < _Pixels.Length; i += 4)
{
_Pixels[i + 0] = color.B;
_Pixels[i + 1] = color.G;
_Pixels[i + 2] = color.R;
_Pixels[i + 3] = color.A;
}
// update bitmap data
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Stream.Seek(0, SeekOrigin.Begin);
_Stream.Write(_Pixels, 0, _Pixels.Length);
_Bitmap.Invalidate();
}
// determine destination
var _Folder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
var _Name = color.ToString().TrimStart('#') + ".png";
// use existing if already
Windows.Storage.StorageFile _File;
try { return await _Folder.GetFileAsync(_Name); }
catch { /* do nothing; not found */ }
_File = await _Folder.CreateFileAsync(_Name, Windows.Storage.CreationCollisionOption.ReplaceExisting);
// extract stream to write
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Pixels = new byte[(uint)_Stream.Length];
await _Stream.ReadAsync(_Pixels, 0, _Pixels.Length);
}
// write file
using (var _WriteStream = await _File.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var _Encoder = await Windows.Graphics.Imaging.BitmapEncoder
.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, _WriteStream);
_Encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied,
(uint)_Bitmap.PixelWidth, (uint)_Bitmap.PixelHeight, 96, 96, _Pixels);
await _Encoder.FlushAsync();
using (var outputStream = _WriteStream.GetOutputStreamAt(0))
await outputStream.FlushAsync();
}
return _File;
}
Best of luck!

Twitter App in Processing

I'm having a massive problem with a Twitter App I'm trying to create. I've been at this problem for 2 weeks straight, 14 hours a day and I cannot get my head around how to fix. I'm a newbie so I'm sure it's just a simple matter.
I need my twitter stream to display five tweets at a time. Then I need for it to remove the oldest tweet and replace it with a new one. Now I was told the best method for this is to use the Linkedlist, which makes perfect sense. However, whenever I attempt to incorporate this, it just won't work.
If someone could help me out I'd be endlessly grateful as I'm at my wits end at this point.
Here's the code:
import com.francisli.processing.http.*;
import java.util.LinkedList;
//LinkedList myList;
HashMap overall = new HashMap();
HttpClient client;
LinkedList myList;
PImage prhomoPix;
int results_to_show = 5;
int updateTime = 10000;
int updateDiff = 0;
void setup()
{
myList = new LinkedList();
for (int i = 0; i < 5; i++)
{
myList.add(client);
}
size(1143, 800);
prhomoPix = loadImage("PrhomoAppBg.jpg");
background(0);
image(prhomoPix, 0, 0);
fill(0, 0, 0, 80);
noStroke();
rect(20, 135, 370, 670);
fill(0, 0, 0, 80);
noStroke();
rect(755, 135, 370, 670);
textAlign(CENTER, CENTER);
}
void responseReceived(HttpRequest request, HttpResponse response)
{
if(response.statusCode == 200)
{
JSONObject allresults;
allresults = response.getContentAsJSONObject();
//JSONObject timeline_tweets = response.getContentAsJSONObject();
for (int i = 0; i < 5; i++)
{
text(allresults.get("results").get(i).get("text").stringValue(), 25, 50+(i*120), 330, 330);
}
frameRate(2);
//}
//for (int i=0; i < results_to_show; i++)
//{
// text(allresults.get("results").get(i).get("text").stringValue(), 25, 50+(i*120), 330, 330);
// }
}
else
{
text("UH-OH" + response.getContentAsString(), 50, 50);
}
}
void tweetUpdate()
{
if(millis() > (updateTime + updateDiff))
{
client = new HttpClient(this, "search.twitter.com");//what webservice we are using, this is the priate OAuth one. "this" means it is not cpying setting from anywhere else
client.GET("search.json?q=dublin&rpp="+results_to_show+"&result_type=recent");
//println(myList);
updateDiff = millis();
}
}
void draw()
{
myList.remove(client);
myList.add(client);
tweetUpdate();
}
Once again thanks so much!
To be honest with you, Java is really not my field, but these tutorials looked quite self explanatory. Hope they help.
http://examples.javacodegeeks.com/core-java/util/linkedlist/
You have to repaint whole screen in draw() method.
I guess, people told you to save tweets in LinkedList, not HttpClient.
Update list of tweets in responseReceived() method.
Eventually, your draw would look something like this:
void draw() {
// repaint
background(0);
// draw picture
image(prhomoPix, 0, 0);
// repaint all tweets
for(int i=0; i< tweetsList.size(); ++i {
drawTweet(tweetsList);
}
tweetUpdate(); // update list of tweets from server
}
tweetUpdate()
void tweetUpdate() {
client = new HttpClient(this, "search.twitter.com");
client.GET("search.json?q=dublin&rpp="+results_to_show+"&result_type=recent");
}

RavendDB faceted search results formatting

Currently I'm playing with faceted search after reading RavenDB doc about it.
The result returned is OK, but there's a small problem. Since the result comes as
IDictionary<string, IEnumerable<FacetValue>>
it's necessary to iterate over it and do some fancy string manipulation to format the result and show it in a PartialView. More specifically this facet:
new Facet
{
Name = "Value_Range",
Mode = FacetMode.Ranges,
Ranges =
{
"[NULL TO Dx500.0]",
"[Dx500.0 TO Dx1000.0]",
"[Dx1000.0 TO Dx2500.0]",
"[Dx2500.0 TO Dx5000.0]",
"[Dx5000.0 TO NULL]",
}
}
View code:
#fv.Range
This is this "beautiful" string that gets output on the view: [Dx400.0 TO Dx600.0]
RavenDB uses the Dx prefix above to do a number to string conversion.
Controller code where the facet result is passed to a specific ViewModel:
var facetResults = DocumentSession.Query<Realty>("RealtyFacets")
//.Where(x => x.Value >= 100 && x.Value <= 1000)
.ToFacets("facets/RealtyFacets").ToArray();
var model = new RealtyFacetsViewModel();
model.Cities = facetResults[0];
model.Purposes = facetResults[1];
model.Types = facetResults[2];
model.Values = facetResults[3];
return PartialView("RealtyFacets", model);
Is there any other/better way of getting results from a faceted search so that no string manipulation must be done to format the returned data?
After Ayende's suggestion, I did this in my controller:
foreach (var val in facetResults[3].Value)
{
switch(val.Range)
{
case "[Dx0.0 TO Dx200.0]":
val.Range = string.Format("{0:C2} {1} {2:C2}",
0, #Localization.to, 200);
break;
case "[Dx200.0 TO Dx400.0]":
val.Range = string.Format("{0:C2} {1} {2:C2}",
200, #Localization.to, 400);
break;
case "[Dx400.0 TO Dx600.0]":
val.Range = string.Format("{0:C2} {1} {2:C2}",
400, #Localization.to, 600);
break;
case "[Dx600.0 TO Dx800.0]":
val.Range = string.Format("{0:C2} {1} {2:C2}",
600, #Localization.to, 800);
break;
case "[Dx800.0 TO Dx1000000.0]":
val.Range = string.Format("{0:C2} {1} {2:C2}",
800, #Localization.to, 1000000);
break;
}
}
model.Values = facetResults[3];
As per #MattWarren suggestion, I ended up using:
foreach (var val in facetResults[3].Value)
{
// Original string format: [Dx5000.0 TO Dx10000.0]
var limits = val.Range.Split(new string[] { "TO", "[", "]", " " },
StringSplitOptions.RemoveEmptyEntries);
// Leveraging RavenDB NumberUtil class...
val.Range = string.Format("{0:C0} {1} {2:C0}",
Raven.Abstractions.Indexing.NumberUtil.StringToNumber(limits.ElementAt(0)),
#Localization.to,
Raven.Abstractions.Indexing.NumberUtil.StringToNumber(limits.ElementAt(1)));
}
Leniel,
In your code, create a dictionary that would map between the facet value and the display string.
RavenDB currently have no way to influence the facet value.