Wednesday, April 11, 2012

Boost asio io_service dispatch vs post

Can anyone tell me the difference between io_service dispatch and post? It was not clear to me what is more suitable for my problem.



I need to invoke a handler inside another handler and I don't know what invoker to use.



Thanks.





How should I use Youtube API [closed]

How should I use youtube API?
I want to use youtube API to search a movie, such as Titanic and then play it in a web page. How should I do these using jsp?





Simple remove text script

this might be simple, but I've spent ages searching and googling, I've come close, but no cigar...



Is anyone able to whip me up a little script to delete all instances of



<a href="http://mysite.com/search?mode=results&amp;queries_name_query="></a>


in the body of a HTML doc?



My tags are generated by JS and they always print an extra blank href so hopefully another quick script to remove them can clear this up?



All help and helpful advice is always very much appreciated.





ruby regular expressions

I am trying to create a program where a user enters four numbers using regular expressions . If one of those numbers is 13 then the numbers to the left do not count toward the sum. My problem is creating an exception where none of the numbers equal 13. I cant seem to find a regular expression for my exception
thanks in advanced



puts "enter a number then hit enter four times"

number1 = STDIN.gets

number2 = STDIN.gets
number3 = STDIN.gets

number4 = STDIN.gets


if number1 =~ /13/ then
puts number2.to_i + number3.to_i + number4.to_i
end

if number2 =~/13/ then
puts number3.to_i + number4.to_i
end

if number3 =~/13/ then
puts number4.to_i
if number4 =~/13/ then
puts "0"
end
if number1 != 13 or number2 != 13 or number3 != 13 or number4 != 13
puts number1.to_i + number2.to_i + number3.to_i + number4.to_i
end
end




Multiple SimpleModals on one page

Newbie question I think, but maybe not... I am using SimpleModal for a project, and have a case where there are multiple triggers and modals on a page.



Page is here: http://lumetta.highchairdesign.com/newsite/lumenate-portfolio/linen



Markup for the trigger is like:



<a class="modalbutton" href="#item_31" title="D112 Sand"
style="background-image: url(/newsite/documents/gallery_photos/59.D112-Sand.jpg);">
</a>


Markup for the Modal is like:



<div id="#item_31" class="modal">
<h3>D112 Sand</h3>
<a href="javascript:;" class="lumenate_largethumb" style="background-image: url(/newsite/documents/gallery_photos/59.D112-Sand.jpg);">
</a>
</div>


Yes, I know it's odd, but the modal contains a sprite so that is why I am using an A with a background image...



My JS looks like:



$(".modalbutton").click(function (e) {

var iden = $(this).attr("href");

$("" + iden + "").modal( {
close: true
});
});


My JS is trying to figure out which link has been clicked, and inject it with the proper DIV. I get the click action, I get the modal container to appear, but the content does not get injected.



I tried quotes around the "iden" variable, I tried no quotes... doesn't help. I tried thedirect call to the modal action, which looks like $.modal( $( iden ), { etc..., no luck there. I tried passing the content div ID to the proper setting variable for SimpleModal, which is "dataId"... no dice.



I'm losing my mind and going to bed. This was supposed to be simple. Help?





Location vs GeoPoint vs 1E6 vs Charging

I am writing a location based App and want to get some wisdom on sensible API usage.



What I've understood so far is that working with int is more efficient. I'm going to need to store loads of them and do alot of distance calculations.



My app uses a Service that implements LocationListener and I am storing longitude & latitude as int values (micro-degrees) inside an SQL db (via ormlite) calculated thus ::



public static int degreesToMicroDegrees(double degrees){
return (int)(degrees * 1E6);
}


Sometimes I need to know when I have returned to a particular 'location' and as such I fetch the int values back out of the db to compare with the latest location update.



Question is, what is the best way to compare 'location' between the int values (where I used to be) and the double values (where I am now) in my latest Location update?



I have searched around for some Math to accomplish the distance calculation and found this ::



public static double distanceBetween(double lat1, double lng1, double lat2, double lng2) {

double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;

return dist;
}


I have tried passing my int values in like this :: ((double)myIntValue) / 1E6F
The returned distance values are confusing me. If I walk 100m my app sensibly tells me I've gone about 100m using Location.distanceTo(myLastLocation). But if I use the method above against my stored int values I get the value zero back.



