Hi
I have this array A = <3,2,9,0,7,5,4,8,6,1> and I want to write all its worst partitions are these correct?thanks
a1 = <0,2,9,3,7,5,4,8,6,1>
a2 = <1,9,3,7,5,4,8,6,2>
a3 = <2,3,7,5,4,8,6,9>
a4 = <3,7,5,4,8,6,9>
a5 = <4,5,7,8,6,9>
a6 = <5,7,8,6,9>
a7 = <6,8,7,9>
a8 = <7,8,9>
a9 = <8,9>
a10 = <9>
With signpost 1.2:
String authUrl = provider.retrieveRequestToken( consumer, callbackUrl );
Netflix API response:
<status>
<status_code>
400
</status_code>
<message>
oauth_consumer_key is missing
</message>
</status>
I see how to craft the URL manually via the netflix documentation, but this seems to contradict other services which use OAuth authentication. Who's incorrect, here? Is there a way to get signpost to work with Netflix, aside from contributing to the signpost source? :P
Is it possible to store something like the following using only one table? Right now, what hibernate will do is create two tables, one for Families and one for people. I would like for the familymembers object to be serialized into the column in the database.
@Entity(name = "family")
class Family{
private final List<Person> familyMembers;
}
class Person{
String firstName, lastName;
int age;
}
What is the relation between web.xml and jboss-web.xml? Seems like:
Jboss-web.xml
specifies the security domain (which can be found in login-config.xml)
web.xml
specifies what the security level is
I don't understand what happens when jboss-web.xml specifies a weak security domain. Ie: one that cannot do what web.xml specifies. What happens then?
This code works perfectly in Ubuntu, in Windows and MacOSX, it also works fine with a Nexus-One currently running firmware 2.1.1.
I start sending and listening multicast datagrams, and all the computers and the Nexus-One will see each other perfectly. Then I run the same code on a Droid (Firmware 2.0.1), and everybody will get the packets sent by the Droid, but the droid will listen only to it's own packets.
This is the run() method of a thread that's constantly listening on a Multicast group for incoming packets sent to that group.
I'm running my tests on a local network where I have multicast support enabled in the router.
My goal is to have devices meet each other as they come on line by broadcasting packages to a multicast group.
public void run() {
byte[] buffer = new byte[65535];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
try{
MulticastSocket ms = new MulticastSocket(_port);
ms.setNetworkInterface(_ni); //non loopback network interface passed
ms.joinGroup(_ia); //the multicast address, currently 224.0.1.16
Log.v(TAG,"Joined Group " + _ia);
while (true) {
ms.receive(dp);
String s = new String(dp.getData(),0,dp.getLength());
Log.v(TAG,"Received Package on "+ _ni.getName() +": " + s);
Message m = new Message();
Bundle b = new Bundle();
b.putString("event", "Listener ("+_ni.getName()+"): \"" + s + "\"");
m.setData(b);
dispatchMessage(m); //send to ui thread
}
}
catch (SocketException se) {
System.err.println(se);
}
catch (IOException ie) {
System.err.println(ie);
}
}
Over here, is the code that sends the Multicast Datagram out of every valid network interface available (that's not the loopback interface).
public void sendPing() {
MulticastSocket ms = null;
try {
ms = new MulticastSocket(_port);
ms.setTimeToLive(TTL_GLOBAL);
List<NetworkInterface> interfaces = getMulticastNonLoopbackNetworkInterfaces();
for (NetworkInterface iface : interfaces) {
//skip loopback
if (iface.getName().equals("lo"))
continue;
ms.setNetworkInterface(iface);
_buffer = ("FW-"+ _name +" PING ("+iface.getName()+":"+iface.getInetAddresses().nextElement()+")").getBytes();
DatagramPacket dp = new DatagramPacket(_buffer, _buffer.length,_ia,_port);
ms.send(dp);
Log.v(TAG,"Announcer: Sent packet - " + new String(_buffer) + " from " + iface.getDisplayName());
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e2) {
e2.printStackTrace();
}
}
Update (April 2nd 2010)
I found a way to have the Droid's network interface to communicate using Multicast!
_wifiMulticastLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).createMulticastLock("multicastLockNameHere");
_wifiMulticastLock.acquire();
Then when you're done...
if (_wifiMulticastLock != null && _wifiMulticastLock.isHeld())
_wifiMulticastLock.release();
After I did this, the Droid started sending and receiving UDP Datagrams on a Multicast group.
gubatron
My DAO detaches and then caches certain objects, and it may retrieve them with different fetch groups. Depending on which fetch group was used to retrieve the object, certain fields of that object may be available, or not. I would like to be able to test whether a given field on that object was loaded or not, but I can't simply check whether the field is null because that results in a "JDODetachedFieldAccessException" which demands that I either not access the field or add detach the field first.
I could always catch that exception, but that doesn't smell right. So, does anyone know whether its possible to check if the field was detached?
Hi you all,
I'm trying to do this contest exercise about graphs:
XPTO is an intrepid adventurer (a little too temerarious for his own good) who boasts about exploring every corner of the universe, no matter how inhospitable. In fact, he doesn't visit the planets where people can easily live in, he prefers those where only a madman would go with a very good reason (several millions of credits for instance). His latest exploit is trying to survive in Proxima III. The problem is that Proxima III suffers from storms of highly corrosive acids that destroy everything, including spacesuits that were especially designed to withstand corrosion.
Our intrepid explorer was caught in a rectangular area in the middle of one of these storms. Fortunately, he has an instrument that is capable of measuring the exact concentration of acid on each sector and how much damage it does to his spacesuit. Now, he only needs to find out if he can escape the storm.
Problem
The problem consists of finding an escape route that will allow XPTOto escape the noxious storm. You are given the initial energy of the spacesuit, the size of the rectangular area and the damage that the spacesuit will suffer while standing in each sector.
Your task is to find the exit sector, the number of steps necessary to reach it and the amount of energy his suit will have when he leaves the rectangular area. The escape route chosen should be the safest one (i.e., the one where his spacesuit will be the least damaged). Notice that Rodericus will perish if the energy of his suit reaches zero.
In case there are more than one possible solutions, choose the one that uses the least number of steps. If there are at least two sectors with the same number of steps (X1, Y1) and (X2, Y2) then choose the first if X1 < X2 or if X1 = X2 and Y1 < Y2.
Constraints
0 < E = 30000 the suit's starting energy
0 = W = 500 the rectangle's width
0 = H = 500 rectangle's height
0 < X < W the starting X position
0 < Y < H the starting Y position
0 = D = 10000 the damage sustained in each sector
Input
The first number given is the number of test cases. Each case will consist of a line with the integers E, X and Y. The following line will have the integers W and H. The following lines will hold the matrix containing the damage D the spacesuit will suffer whilst in the corresponding sector. Notice that, as is often the case for computer geeks, (1,1) corresponds to the upper left corner.
Output
If there is a solution, the output will be the remaining energy, the exit sector's X and Y coordinates and the number of steps of the route that will lead Rodericus to safety. In case there is no solution, the phrase Goodbye cruel world! will be written.
Sample Input
3
40 3 3
7 8
12 11 12 11 3 12 12
12 11 11 12 2 1 13
11 11 12 2 13 2 14
10 11 13 3 2 1 12
10 11 13 13 11 12 13
12 12 11 13 11 13 12
13 12 12 11 11 11 11
13 13 10 10 13 11 12
8 3 4
7 6
4 3 3 2 2 3 2
2 5 2 2 2 3 3
2 1 2 2 3 2 2
4 3 3 2 2 4 1
3 1 4 3 2 3 1
2 2 3 3 0 3 4
10 3 4
7 6
3 3 1 2 2 1 0
2 2 2 4 2 2 5
2 2 1 3 0 2 2
2 2 1 3 3 4 2
3 4 4 3 1 1 3
1 2 2 4 2 2 1
Sample Output
12 5 1 8
Goodbye cruel world!
5 1 4 2
Basically, I think we have to do a modified Dijkstra, in which the distance between nodes is the suit's energy (and we have to subtract it instead of suming up like is normal with distances) and the steps are the ....steps made along the path. The pos with the bester binomial (Energy,num_Steps) is our "way out".
Important : XPTO obviously can't move in diagonals, so we have to cut out this cases.
I have many ideas, but I have such a problem implementing them...
Could someone please help me thinking about this with some code or, at least, ideas?
Am I totally wrong?
And its not '&'
Im using the SAXParser object do parse the actual XML.
This is normally done by passing a URL to the XMLReader.Parse method.
Because my XML is coming from a POST request to a webservice, I am saving that result as a String and then employing StringReader / InputSource to feed this string back to the XMLReader.Parse method.
However, something strange is happening at the 2001st character of the XMLstring.
The 'characters' method of the document handler is being called TWICE in between the startElement and endElement methods, effectively breaking my string (in this case a project title) into two pieces. Because I am instantiating objects in my characters method, I am getting two objects instead of one.
This line, about 2000 chars into the string fires 'characters' two times, breaking between "Lower" and "Level"
<title>SUMC-BOOKSTORE, LOWER LEVEL RENOVATIONS</title>
When I bypass the StringReader / InputSource workaround and feed a flat XML file to XMLReader.Parse, it works absolutely fine.
Something about StringReader and or InputSource is somehow screwing this up.
Here is my method that takes and XML string and parses is through the SAXParser.
public void parseXML(String XMLstring) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
// Something is happening in the StringReader or InputSource
// That cuts the XML element in half at the 2001 character mark.
StringReader sr = new StringReader(XMLstring);
InputSource is = new InputSource(sr);
xr.parse(is);
} catch (IOException e) {
Log.e("CMS1", e.toString());
} catch (SAXException e) {
Log.e("CMS2", e.toString());
} catch (ParserConfigurationException e) {
Log.e("CMS3", e.toString());
}
}
I would greatly appreciate any ideas on how to not have 'characters' firing off twice when I get to this point in the XML String.
Or, show me how to use a POST request and still pass off the URL to the Parse function.
THANK YOU.
First of all let me say that this questions is slightly connected to another question by me. Actually it was created because of that.
I have the following code to write a bitmap downloaded from the net to a file in the sd card:
// Get image from url
URL u = new URL(url);
HttpGet httpRequest = new HttpGet(u.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
Bitmap bmImg = BitmapFactory.decodeStream(instream);
instream.close();
// Write image to a file in sd card
File posterFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/com.myapp/files/image.jpg");
posterFile.createNewFile();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(posterFile));
Bitmap mutable = Bitmap.createScaledBitmap(bmImg,bmImg.getWidth(),bmImg.getHeight(),true);
mutable.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// Launch default viewer for the file
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(posterFile.getAbsolutePath()),"image/*");
((Activity) getContext()).startActivity(intent);
A few notes. I am creating the "mutable" bitmap after seeing someone using it and it seems to work better than without it. And i am using the parse method on the Uri class and not the fromFile because in my code i am calling these in different places and when i am creating the intent i have a string path instead of a file.
Now for my problem. The file gets created. The intent launches a dialog asking me to select a viewer. I have 3 viewers installed. The Astro image viewer, the default media gallery (i have a milstone on 2.1 but on the milestone the 2.1 update did not include the 3d gallery so it's the old one) and the 3d gallery from the nexus one (i found the apk in the wild).
Now when i launch the 3 viewers the following happen:
Astro image viewer: The activity
launches but i see nothing but a
black screen.
Media Gallery: i get an exception
dialog shown "The application Media
Gallery (process
com.motorola.gallery) has stopped
unexpectedly. Please try again" with
a force close option.
3D gallery: Everything works as it
should.
When i try to simply open the file using the Astro file manager (browse to it and simply click) i get the same option dialog but this time things are different:
Astro image viewer: Everything works
as it should.
Media Gallery: Everything works as it
should.
3D gallery: The activity launches but
i see nothing but a black screen.
As you can see everything is a complete mess. I have no idea why this happens but it happens like this every single time. It's not a random bug.
Am i missing something when i am creating the intent? Or when i am creating the image file? Any ideas?
Hello everybody,
I have some problem's with a simple application in JSF 2.0.
I try to build a ToDo List with ajax support. I have some todo strings which I display using a datatable. Inside this datatable I have a commandLink to delete a task. The problem is now that the datatable don't get re-rendered.
<h:dataTable id="todoList" value="#{todoController.todos}" var="todo">
<h:column>
<h:commandLink value="X" action="#{todoController.removeTodo(todo)}">
<f:ajax execute="@this" render="todoList" />
</h:commandLink>
</h:column>
<h:column>
<h:outputText value="#{todo}"/>
</h:column>
</h:dataTable>
Thanks for your help.
Edit (TodoController):
@ManagedBean
@SessionScoped
public class TodoController {
private String todoStr;
private ArrayList<String> todos;
public TodoController() {
todoStr="";
todos = new ArrayList<String>();
}
public void addTodo() {
todos.add(todoStr);
}
public void removeTodo(String deleteTodo) {
todos.remove(deleteTodo);
}
/* getter / setter */
}
I used HTTPComponents to implement a custom web server that access SQLite database. Requests are sent via TCP/IP and I am using REST concepts. By the way my frontend is HTML/jQuery. I know it will be a lot easier if I'll just create a servlet but I am restricted to just using apache http server.
I really don't get good performance in using HTTP Components.
Any suggestions please.
Thanks in advance.
Basically I'm wondering how I'm able to do what I've written in the topic. I've looked through many tutorials on AsyncTask but I can't get it to work. I have a little form (EditText) that will take what the user inputs there and make it to a url query for the application to lookup and then display the results.
What I think would seem to work is something like this: In my main activity i have a string called responseBody. Then the user clicks on the search button it will go to my search function and from there call the GrabUrl method with the url which will start the asyncdata and when that process is finished the onPostExecute method will use the function activity.this.setResponseBody(content).
This is what my code looks like simpliefied with the most important parts (I think).
public class activity extends Activity {
private String responseBody;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
public void initControls() {
fieldSearch = (EditText) findViewById(R.id.EditText01);
buttonSearch = (Button)findViewById(R.id.Button01);
buttonSearch.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ search();
}});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, String> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private boolean error = false;
private ProgressDialog dialog = new ProgressDialog(activity.this);
protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = true;
cancel(true);
} catch (IOException e) {
error = true;
cancel(true);
}
return content;
}
protected void onPostExecute(String content) {
dialog.dismiss();
if (error) {
Toast toast = Toast.makeText(activity.this, getString(R.string.offline), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 75);
toast.show();
} else {
activity.this.setResponseBody(content);
}
}
}
public void search() {
String query = fieldSearch.getText().toString();
String url = "http://example.com/example.php?query=" + query; //this is just an example url, I have a "real" url in my application but for privacy reasons I've replaced it
grabURL(url); // the method that will start the asynctask
processData(responseBody); // process the responseBody and display stuff on the ui-thread with the data that I would like to get from the asyntask but doesn't obviously
}
Hi There!
I have a design problem .
My application has multiple J2EE components ,In simple terms one acts as a service provider(Non UI) and others are consumers(UI webapp) .
The consumer gets the configuration data from the service provider(this basically reads the data from DB) during the start up and stores it in the Cache.
The cache gets refreshed after periodic time to reflect any changes done at the database.
The Problem
Apart from the cache refresh ,I also want to notify the consumers when someone changes the DB . that configuration has been changed please reload it.
What notification mechanism's can I use to achieve this.
Thanks!
Pratik
i write a method and when i add some insignificant code it works faster,
like these :
array[1]=array[1];
array[0]=array[0];
array[3]=array[3];
array[2]=array[2];
i use double t=System.currentTimeMillis(); at first to record the time.
then call the method
and use System.out.println(System.currentTimeMillis()-t); in the end.
when i delete the code (array[1]=array[1];...) the cost time is 1035.0 ms,but if i add these code,
the cost time become 898.0ms.
here is my method and my code. PS:this method is use for the game 2048, exp: {2,2,2,2} trans to {0,0,4,4}
static void toRight2(int[] array){
if (array[2]==array[3] ) {
array[3]=array[2]*2;
if (array[0]==array[1]) {
array[2]=array[1]*2;
array[0]=0;
array[1]=0;
}else {
array[2]=array[1];
array[1]=array[0];
array[0]=0;
}
} else{
if (array[0]==array[1]) {
array[1]=array[1]*2;
array[0]=0;
array[3]=array[3];
array[2]=array[2];
}else {
array[1]=array[1];//delete this cost more time
array[0]=array[0];//delete this cost more time
array[3]=array[3];//delete this cost more time
array[2]=array[2];//delete this cost more time
}
}
}
public static void main(String[] args) {
double t=System.currentTimeMillis();
int[] array={1,2,3,3};
for (int j = 2; j <400*1000000; j++) {
toRight2(array);
}
System.out.println(System.currentTimeMillis()-t);
}
Hi
I have a special requirement for one of my applications where I need the servers nounce (Handshaker.srv_random) when verifying the client certificate.
Yet JSSEs X509TrustManager only passes me the certificate, no other information of the handshake.
I have located the place, where checkClientTrusted is called (inside ServerHandshaker) and it would be easy to extend it to also allow some X509CustomTrustManager to be called with all required information. Yet this would require me to recompile JSSE...
I also found jsse sources in openjdk.
Now for my questions:
What is the easiest way to compile jsse from openjdk?
Can the resulting jsse.jar be used as a replacement for the (original) sun jre as a replacement for the included jsse.jar?
Is there another (more standard compliant) way to archive what I am trying to do? I did not find a hook to use my own handshaker...
Regards,
Steffen
In their real life, are Object Oriented Programmers more forgetting than Structured Language Programmers. I personally feel that way being a an Object Oriented Programmer.
I have problem with I18N in JSP, specifically, with forms.
When I enter some Czech characters (e.g., "ešcržýá...") into my page one form, into the field "fieldOne", and then show text from that field on page two, instead of Czech characters I see this as "ÄÄ". (Note, the second page gets the Czech characters with "request.getProperty("fieldOne")")
Here is the source code:
Page one:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<html>
<head></head>
<body>
<form action="druha.jsp" method="post">
<input type="textarea" name="fieldOne">
<input type="submit">
</form>
</body>
</html>
Page two:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<html>
<head></head>
<body>
<h1>The text: </h1> <%=request.getProperty("fieldOne")%>
</body>
</html>
Thanks for help...
interfaces provide a useful abstraction capability. One can have a class Foo implement some interfaces, say A, B, and C. Some client code may get a reference of type A, others one of type B, etc. each actually the same Foo object but the interface exposing only a narrow subset of the functionality. Of course, evil client code can try to cast the A reference to Foo, then access the other functionality.How to prevent this?
Hi All !
I have hashmap and its keys are like "folder/1.txt,folder/2.txt,folder/3.txt" and value has these text files data.
Now i am stucked. I want to sort this list. But it does not let me do it :(
Here is my hashmap data type:
HashMap<String, ArrayList<String>>
following function work good but it is for arraylist not for hashmap.
Collections.sort(values, Collections.reverseOrder());
I also tried MapTree but it also didn't work, or may be I couldn't make it work. I used
following steps to sort the code with maptree
HashMap testMap = new HashMap();
Map sortedMap = new TreeMap(testMap);
any other way to do it??
I have one doubt as my keys are (folder/1.txt, folder/2.txt ) may be that's why?
I've got a stream of incoming data that I would like to plot using a simple histogram. I don't know the range of values, or the proper resolution or bin width to use for the histogram.
SimpleHistogramDataset provides some of this functionality, but I don't want to have to deal with catching exceptions in order to add new bins if the new value isn't covered. In addition, it doesn't easily allow me to rebuild the histogram using a different bin width (perhaps an integer multiples of some initial set width).
Is there an easy way to accomplish this with JFreeChart or some alternate charting library, or am I going to have to write my own class here?
When there is a network problem which results in the client being disconnected from the JMS server, is there some other way to detect the problem other than waiting until the next JMS message being sent fails?