If anyone can explain the E6 format that would be great.



1E6 is the same as 1000000 ?



Additionally I can see there is this GeoPoint class. I am hesitant to use this as I'm not clear if making vast numbers of calculations on GeoPoints is going to be charged for by Google. There seems to be some noise about charges for use of GoogleMaps APIs and I haven't been able to find a clear explanation of how that charging works.



All wisdom gratefully received.





How well do Tomahawk20 and Richfaces3.3.3.Final work together?

When i use Tomahawk20(Tomahawk20-1.1.11 for jsf-2.0) and Richfaces3.3.3.Final together, the tag of t:inputCalender can not work, the pop-up overlay can not displayed, and got javascript errors. I find that the function processEvent() can not work after adding richfaces, some javascript and css files can not include in the jsp page. After adding the js and css files manually, the t:inputCalender work, but tag of rich:pickList and rich:orderingList will not work both.





C - How to prompt user to enter filename

Very new to C programming. I'm writing a program where I want to prompt the user to input the name of the file to be open for reading. On my code shown bellow I want to throw an error if it doesn't open or if the file doesn't exist, but when I run it, my code blows up and I have to close the program (DOS)



/*ask user for the name of the file*/
printf("enter file name: ");
gets(fname);


//Opens the file from where the text will be read.
fp=fopen(fname, "r");

//Checks if the file us unable to be opened, then it shows the error message
if (fp == NULL)
{
printf("\nError, Unable to open the file for reading\n");
}


// you can test this by creating a name.txt file. Please let me know if you need additional information.





Camera onPreviewFrame not called on XT910

I have a problem with the camera of my MOTO XT910 android phone. I would like only to access to the camera's (frame)buffer but "onPreviewFrame" is never called. On my emulator, it works fine.



Thanks in advance,



My code is as below:



public class Store extends SurfaceView implements SurfaceHolder.Callback, PreviewCallback {
static {
System.loadLibrary("hello-jni");
}

public native void decode(Bitmap pTarget, byte[] pSource);

private Camera mCamera;
private byte[] mVideoSource;
private Bitmap mBackBuffer;
private Paint mPaint;
private Size lSize;
private static String TAG = Store.class.getCanonicalName();


public Store(Context context) {
super(context);
getHolder().addCallback(this);
setWillNotDraw(false);
}

public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera = Camera.open();
mCamera.setDisplayOrientation(0);
mCamera.setPreviewDisplay(null);
mCamera.setPreviewCallbackWithBuffer(this);
Log.d(TAG,"surfaceCreated ok");
} catch (IOException eIOException) {
mCamera.release();
mCamera = null;
Log.d(TAG,"surfaceCreated failed");
throw new IllegalStateException();
}
}

public void surfaceChanged(SurfaceHolder pHolder, int pFormat, int pWidth, int pHeight) {
Log.d(TAG,"surfaceChanged in");
mCamera.stopPreview();
lSize = findBestResolution(pWidth, pHeight);
invalidate();
PixelFormat lPixelFormat = new PixelFormat();
PixelFormat.getPixelFormatInfo(mCamera.getParameters()
.getPreviewFormat(), lPixelFormat);
int lSourceSize = lSize.width * lSize.height * lPixelFormat.bitsPerPixel / 8;
mVideoSource = new byte[lSourceSize];
mBackBuffer = Bitmap.createBitmap(lSize.width, lSize.height,Bitmap.Config.ARGB_8888);
Camera.Parameters lParameters = mCamera.getParameters();
lParameters.setPreviewSize(lSize.width, lSize.height);
lParameters.setPreviewFormat(PixelFormat.YCbCr_420_SP);
mCamera.setParameters(lParameters);
mCamera.addCallbackBuffer(mVideoSource);
mCamera.startPreview();
Log.d(TAG,"surfaceChanged out");
}

private Size findBestResolution(int pWidth, int pHeight) {
List<Size> lSizes = mCamera.getParameters().getSupportedPreviewSizes();
Size lSelectedSize = mCamera.new Size(0, 0);
for (Size lSize : lSizes) {
if ((lSize.width <= pWidth) && (lSize.height <= pHeight)
&& (lSize.width >= lSelectedSize.width)
&& (lSize.height >= lSelectedSize.height)) {
lSelectedSize = lSize;
}
}
if ((lSelectedSize.width == 0) || (lSelectedSize.height == 0)) {
lSelectedSize = lSizes.get(0);
}
return lSelectedSize;
}

public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
Log.d(TAG,"surfaceDestroyed");
mCamera.stopPreview();
mCamera.release();

mCamera = null;
mVideoSource = null;
mBackBuffer = null;
}
}

public void onPreviewFrame(byte[] pData, Camera pCamera) {
Log.d(TAG,"onPreviewFrame");
decode(mBackBuffer, pData);
invalidate();
}

@Override
protected void onDraw(Canvas pCanvas) {
Log.d(TAG,"onDraw in");
if (mCamera != null) {
Paint paint = new Paint();
paint.setColor(Color.YELLOW);
String text = String.format("%dx%d", lSize.width, lSize.height);
pCanvas.drawText(text, 10, 10, paint);
pCanvas.drawLine(0, 0, 100, 100, paint);
pCanvas.drawLine(20, 0, 0, 20, paint);
pCanvas.drawBitmap(mBackBuffer, 0, 0, mPaint);

mCamera.addCallbackBuffer(mVideoSource);
Log.d(TAG,"onDraw out");
}
}


}





Android: Detect When SD Card Mounted as Disk Drive to a Computer

I am writing an application that needs to detect when the SD card is mounted as a disk drive to a computer via USB or when it has been manually removed. I tried using a broadcast receiver for this purpose, but the onReceive is not getting called. My code is as follows.



IntentFilter filter2 = new IntentFilter();
//filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
filter2.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter2.addAction(Intent.ACTION_MEDIA_SHARED);
filter2.addAction(Intent.ACTION_MEDIA_REMOVED);
filter2.addAction(Intent.ACTION_MEDIA_MOUNTED);

registerReceiver(new CustomBroadcastReceiver(), filter2);


My broadcast receiver is as follows...



public class CustomBroadcastReceiver extends BroadcastReceiver{

public CustomBroadcastReceiver(){

}

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_SHARED) || action.equals(Intent.ACTION_MEDIA_REMOVED)){
HardwareManager.IS_MEDIA_MOUNTED = false;
}else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
HardwareManager.IS_MEDIA_MOUNTED = true;
}else if(action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){
HardwareManager.IN_AIRPLANE_MODE = intent.getBooleanExtra("state", false);
}
}

}


The onReceive method does not fire when I connect as a disk drive via USB.



What am I doing wrong ?





Flushing footer to bottom of the page, twitter bootstrap

I am generally familiar with the technique of flushing a footer using css and the following approach - http://od-eon.com/blogs/calvin/flush-footer-css-bottom-page/



But I am having some trouble getting this approach to work for twitter bootstrap, most likely due to the fact that twitter bootstrap is responsive in nature. Here's a web app I am working on, using twitter bootstrap and I am not able to get the footer to flush to the bottom of the page using the approach described in the above blog post.



See
http://bokxy.com
and
http://bokxy.com/404



The "404 page" shows that the footer is all the way high up the page when the content is sparse.





Do I need to add memory pressure when starting to solve a large MIP via the c# API for cplex?

Do I need to call GC.AddMemoryPressure when solving a large problem via the cplex API?



Edit: The reason I ask is that cplex throws errors during solving that might be cause by lack of memory. So perhaps adding pressure will convince the GC that a Collection is needed? But I don't know how much memory is used by cplex?





Proper way to redirect binding in Ember.js

I've read the Ember.js documentation + samples, and nested views with bindings are confusing me a little bit.



I have the following abbreviated HTML (working fine):



{{#view App.outerArea}}
{{#view innerArea}}
{{view Ember.TextField valueBinding="parentView.parentView.bound.username"}}
{{/view}}
{{/view}}


...and JavaScript (also working fine):



App = Ember.Application.create();
App.outerArea = Ember.View.extend({
bound : {
username:'test',
},
innerArea: Ember.View.extend({}),
});


(If I remove innerArea from the HTML I can remove 'parentView.parentView.' entirely.)



To clean this up I've tried:



...
{{view Ember.TextField valueBinding="bound.username"}}
...
innerArea: Ember.View.extend({
bound: function() {
return App.outerArea.bound;
}
})


And tried:



{{view Ember.TextField valueBinding="getPath(bound.username)"}} // with above bound: function().


And some other combinations, but they don't work at all.



Is there a more elegant way to reference 'parentView.parentView.bound.username' from the TextField valueBinding? Is there more than one approach to this? What are the best design patterns for this sort of thing?



Thank you!





Sorting on Multiple fields -- Its working, but not able to understand how is it working.

class Employee implements Comparable{
private String name;
private String gender;

Employee(String name, String gender) {
this.name = name;
this.gender = gender;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String toString() {
return this.getName() + " : " + this.getGender();
}

@Override
public int compareTo(Object o) {
int gendarComp=this.getGender().compareTo(((Employee)o).getGender());
return (gendarComp!=0?gendarComp:this.name.compareTo(((Employee)o).getName()));
}
}

class EmployeeExec {
public static void main(String[] args) {
List allEmpls = new ArrayList();
allEmpls.add(new Employee("vijay", "m"));
allEmpls.add(new Employee("balaji", "m"));
allEmpls.add(new Employee("shaifali", "f"));
allEmpls.add(new Employee("archana", "f"));
allEmpls.add(new Employee("alala", "m"));
allEmpls.add(new Employee("kiran", "f"));

sortEmployees(allEmpls);
}

public static void sortEmployees(List allEmpls) {
Collections.sort(allEmpls);
System.out.println(allEmpls);
}
}


Can any one Please help me in understanding how it is working? what is the funda to sort. I kept some sysout statements to see, but I dont really understand how it is getting called. I know its working with merge sort. but how? please help me.



-Balaji





DataAnnotationsExtensionsMVC3 validation not working on Integer value

Getting default error message for int datatype
i.e he value 'abc' is not valid for age

What should i do.



   public class HomeViewModel
{
[Integer(ErrorMessage="provide valid numeric value")}
public int age{ get; set; }
}




Grails 1.3.5: How to configure Datasource.groovy to either connect to MySQL or SQL Server

The grails application I am developing could run against MySQL or SQL Server. I want to add a new property in application.properties file say

database.type=MySQL // or it could be SQLSERVER



How do I get this property in Datasource.groovy so that if it is MySQL I connect to MySQL server or it is SQLSERVER I connect to SQL Server?



Is this the correct way to do it? How can I do it?



EDIT: After reading and searching for options I figured the following way explained.
I have created config.properties file in /grails-app/conf/ folder.



driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver
dataSource.url = jdbc:sqlserver://localhost:1433;databaseName=testDB
dataSource.username = sa
dataSource.password = sa


Also updated Config.groovy



grails.config.locations = ["classpath:config.properties"]


But I get the below error

Unable to load specified config location classpath:config.properties : class path resource [config.properties] cannot be opened because it does not exist



But if use



grails.config.locations = ["file:E:/workspace/SpringSource2.3.3/GRAILS_PRO/config.properties"]


The application starts up and is able to connect to the database. I don't want to use static file path. What is wrong when using classpath?



Have the same issue for both 'run-app' and 'war' mode i.e. same file does not exist error.



2nd EDIT:



After so much frustration of using classpath and not able to get it to work, I resorted to using environment property. Since server will have CATALINA_HOME defined, I used the below to build the path for external configuration file.



def CATALINA_HOME = "CATALINA_HOME"
def CONFIG_FILE_NAME = "db_config.properties"
if(!grails.config.locations || !(grails.config.locations instanceof List)) {
grails.config.locations = []
}

if(System.getenv(CATALINA_HOME)) {
def fullPath = System.getenv(CATALINA_HOME) + File.separator + "webapps" + File.separator + "${appName}" + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + CONFIG_FILE_NAME
grails.config.locations << "file:" + fullPath
} else {
println "Missing configuration!"
}


The above solution is Tomcat specific. I really would like to see classpath version working!



Thank You.
Regards,
Jay Chandran.





Sscanf Equivalent in Objective-C

I'm currently writing a wavefront OBJ loader in Objective-C and I'm trying to figure out how to parse data from an NSString in a similar manner to the sscanf() function in C.



OBJ files define faces in x,y,z triplets of vertices, texture coordinates, and normals such as:



f 1.43//2.43 1.11//2.33 3.14//0.009


I'm not concerned about texture coordinates at the current moment. In C, an easy way to parse this line would be a statement such as:



sscanf(buf, "f %d//%d %d//%d %d//%d", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]);


Obviously, NSStrings can't be used in a sscanf() without first converting them to a C-style string, but I'm wondering if there's a more elegant way to performing this without doing such a conversion.





Creating a tree node diagram

I am trying to create a tree like node diagram, like the example image here. I have the following code:



    private void DrawNode(Graphics g, Node<T> node, float xOffset, float yOffset)
{
if (node == null)
{
return;
}

Bitmap bmp = (from b in _nodeBitmaps where b.Node.Value.Equals(node.Value) select b.Bitmap).FirstOrDefault();

if (bmp != null)
{
g.DrawImage(bmp, xOffset, yOffset);

DrawNode(g, node.LeftNode, xOffset - 30 , yOffset + 20);
DrawNode(g, node.RightNode, xOffset + 30, yOffset + 20);
}
}


My code is almost working. The problem I'm having is that some of the nodes are overlapping. In the picture above, nodes 25 and 66 are overlapping. The reason, I'm sure, is because its mathematically laying the left nodes and right nodes equal space, so the parent's right node overlaps with the adjacent parent's left node. How can I fix this problem?



UPDATE:



This is the code update I made after dtb's suggestion:



            int nodeWidth = 0;
int rightChildWidth = 0;

if (node.IsLeafNode)
{
nodeWidth = bmp.Width + 50;
}
else
{
int leftChildWidth = 0;

Bitmap bmpLeft = null;
Bitmap bmpRight = null;

if (node.LeftNode != null)
{
bmpLeft =
(from b in _nodeBitmaps where b.Node.Value.Equals(node.LeftNode.Value) select b.Bitmap).
FirstOrDefault();
if (bmpLeft != null)
leftChildWidth = bmpLeft.Width;
}
if (node.RightNode != null)
{
bmpRight =
(from b in _nodeBitmaps where b.Node.Value.Equals(node.RightNode.Value) select b.Bitmap).
FirstOrDefault();
if (bmpRight != null)
rightChildWidth = bmpRight.Width;
}

nodeWidth = leftChildWidth + 50 + rightChildWidth;
}


g.DrawImage(bmp, xOffset + (nodeWidth - bmp.Width) / 2, yOffset);

if (node.LeftNode != null)
{
DrawNode(g, node.LeftNode, xOffset, yOffset + 20);
}
if (node.RightNode != null)
{
DrawNode(g, node.RightNode, xOffset + nodeWidth - rightChildWidth, yOffset + 20);
}


Here is a screenshot from this code: Screen Shot





WPF pie chart - slices not displayed on the chart

I'm trying to use a WPF pie chart. The problem is that only the last slice remains displayed. I can see that all slices are displayed and immediatly hidden except the last one. Any idea ?



<DVC:Chart Margin="25,268,0,0" Title="Pointe de tarte" LegendTitle="Les datas" Background="LightSteelBlue" HorizontalAlignment="Left" VerticalAlignment="Top" Height="324" Width="307">
<DVC:PieSeries Title="Les datas en tarte" Name="Tarte2"
ItemsSource="{StaticResource FruitCollection2}"
IndependentValueBinding="{Binding Path=sss}"
DependentValueBinding="{Binding Path=nnn}" >
</DVC:PieSeries>




private void button3_Click(object sender, RoutedEventArgs e)
{
FruitCollection2 fff = new FruitCollection2();
fff.Clear();
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[0], bbb = 1, ddd = 10, sss = "Item a" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[1], bbb = 2, ddd = 9, sss = "Item b" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[2], bbb = 3, ddd = 11, sss = "Item c" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[3], bbb = 1, ddd = 14, sss = "Item d" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[4], bbb = 4, ddd = 7, sss = "Item e" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[5], bbb = 5, ddd = 1, sss = "Item f" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[6], bbb = 6, ddd = 7, sss = "Item g" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[7], bbb = 3, ddd = 6, sss = "Item h" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[8], bbb = 3, ddd = 7, sss = "Item i" });
fff.Add(new Fruit02 { nnn = this.data001.listeNombres03[9], bbb = 4, ddd = 5, sss = "Item j" });


this.Tarte2.ItemsSource = fff;

}




put formatted output in a file, perl format

If we set a specified format like this. Is there any way that we can copy the output and put it in a file.



ps: when i use strict, it shows "Global symbol "$counter" requires explicit package name at aggregator.pl line 19". What caused this? I have used local to define its scope, so i got a bit confused. Hope someone can give me a reponse. thx a lot



enter code here

# Setup includes
# use strict;
use XML::RSS;
use LWP::UserAgent;
# Declare variables for URL to be parsed
my $url2parse;
# Get the command-line argument
my $arg = shift;
# Create new instance of XML::RSS
my $rss = new XML::RSS;
# Get the URL, assign it to url2parse, and then parse the RSS content
$url2parse = get($arg);
die "Could not retrieve $arg" unless $url2parse;
$rss->parse($url2parse);
#create arrays to hold data
my @titles;
local $counter = 0;

#open file and write .txt output to it
open my $fh, ">output.txt" or die "File creation failed: $!";

# Print the channel items
foreach my $item (@{$rss->{'items'}}) {
$titles[$counter] = $item->{'title'};
&format_output($item->{'title'});
$counter++;
}
sub get {
my $url = shift;
my $ua = LWP::UserAgent->new();
my $res = $ua->get($url);
die ("Could not retrieve $url: " . $res->status_line) unless($res->is_success);
return $res->content;
}

sub format_output {
local($title) = @_;
$~ = "MYFORMAT";
write;
print $fh @_;
}
format MYFORMAT =

=======================
Title :~ ^<<<<<<<<<
$title
=======================
.




runing 32&64-bit java code

I develop a java code that, when running, call CPLEX Optimizer that is 32 bit.
But i will run this code in 64bit.
Do i can run part of program in 64bit and other part in 32bit?





Why it is UDP, not RTP in Wireshark when I stream using jmf?

I want to capture and stream audio using JMF 2.1.1e in RTP format. I wrote a simple transmitter, I can transmit and receive the audio. But when I saw in Wireshark, I saw the packets as UDP. Can anyone point me out the problem, please.



And here is my function responsible for audio capture and transmit.



public void captureAudio(){

// Get the device list for ULAW
Vector devices = captureDevices();

CaptureDeviceInfo captureDeviceInfo = null;

if (devices.size() > 0) {
//get the first device from the list and cast it as CaptureDeviceInfo
captureDeviceInfo = (CaptureDeviceInfo) devices.firstElement();
}
else {
// exit if we could not find the relevant capturedevice.
System.out.println("No such device found");
System.exit(-1);
}


Processor processor = null;
try {
//Create a Processor for the specified media.
processor = Manager.createProcessor(captureDeviceInfo.getLocator());
} catch (IOException ex) {
System.err.println(ex);
} catch (NoProcessorException ex) {
System.err.println(ex);
}
//Prepares the Processor to be programmed.
//puts the Processor into the Configuring state.
processor.configure();

//Wait till the Processor configured.
while (processor.getState() != Processor.Configured){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


//Sets the output content-type for this Processor
processor.setContentDescriptor(CONTENT_DESCRIPTOR);
/**
ContentDescriptor CONTENT_DESCRIPTOR
= new ContentDescriptor(ContentDescriptor.RAW_RTP);
*/

//Gets a TrackControl for each track in the media stream.
TrackControl track[] = processor.getTrackControls();

boolean encodingOk = false;

//searching through tracks to get a supported audio format track.
for (int i = 0; i < track.length; i++) {
if (!encodingOk && track[i] instanceof FormatControl) {
if (((FormatControl)
track[i]).setFormat( new AudioFormat(AudioFormat.ULAW_RTP, 8000, 8, 1) ) == null)
{
track[i].setEnabled(false);
}
else {
encodingOk = true;
track[i].setEnabled(encodingOk);
System.out.println("enc: " + i);
}
} else {
// we could not set this track to ULAW, so disable it
track[i].setEnabled(false);
}
}

//If we could set this track to ULAW we proceed
if (encodingOk){
processor.realize();
while (processor.getState() != Processor.Realized){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

DataSource dataSource = null;
try {
dataSource = processor.getDataOutput();
} catch (NotRealizedError e) {
e.printStackTrace();
}

try {

String url= "rtp://192.168.1.99:49150/audio/1";
MediaLocator m = new MediaLocator(url);
DataSink d = Manager.createDataSink(dataSource, m);
d.open();
d.start();
System.out.println("transmitting...");
processor.start();

} catch (Exception e) {
e.printStackTrace();
}
}
}


And please ask, if you find anything improper or vague.
Thanks in advance. :)



Clarification: I have a peice of C# code for RTP streaming. And when I capture the data using wireshark, I can see them as RTP, but the problem is when I capture the data stream from JMF wireshark show them as UDP. And my question is, why?



I know the difference between UDP and RTP.





zend framework: Creating the Default Module

I did everything as it is written in the book of Vaswani V. - the Zend Framework. A Beginner's Guide (page 33), but the page "http://square.localhost/default/index/index" returns the response "not found". What is wrong?





MySQL taking forever 'sending data'. Simple query, lots of data

I'm trying to run what I believe to be a simple query on a fairly large dataset, and it's taking a very long time to execute -- it stalls in the "Sending data" state for 3-4 hours or more.



The table looks like this:



CREATE TABLE `transaction` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`uuid` varchar(36) NOT NULL,
`userId` varchar(64) NOT NULL,
`protocol` int(11) NOT NULL,
... A few other fields: ints and small varchars
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `uuid` (`uuid`),
KEY `userId` (`userId`),
KEY `protocol` (`protocol`),
KEY `created` (`created`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4 COMMENT='Transaction audit table'


And the query is here:



select protocol, count(distinct userId) as count from transaction
where created > '2012-01-15 23:59:59' and created <= '2012-02-14 23:59:59'
group by protocol;


The table has approximately 222 million rows, and the where clause in the query filters down to about 20 million rows. The distinct option will bring it down to about 700,000 distinct rows, and then after grouping, (and when the query finally finishes), 4 to 5 rows are actually returned.



I realize that it's a lot of data, but it seems that 4-5 hours is an awfully long time for this query.



Thanks.





Programmatically how to know device service type like its CDMA/GSM/GPRS

I am trying to find a code that with help me to find out the device serive-type like CDMA / GSM . I have tried the code below but not helped.



DeviceInfo.getDeviceName();




drawRect see empty array

Button in drawtestViewController.m is linked to pushPoint action in ChalkBoard.m. It populates pointArray with CGpoint objects. This array is full of objects everywhere, except when viewed from drawRect. It seems as from drawRect I'm somehow referencing the empty copy of original array, but I can not find any error ...



I have uploaded the whole project at http://dl.dropbox.com/u/42099382/drawtest.zip






Button action in drawtestViewController.m



- (IBAction)myDo {
NSLog(@"-Button was pressed");
[self.board pushPoint:CGPointMake(100, 100 )];
[self.board pushPoint:CGPointMake(10, 100 )];
[self.graphicView setNeedsDisplay];
}





//  ChalkBoard.h
#import <UIKit/UIKit.h>

@interface ChalkBoard : UIView
-(void)pushPoint:(CGPoint)point;
@property (nonatomic,retain) NSMutableArray *pointArray;
@end





//ChalkBoard.m
#import "ChalkBoard.h"

@implementation ChalkBoard
@synthesize pointArray;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor blackColor];
}
return self;
}

-(NSMutableArray *)pointArray
{
if(pointArray == nil) pointArray = [[NSMutableArray alloc]initWithCapacity:10];
return pointArray;
}

-(void)pushPoint:(CGPoint)point{
// this is called from drawtestViewController.m by button press
// in here the array is full and growing by each button press
[self.pointArray addObject:[NSValue valueWithCGPoint:point]];
NSLog(@"-pushPoint executed, size is %u, array: %@",[self.pointArray count], pointArray);
}

- (void)drawRect:(CGRect)rect{
// here array is always empty
NSLog(@"-DrawRect executed, size is %u, array: %@",[pointArray count], pointArray);
if ([pointArray count] >1){
... some irrelevant code
}
}

@end





NSLog output

2012-04-09 11:34:39.145 drawtest[5260:f803] -DrawRect executed, size is 0, array: (null)
2012-04-09 11:34:41.261 drawtest[5260:f803] -Button was pressed
2012-04-09 11:34:41.262 drawtest[5260:f803] -pushPoint executed, size is 1, array: (
"NSPoint: {100, 100}"
)
2012-04-09 11:34:41.264 drawtest[5260:f803] -pushPoint executed, size is 2, array: (
"NSPoint: {100, 100}",
"NSPoint: {10, 100}"
)
2012-04-09 11:34:41.266 drawtest[5260:f803] -DrawRect executed, size is 0, array: (null)
2012-04-09 11:34:42.825 drawtest[5260:f803] -Button was pressed
2012-04-09 11:34:42.826 drawtest[5260:f803] -pushPoint executed, size is 3, array: (
"NSPoint: {100, 100}",
"NSPoint: {10, 100}",
"NSPoint: {100, 100}"
)
2012-04-09 11:34:42.827 drawtest[5260:f803] -pushPoint executed, size is 4, array: (
"NSPoint: {100, 100}",
"NSPoint: {10, 100}",
"NSPoint: {100, 100}",
"NSPoint: {10, 100}"
)
2012-04-09 11:34:42.829 drawtest[5260:f803] -DrawRect executed, size is 0, array: (null)




Use jQuery to 'reset' functions to make plugins work

I'm using a jQuery image gallery (in this case, FlexSlider) to present several galleries on a page. Only one can be viewed at a time. To accommodate this, I'm using fadeIn/fadeOut after clicking a thumbnail. The problem is the gallery breaks. I've tried several, and they break in different ways. I'm sure there is a way to kind of 'reset' the plugin to keep it from breaking. Here's what I'm doing, which, when presenting multiple sliders on a page, should work according to the site:



jQuery:



<script type="text/javascript" charset="utf-8">
$(window).load(function() {

$('#main-slider').flexslider({
animation:'fade',
directionNav:true,
controlsContainer: ".flex-container"
});

$('#secondary-slider').flexslider({
animation:'fade',
directionNav:true,
controlNav:true,
controlsContainer: ".flex-container"
});

});

$(function(){
$('#main-slider,#secondary-slider').hide();

//1//

$('.gal_icon_1').click(function(){
$('#secondary-slider').fadeOut(function(){
$('#main-slider').fadeIn();
});
});

//2//

$('.gal_icon_2').click(function(){
$('#main-slider').fadeOut(function(){
$('#secondary-slider').fadeIn();
});
});

});
</script>


html:



<div class="container">
<div id="main-slider" class="flexslider">
<ul class="slides">
<li>
<img src="images/BVL_CHANDRA-B_MM_2010_A3.jpg" />
</li>
<li>
<img src="images/BVL_CHANDRA-BLUE_MM_2010_A3.jpg" />
</li>
<li>
<img src="images/BVL_JEWELS_MM_2010_A3.jpg" />
</li>
</ul>
</div>


As to simply fade one slider out and fade the other in. But when I do, it gets wonky. So, again, is there a way to kind of 'reset' the slider to get it to work on each div?





Custom Android EditText not working

I am trying to implement a custom onDraw() method in my EditText.
onDraw is getting called - I can see the log messages, but it is not drawing anything.



Can anyone please tell me what I am doing wrong?



Here is an excerpt from my layout:



    <view xmlns:android="http://schemas.android.com/apk/res/android"
class ="my.package.NotePadEditView"
android:inputType="textMultiLine"
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:background="@android:color/transparent"
android:singleLine="false"
>
<requestFocus/>
</view>
</ScrollView>




Here is the class (just with some test code for now):



public class NotePadEditView extends EditText {
Paint paint = new Paint();
public NotePadEditView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
paint.setColor(0xFF0000);
}
@Override
protected void onDraw(Canvas canvas) {
Log.d("NotePadEditView", "Calling onDraw()"); // These log messages are displaying
canvas.drawLine(0, 0, 50, 50, paint); // just some random stuff so we know when we are done. (Note: these are not displaying - what's up with that???)
canvas.drawText("Hello, World", 30, 30, paint);
super.onDraw(canvas);
}

// more constructors, etc




How to get name of an array

How to get name of an array in c# ??
for example something like :



double[] Pb = new double[100];
Debug.Writeline(Pb[].getName());


so that it prints "Pb"?





how to get the 10 most frequent strings in a list in python

I have a list that has 93 different strings. I need to find the 10 most frequent strings and the return must be in order from most frequent to least frequent.



mylist = ['"and', '"beware', '`twas', 'all', 'all', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'arms', 'as', 'as', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'borogoves', 'borogoves', 'boy', 'brillig']
# this is just a sample of the actual list.