Search Results

Search found 461 results on 19 pages for 'parseint'.

Page 11/19 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Couldn't assign 'top' from variable in jQuery Animate

    - by bhu1st
    Hi, I am stuck here, i am trying to animate number of 'x' divs (the code below is just for one div) by selecting their original 'top' position & adding some 'newTop' pixel values to them. var dur = 1500; var origTop = $("#div_x").position().top; var newTop = parseInt(origTop) + 30; $("#div_x").animate({ top : newTop + "px" }, dur); I checked alerting the 'newTop' variable and it's showing correct values but the animation is not working. I tried different variants to assign 'top' to the animate function but nothing is working. any suggestion would help me a lot. thanks in advance.

    Read the article

  • Javascript large number array compression

    - by gatapia
    Hi All, I've got a javascript application that sends a large amount of numerical data down the wire. This data is then stored in a database. I am having size issues (too much bandwidth, database getting too big). I am now ready to sacrifice some performance for compression. I was thinking of implementing a base 62 number.toString(62) and parseInt(compressed, 62). This would certainly reduce the size of the data but before I go ahead and do this I thought I would put it to the folks here as I know there must be some outside the box solution I have not considered. The basic specs are: - Compress large number arrays into strings for JSONP transfer (So I think UTF is out) - Be relatively fast, look I'm not expecting same performance as I have now but I also don't want gzip compression either. Any ideas would be greatly appreciated. Thanks Guido Tapia

    Read the article

  • How to find the width of the div or check wheather horizontal scroll apeear or not?

    - by Salil
    I want to print the page (div) if there is no horizontal scroll appear for that div. I have a div (1000px) with dynamic data which having property overflow:auto;. So, i want to print the div only if div's width is not getting crossed. to achieve this i used following method of a javascript var curr_width = parseInt(mydiv.style.width); But it gives 1000px; only althogh i can see horizontal scrollbar for the div. What should i do to achive this. Can i check wheather horizontal scrollbar is appear for the div or not. Any help is appreciated. NOTE:- i don't want to use any javascript library.

    Read the article

  • online payment process in radio button

    - by keils
    hi guys im developing in my own website.every thing works fine.i want to know if i clicks the any one of the radio button that value change correspondingly.can any one please post some code i tried this below code. my website is http:spsmobile.co.uk just check the link in this page u just go to phone unlock and click make payment you will see the radio button named pay delivery methods thanks in adv var total = parseInt($("div.total-text").text().substring(1), 10); $("input[name='rmr']").bind('change', function () { var amount = 0; switch (this.value) { case "1": amount = 3; break; case "2": amount = 5.5; break; case "4": amount = 10; break; } $("div.total-text").text("£" + (total + amount)); }); }); $(document).ready(function () { $('#primary').bind('change', function () { $.ajax({ type: "POST", url: "include/unlock_function.php", data: $(this).is(':checked'), success: function (theresponse) {} } } }; } }:

    Read the article

  • remove spaces in string using javascript

    - by reza saberi
    I need to do some functions on some text field contents before submitting the form, like checking the validity of the customer registeration code, having the customer name as his code in customers table appending an incrementing number. I don't want to do it after the form is submitted becuase I need it to be displayed in the code field before submitting the form. My code: function getCode(){ var temp = document.getElementById("temp").value ; var d = parseInt(document.getElementById("temp").value) + 1; document.getElementById("customernumber").value = d; document.getElementById("code").value = document.getElementById("name").value+"-"+ d; } It all works fine, but the last line of code developed the code WITH the spaces between the code.

    Read the article

  • Paging with jQuery

    - by zurna
    I get data from another page using jQuery get method. But I have a small problem. Sometimes, data that I take from another page is too long so it's divided into pages. When the user clicks on 1, 2, 3, ... links he/she is redirected to the other page. However, I want data to be reloaded on the same page. Edit $('ul.thumbs li.pagination a').live('click', function() { var pageNumber = parseInt($(this).text().replace(/[^0-9]/g, '')); $.ajax({ type: "GET", url: "images.cs.asp?Process=ViewImages&PAGEID=<%=Request.QueryString("PAGEID")%>", success: function(data) { $("#ViewImages").html(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#ViewImages").html('.'); } }); return false; });

    Read the article

  • how to represent negative number to array of integers ?

    - by stdnoit
    I must convert string of 1324312321 to array of integers in java this is fine. I could use integer parseint and string substring method but how do I repesent -12312312 to my original array of integer.. the fact that - is a char / string and convert to array of integer would alter the value ( even though I convert - to integer-equivalent , it would change the rest of 12312312) it must be an array of integers and how should I convert negative numbers and still keeep the same value somehow reminding me of two complements trick but i dont think i need to go down to binary level in my program.. any other trick for doing this? thanks!

    Read the article

  • check for a span class content and then update the quantity using jquery?

    - by PD24
    I have code code here: //Check current if (parseInt($("#Quantity").val()) < 25) { // If it is less than 25 then set it to 25 $("#Quantity").attr("value", "25"); } It checks if the quantity box has less than 25 and if it is, adds 25 to the box. The problem is on a particular product i need to check IF my pages contains: <span class="ProductNameText">This is product ABC</span> This is a work around because the customer only has 2 products which dont require 25 quantity. Ideally i would want to check if a page contained Kit Option form fields and then add 25 to the box. Any ideas on how to check for a span and then update the quantity. But the quantity shouldnt be forced, so if the user wants 6 items they should be able to add that figure.

    Read the article

  • Hibernate Save Parent Only

    - by user239905
    Hi, I'm having an issue with Hibernate 3.2.5, where I have to save only the parent object in a one-to-many relationship. For example, I have a flower A, that can have many details. Firstly I want to save only the flower, and the details will be added later. This process throws an exception: not-null property references a null or transient value: com.juflora.bean.JFlora._floraSetBackref This is my code: JFlora flora = new JFlora(); flora.setTypeId(Integer.parseInt(type)); flora.setDescription(description); flora.setName(name); flora.setImage(image); flora.setFloraDetails(new HashSet()); session.save(flora); session.getTransaction().commit();

    Read the article

  • Postfix evaluation in C

    - by Andrewziac
    I’m taking a course in C and we have to make a program for the classic Postfix evaluation problem. Now, I’ve already completed this problem in java, so I know that we have to use a stack to push the numbers into, then pop them when we get an operator, I think I’m fine with all of that stuff. The problem I have been having is scanning the postfix expression in C. In java it was easier because you could use charAt and you could use the parseInt command. However, I’m not aware of any similar commands in C. So could anyone explain a method to read each value from a string in the form: 4 9 * 0 - = Where the equals is the signal of the end of the input. Any help would be greatly appreciated and thank you in advance :)

    Read the article

  • A better and faster way for eval?

    - by user1707250
    I want to build my queries dynamically and use the following snippet: --snip-- module.exports = { get : function(req, res, next) { var queryStr = "req.database.table('locations').get(parseInt(req.params.id))"; if (req.params.id) { if (req.fields) { queryStr += '.pick(' + req.fieldsStr + ')'; } console.log(queryStr); eval(queryStr).run(function(result) { console.log(result); res.send(result); }); } else if (!req.params.id) { --snip-- However introducing eval opens up my code to injection (req.fields is filled with url parameters) and I see the response time of my app increase from 7 to 11ms Is there a smarter way to accomplish what I did here? Please advice.

    Read the article

  • How do I "valueOf" an enum given a class name?

    - by stevemac
    Lets say I have a simple Enum called Animal defined as: public enum Animal { CAT, DOG } and I have a method like: private static Object valueOf(String value, Class<?> classType) { if (classType == String.class) { return value; } if (classType == Integer.class) { return Integer.parseInt(value); } if (classType == Long.class) { return Long.parseLong(value); } if (classType == Boolean.class) { return Boolean.parseBoolean(value); } // Enum resolution here } What can I put inside this method to return an instance of my enum where the value is of the classType? I have looked at trying: if (classType == Enum.class) { return Enum.valueOf((Class<Enum>)classType, value); } But that doesn't work.

    Read the article

  • How do I setup Eclipse to stop on the line an exception occured?

    - by Chris Persichetti
    Hi, How can I setup Eclipse to stop at the point an exception occurred. I have an Eclipse breakpoint setup to break on an exception. In the code example below, the problem I'm having is Eclipse tries to open the Integer source code. Is there any way to just have debugger break at the point shown in my code example? If I move down the stack trace, I will get to this line, it'd be nice if there's a way to do this without the "Source not found" window coming up. This can be done in Visual Studio, so it's driving me crazy not being able to find a way to do this in Eclipse. package com.test; public class QuickTest { public static void main(String[] args) { try { test(); } catch(NumberFormatException e) { System.out.println(e.getMessage()); } } private static void test() { String str = "notAnumber"; Integer.parseInt(str);//<----I want debugger to stop here } }

    Read the article

  • javascript timer fires up on the first key press

    - by pedrag
    I have a html page with a timer in it. I'm starting the timer with the keypress event, but i want it to execute only for the first key. I'm using a variable to catch the total keys in an other function which there were pressed and i have something like that: if(totaAttempts==1) start the timer, but with this solution the timer starts correctly, but is stomps when a key is pressed again. Any better ideas? Thanks in advance function setTime() { if (totalAttempts == 1) { ++totalSeconds; secondsLabel.innerHTML = pad(totalSeconds % 60); minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60)); } } function pad(val) { var valString = val + ""; if (valString.length < 2) { return "0" + valString; } else { return valString; } }

    Read the article

  • Args error in main method for client-server program

    - by socket
    Hi I have a client and server program, all the coding is done and compiles, the client has a GUI and the server is command line. The program uses sockets. But when I run the client to connect to the server it keeps coming with the error message: "Usage: TodoClient []", rather than connecting to the server and starting up. This is where the problem lies: public static void main(String[] args) { TodoClient client; if (args.length > 2 || args.length == 0) { System.err.println("Usage: TodoClient <host> [<port>]"); } else if (args.length == 1) { client = new TodoClient(args[0], DEFAULT_PORT); } else { client = new TodoClient(args[0], Integer.parseInt(args[1])); } } Thank You

    Read the article

  • If statements Evaluations

    - by user2464795
    Using the code below I get this result even though I put in a number that is greater than 18. run: How old are you? 21 You have not reached the age of Majority yet! BUILD SUCCESSFUL (total time: 3 seconds) I am new to java and trying to self learn can anybody help? import java.util.Scanner; public class Chapter8 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner reader = new Scanner (System.in); // TODO code application logic here //Excercise 15 System.out.print("How old are you? "); int x = Integer.parseInt(reader.nextLine()); if (x > 18){ System.out.println("You have not reached the age of Majority yet!"); }else { System.out.println("You have reached the age of Majority!"); }

    Read the article

  • Function Procedure in Java

    - by Lhea Bernardino
    Create a program that will ask the user to enter 3 numbers using for loop, then test the numbers and display it in ascending order. Sample Input: 5 2 7 Sample Output: 2 5 7 I'm stuck with the testing procedure. I don't know how to test the numbers since the variable holding those numbers is just a single variable and inside the for loop here is my sample code: import javax.swing.JOptionPane; public class ascending { public static void main(String args[]) { for(int x= 0; x<3;x++) { String Snum = JOptionPane.showInputDialog("Enter a number"); int num = Integer.parseInt(Snum); } <Here comes the program wherein I will test the 3 numbers inputted by the user and display in ascending order. I don't know where to start. :'( >

    Read the article

  • Java - 2d Array Tile Map Collision

    - by Corey
    How would I go about making certain tiles in my array collide with my player? Like say I want every number 2 in the array to collide. I am reading my array from a txt file if that matters and I am using the slick2d library. Here is my code if needed. public class Tiles { Image[] tiles = new Image[3]; int[][] map = new int[500][500]; Image grass, dirt, mound; SpriteSheet tileSheet; int tileWidth = 32; int tileHeight = 32; public void init() throws IOException, SlickException { tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight); grass = tileSheet.getSprite(0, 0); dirt = tileSheet.getSprite(7, 7); mound = tileSheet.getSprite(2, 6); tiles[0] = grass; tiles[1] = dirt; tiles[2] = mound; int x=0, y=0; BufferedReader in = new BufferedReader(new FileReader("assets/map.txt")); String line; while ((line = in.readLine()) != null) { String[] values = line.split(","); for (String str : values) { int str_int = Integer.parseInt(str); map[x][y]=str_int; //System.out.print(map[x][y] + " "); y=y+1; } //System.out.println(""); x=x+1; y = 0; } in.close(); } public void update() { } public void render(GameContainer gc) { for(int x = 0; x < 50; x++) { for(int y = 0; y < 50; y ++) { int textureIndex = map[y][x]; Image texture = tiles[textureIndex]; texture.draw(x*tileWidth,y*tileHeight); } } } } I tried something like this, but I it doesn't ever "collide". X and y are my player position. if (tiles.map[(int)x/32][(int)y/32] == 2) { System.out.println("Collided"); }

    Read the article

  • Fixing a NoClassDefFoundError

    - by Chris Okyen
    I have some code: package ftc; import java.util.Scanner; public class Fer_To_Cel { public static void main(String[] argv) { // Scanner object to get the temp in degrees Farenheit Scanner keyboard = new Scanner(System.in); boolean isInt = true; // temporarily put as true in case the user enters a valid int the first time int degreesF = 0; // initialy set to 0 do { try { // Input the temperature text. System.out.print("\nPlease enter a temperature (integer number, no fractional part) in degrees Farenheit: "); degreesF = Integer.parseInt(keyboard.next()); // Get user input and Assign the far. temperature variable, which is casted from String to int. } // Let the user know in a user friendly notice that the value entered wasnt an int ( give int value range ) , and then give error log catch(java.lang.Exception e) { System.out.println("Sorry but you entered a non-int value ( needs to be between ( including ) -2,147,483,648 and 2,147,483,647 ).. \n"); e.printStackTrace(); isInt = false; } } while(!isInt); System.out.println(""); // print a new line. final int degreesC = (5*(degreesF-32)/9); // convert the degrees from F to C and store the resulting expression in degreesC // Print out a newline, then print what X degrees F is in Celcius. System.out.println("\n" + degreesF + " degrees Farenheit is " + degreesC + " degrees Celcius"); } } And The following error: C:\Program Files\Java\jdk1.7.0_06\bin>java Fer_To_Cel Exception in thread "main" java.lang.NoClassDefFoundError: Fer_To_Cel (wrong name: ftc/Fer_To_Cel) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:791) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14 at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480) The code compiled without compile errors, but presented errors during execution. Which leads me to two questions. I know Errors can be termed Compiler, Runtime and Logic Errors, but the NoClassDefFoundError inherits java.lang.LinkageError. Does that make it a Linker error, being niether of the three types of errors I listed, If I am right this is the answer. For someone else who obtains the singular .java file and compiles it, would this be the only way to solve this problem? Or can I (should I ) do/have done something to fix this problem? Basically, based on a basis of programming, is this a fault of me as the writer? Could this be done once on, my half and be distributed and not needed be done again?

    Read the article

  • Attach my sprite with Box2d

    - by user919496
    I'm coding Javascript(HTML5) with Box2D. And I want to ask how to attach Sprite with Box2D. This is function My sprite: function My_Sprite() { this.m_Image = new Image(); this.m_Position = new Vector2D(0,0); this.m_CurFrame = 0; this.m_ColFrame = 0; this.m_Size = new Vector2D(0,0); this.m_Scale = new Vector2D(0,0); this.m_Rotation = 0; } My_Sprite.prototype.constructor = function (_Image_SRC) { this.m_Image.src = _Image_SRC; } My_Sprite.prototype.constructor = function (_Image_SRC,_Size,_Col) { this.m_Image.src = _Image_SRC; this.m_Size = _Size; this.m_ColFrame = _Col; this.m_Scale = new Vector2D(1, 1); } My_Sprite.prototype.Draw = function (context) { context.drawImage(this.m_Image, this.m_Size.X * (this.m_CurFrame % this.m_ColFrame), this.m_Size.Y * parseInt(this.m_CurFrame / this.m_ColFrame), this.m_Size.X, this.m_Size.Y, this.m_Position.X, this.m_Position.Y, this.m_Size.X * this.m_Scale.X, this.m_Size.Y * this.m_Scale.Y ); } and this is function Object : function Circle(type, angle, size) { // Circle.prototype = new My_Object(); // Circle.prototype.constructor = Circle; // Circle.prototype.parent = My_Object.prototype; this.m_den = 1.0; this.m_fri = 0.5; this.m_res = 0.2; fixDef.density = this.m_den; fixDef.friction = this.m_fri; fixDef.restitution = this.m_res; fixDef.shape = new b2PolygonShape; bodyDef.type = type; bodyDef.angle = angle; bodyDef.userData = m_spriteCircle; fixDef.shape = new b2CircleShape( Radius / SCALE //radius ); this.m_Body = world.CreateBody(bodyDef); this.m_Body.CreateFixture(fixDef); m_spriteCircle = new My_Sprite(); this.Init(); } Circle.prototype.Init = function () { m_spriteCircle.constructor("images/circle.png", new Vector2D(80, 80), 1); m_spriteCircle.m_CurFrame = 0; } Circle.prototype.Draw = function (context) { m_spriteCircle.Draw(context); } and I draw it : var m_Circle = new Circle(); m_Circle.Draw(context);

    Read the article

  • I get java.lang.NullPointerException when trying to get the contents of the database in Android

    - by ncountr
    I am using 8 EditText boxes from the NewCard.xml from which i am taking the values and when the save button is pressed i am storing the values into a database, in the same process of saving i am trying to get the values and present them into 8 different TextView boxes on the main.xml file and when i press the button i get an FC from the emulator and the resulting error is java.lang.NullPointerException. If Some 1 could help me that would be great, since i have never used databases and this is my first application for android and this is the only thing keepeng me to complete the whole thing and publish it on the market like a free app. Here's the full code from NewCard.java. public class NewCard extends Activity { private static String[] FROM = { _ID, FIRST_NAME, LAST_NAME, POSITION, POSTAL_ADDRESS, PHONE_NUMBER, FAX_NUMBER, MAIL_ADDRESS, WEB_ADDRESS}; private static String ORDER_BY = FIRST_NAME; private CardsData cards; EditText First_Name; EditText Last_Name; EditText Position; EditText Postal_Address; EditText Phone_Number; EditText Fax_Number; EditText Mail_Address; EditText Web_Address; Button New_Cancel; Button New_Save; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.newcard); cards = new CardsData(this); //Define the Cancel Button in NewCard Activity New_Cancel = (Button) this.findViewById(R.id.new_cancel_button); //Define the Cancel Button Activity/s New_Cancel.setOnClickListener ( new OnClickListener() { public void onClick(View arg0) { NewCancelDialog(); } } );//End of the Cancel Button Activity/s //Define the Save Button in NewCard Activity New_Save = (Button) this.findViewById(R.id.new_save_button); //Define the EditText Fields to Get Their Values Into the Database First_Name = (EditText) this.findViewById(R.id.new_first_name); Last_Name = (EditText) this.findViewById(R.id.new_last_name); Position = (EditText) this.findViewById(R.id.new_position); Postal_Address = (EditText) this.findViewById(R.id.new_postal_address); Phone_Number = (EditText) this.findViewById(R.id.new_phone_number); Fax_Number = (EditText) this.findViewById(R.id.new_fax_number); Mail_Address = (EditText) this.findViewById(R.id.new_mail_address); Web_Address = (EditText) this.findViewById(R.id.new_web_address); //Define the Save Button Activity/s New_Save.setOnClickListener ( new OnClickListener() { public void onClick(View arg0) { //Add Code For Saving The Attributes Into The Database try { addCard(First_Name.getText().toString(), Last_Name.getText().toString(), Position.getText().toString(), Postal_Address.getText().toString(), Integer.parseInt(Phone_Number.getText().toString()), Integer.parseInt(Fax_Number.getText().toString()), Mail_Address.getText().toString(), Web_Address.getText().toString()); Cursor cursor = getCard(); showCard(cursor); } finally { cards.close(); NewCard.this.finish(); } } } );//End of the Save Button Activity/s } //======================================================================================// //DATABASE FUNCTIONS private void addCard(String firstname, String lastname, String position, String postaladdress, int phonenumber, int faxnumber, String mailaddress, String webaddress) { // Insert a new record into the Events data source. // You would do something similar for delete and update. SQLiteDatabase db = cards.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(FIRST_NAME, firstname); values.put(LAST_NAME, lastname); values.put(POSITION, position); values.put(POSTAL_ADDRESS, postaladdress); values.put(PHONE_NUMBER, phonenumber); values.put(FAX_NUMBER, phonenumber); values.put(MAIL_ADDRESS, mailaddress); values.put(WEB_ADDRESS, webaddress); db.insertOrThrow(TABLE_NAME, null, values); } private Cursor getCard() { // Perform a managed query. The Activity will handle closing // and re-querying the cursor when needed. SQLiteDatabase db = cards.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY); startManagingCursor(cursor); return cursor; } private void showCard(Cursor cursor) { // Stuff them all into a big string long id = 0; String firstname = null; String lastname = null; String position = null; String postaladdress = null; long phonenumber = 0; long faxnumber = 0; String mailaddress = null; String webaddress = null; while (cursor.moveToNext()) { // Could use getColumnIndexOrThrow() to get indexes id = cursor.getLong(0); firstname = cursor.getString(1); lastname = cursor.getString(2); position = cursor.getString(3); postaladdress = cursor.getString(4); phonenumber = cursor.getLong(5); faxnumber = cursor.getLong(6); mailaddress = cursor.getString(7); webaddress = cursor.getString(8); } // Display on the screen add for each textView TextView ids = (TextView) findViewById(R.id.id); TextView fn = (TextView) findViewById(R.id.firstname); TextView ln = (TextView) findViewById(R.id.lastname); TextView pos = (TextView) findViewById(R.id.position); TextView pa = (TextView) findViewById(R.id.postaladdress); TextView pn = (TextView) findViewById(R.id.phonenumber); TextView fxn = (TextView) findViewById(R.id.faxnumber); TextView ma = (TextView) findViewById(R.id.mailaddress); TextView wa = (TextView) findViewById(R.id.webaddress); ids.setText(String.valueOf(id)); fn.setText(String.valueOf(firstname)); ln.setText(String.valueOf(lastname)); pos.setText(String.valueOf(position)); pa.setText(String.valueOf(postaladdress)); pn.setText(String.valueOf(phonenumber)); fxn.setText(String.valueOf(faxnumber)); ma.setText(String.valueOf(mailaddress)); wa.setText(String.valueOf(webaddress)); } //======================================================================================// //Define the Dialog that alerts you when you press the Cancel button private void NewCancelDialog() { new AlertDialog.Builder(this) .setMessage("Are you sure you want to cancel?") .setTitle("Cancel") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { NewCard.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .show(); }//End of the Cancel Dialog }

    Read the article

  • Refresh Button in java

    - by lakshmi
    I need to make a simple refresh button for a gui java program I have the button made but its not working properly. I just am not sure what the code needs to be to make the button work. Any help would be really appreciated.I figured the code below ` public class CompanySample extends Panel { DBServiceAsync dbService = GWT.create(DBService.class); Panel panel = new Panel(); public Panel CompanySampledetails(com.viji.example.domain.Record trec, int count) { panel.setWidth(800); Panel borderPanel = new Panel(); Panel centerPanel = new Panel(); final FormPanel formPanel = new FormPanel(); formPanel.setFrame(true); formPanel.setLabelAlign(Position.LEFT); formPanel.setPaddings(5); formPanel.setWidth(800); final Panel inner = new Panel(); inner.setLayout(new ColumnLayout()); Panel columnOne = new Panel(); columnOne.setLayout(new FitLayout()); GridPanel gridPanel = null; if (gridPanel != null) { gridPanel.getView().refresh(); gridPanel.clear(); } gridPanel = new SampleGrid(trec); gridPanel.setHeight(450); gridPanel.setTitle("Company Data"); final RowSelectionModel sm = new RowSelectionModel(true); sm.addListener(new RowSelectionListenerAdapter() { public void onRowSelect(RowSelectionModel sm, int rowIndex, Record record) { formPanel.getForm().loadRecord(record); } }); gridPanel.setSelectionModel(sm); gridPanel.doOnRender(new Function() { public void execute() { sm.selectFirstRow(); } }, 10); columnOne.add(gridPanel); inner.add(columnOne, new ColumnLayoutData(0.6)); final FieldSet fieldSet = new FieldSet(); fieldSet.setLabelWidth(90); fieldSet.setTitle("company Details"); fieldSet.setAutoHeight(true); fieldSet.setBorder(false); final TextField txtcompanyname = new TextField("Name", "companyname", 120); final TextField txtcompanyaddress = new TextField("Address", "companyaddress", 120); final TextField txtcompanyid = new TextField("Id", "companyid", 120); txtcompanyid.setVisible(false); fieldSet.add(txtcompanyid); fieldSet.add(txtcompanyname); fieldSet.add(txtcompanyaddress); final Button addButton = new Button(); final Button deleteButton = new Button(); final Button modifyButton = new Button(); final Button refeshButton = new Button(); addButton.setText("Add"); deleteButton.setText("Delete"); modifyButton.setText("Modify"); refeshButton.setText("Refresh"); fieldSet.add(addButton); fieldSet.add(deleteButton); fieldSet.add(modifyButton); fieldSet.add(refeshButton); final ButtonListenerAdapter buttonClickListener = new ButtonListenerAdapter() { public void onClick(Button button, EventObject e) { if (button == refeshButton) { sendDataToServ("Refresh"); } } }; addButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Add")) { sendDataToServer("Add"); } } private void sendDataToServer(String action) { String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { Window.alert("Record not inserted"); } @Override public void onSuccess(String result) { Window.alert("Record inserted"); } }; if (action.trim().equals("Add")) { System.out.println("Before insertServer"); dbService.insertCompany(txtcnameToServer, txtcaddressToServer, ascallback); } } }); deleteButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Delete")) { sendDataToServer("Delete"); } } private void sendDataToServer(String action) { String txtcidToServer = txtcompanyid.getText().trim(); String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (!action.equals("Delete")) { if (txtcidToServer.trim().equals("") || txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } } else if (txtcidToServer.trim().equals("")) { Window.alert("Doesn't deleted any row"); } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub Window.alert("Record not deleted"); } @Override public void onSuccess(String result) { Window.alert("Record deleted"); } }; if (action.trim().equals("Delete")) { System.out.println("Before deleteServer"); dbService.deleteCompany(Integer.parseInt(txtcidToServer), ascallback); } } }); modifyButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Modify")) { sendDataToServer("Modify"); } } private void sendDataToServer(String action) { // TODO Auto-generated method stub System.out.println("ACTION :----->" + action); String txtcidToServer = txtcompanyid.getText().trim(); String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { Window.alert("Record not Updated"); } @Override public void onSuccess(String result) { Window.alert("Record Updated"); } }; if (action.equals("Modify")) { System.out.println("Before UpdateServer"); dbService.modifyCompany(Integer.parseInt(txtcidToServer), txtcnameToServer, txtcaddressToServer, ascallback); } } }); inner.add(new PaddedPanel(fieldSet, 0, 10, 0, 0), new ColumnLayoutData( 0.4)); formPanel.add(inner); borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER)); centerPanel.add(formPanel); panel.add(borderPanel); return panel; } public void sendDataToServ(String action) { AsyncCallback<com.viji.example.domain.Record> callback = new AsyncCallback<com.viji.example.domain.Record>() { @Override public void onFailure(Throwable caught) { System.out.println("Failure"); } public void onSuccess(com.viji.example.domain.Record result) { CompanySampledetails(result, 1); } }; dbService.getRecords(callback); } } class SampleGrid extends GridPanel { private static BaseColumnConfig[] columns = new BaseColumnConfig[] { new ColumnConfig("Name", "companyname", 120, true), new ColumnConfig("Address", "companyaddress", 120, true), }; private static RecordDef recordDef = new RecordDef(new FieldDef[] { new IntegerFieldDef("companyid"), new StringFieldDef("companyname"), new StringFieldDef("companyaddress") }); public SampleGrid(com.viji.example.domain.Record trec) { Object[][] data = new Object[0][];// getCompanyDataSmall(); MemoryProxy proxy = new MemoryProxy(data); ArrayReader reader = new ArrayReader(recordDef); Store store = new SimpleStore(new String[] { "companyid", "companyname", "companyaddress" }, new Object[0][]); store.load(); ArrayList<Company> Companydetails = trec.getCompanydetails(); for (int i = 0; i < Companydetails.size(); i++) { Company company = Companydetails.get(i); store.add(recordDef.createRecord(new Object[] { company.getCompanyid(), company.getCompanyName(), company.getCompanyaddress() })); } store.commitChanges(); setStore(store); ColumnModel columnModel = new ColumnModel(columns); setColumnModel(columnModel); } } `

    Read the article

  • Data not synchornizing java sockets

    - by Droid_Interceptor
    I am writing a auction server and client and using a class called BidHandler to deal with the bids another class AuctionItem to deal with the items for auction. The main problem I am having is little synchroization problem. Screen output of client server as can see from the image at 1st it takes the new bid and changes the value of the time to it, but when one the user enters 1.0 the item seems to be changed to that. But later on when the bid changes again to 15.0 it seems to stay at that price. Is there any reason for that. I have included my code below. Sorry if didnt explain this well. This is the auction client import java.io.*; import java.net.*; public class AuctionClient { private AuctionGui gui; private Socket socket; private DataInputStream dataIn; private DataOutputStream dataOut; //Auction Client constructor String name used as identifier for each client to allow server to pick the winning bidder public AuctionClient(String name,String server, int port) { gui = new AuctionGui("Bidomatic 5000"); gui.input.addKeyListener (new EnterListener(this,gui)); gui.addWindowListener(new ExitListener(this)); try { socket = new Socket(server, port); dataIn = new DataInputStream(socket.getInputStream()); dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF(name); while (true) { gui.output.append("\n"+dataIn.readUTF()); } } catch (Exception e) { e.printStackTrace(); } } public void sentBid(String bid) { try { dataOut.writeUTF(bid); } catch(IOException e) { e.printStackTrace(); } } public void disconnect() { try { socket.close(); } catch(IOException e) { e.printStackTrace(); } } public static void main (String args[]) throws IOException { if(args.length!=3) { throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>"); } int port = Integer.parseInt(args[2]); AuctionClient a = new AuctionClient(args[0],args[1],port); } } The Auction Server import java.io.*; import java.net.*; import java.util.*; public class AuctionServer { public AuctionServer(int port) throws IOException { ServerSocket server = new ServerSocket(port); while(true) { Socket client = server.accept(); DataInputStream in = new DataInputStream(client.getInputStream()); String name = in.readUTF(); System.out.println("New client "+name+" from " +client.getInetAddress()); BidHandler b = new BidHandler (name, client); b.start(); } } public static void main(String args[]) throws IOException { if(args.length != 1) throw new RuntimeException("Syntax: java AuctionServer <port>"); new AuctionServer(Integer.parseInt(args[0])); } } The BidHandler import java.net.*; import java.io.*; import java.util.*; import java.lang.Float; public class BidHandler extends Thread { Socket socket; DataInputStream in; DataOutputStream out; String name; float currentBid = 0.0f; AuctionItem paper = new AuctionItem(" News Paper ", " Free newspaper from 1990 ", 1.0f, false); protected static Vector handlers = new Vector(); public BidHandler(String name, Socket socket) throws IOException { this.name = name; this.socket = socket; in = new DataInputStream (new BufferedInputStream (socket.getInputStream())); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); } public synchronized void run() { try { broadcast("New bidder has entered the room"); handlers.addElement(this); while(true) { broadcast(paper.getName() + paper.getDescription()+" for sale at: " +paper.getPrice()); while(paper.getStatus() == false) { String message = in.readUTF(); currentBid = Float.parseFloat(message); broadcast("Bidder entered " +currentBid); if(currentBid > paper.getPrice()) { paper.setPrice(currentBid); broadcast("New Higgest Bid is "+paper.getPrice()); } else if(currentBid < paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } else if(currentBid == paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } } } } catch(IOException ex) { System.out.println("-- Connection to user lost."); } finally { handlers.removeElement(this); broadcast(name+" left"); try { socket.close(); } catch(IOException ex) { System.out.println("-- Socket to user already closed ?"); } } } protected static void broadcast (String message) { synchronized(handlers) { Enumeration e = handlers.elements(); while(e.hasMoreElements()) { BidHandler handler = (BidHandler) e.nextElement(); try { handler.out.writeUTF(message); handler.out.flush(); } catch(IOException ex) { handler = null; } } } } } The AuctionItem Class class AuctionItem { String itemName; String itemDescription; float itemPrice; boolean itemStatus; //Create a new auction item with name, description, price and status public AuctionItem(String name, String description, float price, boolean status) { itemName = name; itemDescription = description; itemPrice = price; itemStatus = status; } //return the price of the item. public synchronized float getPrice() { return itemPrice; } //Set the price of the item. public synchronized void setPrice(float newPrice) { itemPrice = newPrice; } //Get the status of the item public synchronized boolean getStatus() { return itemStatus; } //Set the status of the item public synchronized void setStatus(boolean newStatus) { itemStatus = newStatus; } //Get the name of the item public String getName() { return itemName; } //Get the description of the item public String getDescription() { return itemDescription; } } There is also simple GUI to go with this that seems to be working fine. If anyone wants it will include the GUI code.

    Read the article

  • Java: Cannot find a method's symbol even though that method is declared later in the class. The remaining code is looking for a class.

    - by Midimistro
    This is an assignment that we use strings in Java to analyze a phone number. The error I am having is anything below tester=invalidCharacters(c); does not compile because every line past tester=invalidCharacters(c); is looking for a symbol or the class. In get invalidResults, all I am trying to do is evaluate a given string for non-alphabetical characters such as *,(,^,&,%,@,#,), and so on. What to answer: Why is it producing an error, what will work, and is there an easier method WITHOUT using regex. Here is the link to the assignment: http://cis.csuohio.edu/~hwang/teaching/cis260/assignments/assignment9.html public class PhoneNumber { private int areacode; private int number; private int ext; /////Constructors///// //Third Constructor (given one string arg) "xxx-xxxxxxx" where first three are numbers and the remaining (7) are numbers or letters public PhoneNumber(String newNumber){ //Note: Set default ext to 0 ext=0; ////Declare Temporary Storage and other variables//// //for the first three numbers String areaCodeString; //for the remaining seven characters String newNumberString; //For use in testing the second half of the string boolean containsLetters; boolean containsInvalid; /////Separate the two parts of string///// //Get the area code part of the string areaCodeString=newNumber.substring(0,2); //Convert the string and set it to the area code areacode=Integer.parseInt(areaCodeString); //Skip the "-" and Get the remaining part of the string newNumberString=newNumber.substring(4); //Create an array of characters from newNumberString to reuse in later methods for int length=newNumberString.length(); char [] myCharacters= new char [length]; int i; for (i=0;i<length;i++){ myCharacters [i]=newNumberString.charAt(i); } //Test if newNumberString contains letters & converting them into numbers String reNewNumber=""; //Test for invalid characters containsInvalid=getInvalidResults(newNumberString,length); if (containsInvalid==false){ containsLetters=getCharResults(newNumberString,length); if (containsLetters==true){ for (i=0;i<length;i++){ myCharacters [i]=(char)convertLetNum((myCharacters [i])); reNewNumber=reNewNumber+myCharacters[i]; } } } if (containsInvalid==false){ number=Integer.parseInt(reNewNumber); } else{ System.out.println("Error!"+"\t"+newNumber+" contains illegal characters. This number will be ignored and skipped."); } } //////Primary Methods/Behaviors/////// //Compare this phone number with the one passed by the caller public boolean equals(PhoneNumber pn){ boolean equal; String concat=(areacode+"-"+number); String pN=pn.toString(); if (concat==pN){ equal=true; } else{ equal=false; } return equal; } //Convert the stored number to a certain string depending on extension public String toString(){ String returned; if(ext==0){ returned=(areacode+"-"+number); } else{ returned=(areacode+"-"+number+" ext "+ext); } return returned; } //////Secondary Methods/////// //Method for testing if the second part of the string contains any letters public static boolean getCharResults(String newNumString,int getLength){ //Recreate a character array int i; char [] myCharacters= new char [getLength]; for (i=0;i<getLength;i++){ myCharacters [i]=newNumString.charAt(i); } boolean doesContainLetter=false; int j; for (j=0;j<getLength;j++){ if ((Character.isDigit(myCharacters[j])==true)){ doesContainLetter=false; } else{ doesContainLetter=true; return doesContainLetter; } } return doesContainLetter; } //Method for testing if the second part of the string contains any letters public static boolean getInvalidResults(String newNumString,int getLength){ boolean doesContainInvalid=false; int i; char c; boolean tester; char [] invalidCharacters= new char [getLength]; for (i=0;i<getLength;i++){ invalidCharacters [i]=newNumString.charAt(i); c=invalidCharacters [i]; tester=invalidCharacters(c); if(tester==true)){ doesContainInvalid=false; } else{ doesContainInvalid=true; return doesContainInvalid; } } return doesContainInvalid; } //Method for evaluating string for invalid characters public boolean invalidCharacters(char letter){ boolean returnNum=false; switch (letter){ case 'A': return returnNum; case 'B': return returnNum; case 'C': return returnNum; case 'D': return returnNum; case 'E': return returnNum; case 'F': return returnNum; case 'G': return returnNum; case 'H': return returnNum; case 'I': return returnNum; case 'J': return returnNum; case 'K': return returnNum; case 'L': return returnNum; case 'M': return returnNum; case 'N': return returnNum; case 'O': return returnNum; case 'P': return returnNum; case 'Q': return returnNum; case 'R': return returnNum; case 'S': return returnNum; case 'T': return returnNum; case 'U': return returnNum; case 'V': return returnNum; case 'W': return returnNum; case 'X': return returnNum; case 'Y': return returnNum; case 'Z': return returnNum; default: return true; } } //Method for converting letters to numbers public int convertLetNum(char letter){ int returnNum; switch (letter){ case 'A': returnNum=2;return returnNum; case 'B': returnNum=2;return returnNum; case 'C': returnNum=2;return returnNum; case 'D': returnNum=3;return returnNum; case 'E': returnNum=3;return returnNum; case 'F': returnNum=3;return returnNum; case 'G': returnNum=4;return returnNum; case 'H': returnNum=4;return returnNum; case 'I': returnNum=4;return returnNum; case 'J': returnNum=5;return returnNum; case 'K': returnNum=5;return returnNum; case 'L': returnNum=5;return returnNum; case 'M': returnNum=6;return returnNum; case 'N': returnNum=6;return returnNum; case 'O': returnNum=6;return returnNum; case 'P': returnNum=7;return returnNum; case 'Q': returnNum=7;return returnNum; case 'R': returnNum=7;return returnNum; case 'S': returnNum=7;return returnNum; case 'T': returnNum=8;return returnNum; case 'U': returnNum=8;return returnNum; case 'V': returnNum=8;return returnNum; case 'W': returnNum=9;return returnNum; case 'X': returnNum=9;return returnNum; case 'Y': returnNum=9;return returnNum; case 'Z': returnNum=9;return returnNum; default: return 0; } } } Note: Please Do not use this program to cheat in your own class. To ensure of this, I will take this question down if it has not been answered by the end of 2013, if I no longer need an explanation for it, or if the term for the class has ended.

    Read the article

  • jQuery FullCalendar - trying to add event and display on calendar failed

    - by Michael Mao
    Hi all: I am trying to work out how to use Adam Shaw's brilliant jQuery plugin - FullCalendar to add an event on our project : online balloon ordering page under development Basically, if you click on "step1" and choose "pickup in shop" , the page will bring you to the calendar view, where you could click on the upper-right corner at the "week" button to alter the view to a weekly basis. What I am trying to achieve is when client clicks on an empty slot in a day, she can create her event on that spot. Here is my code in custom.js: dayClick: function() { var n = parseInt(this.className.match(/fc\-slot(\d+)/)[1]); alert('a day has been clicked on slot ' + n); //trying to add an event using the renderEvent() method. $('#' + type + 'Calendar').fullCalendar('renderEvent', { title : 'my pickup slot', start : new Date(y,m,d, 12, 30), end : new Date(y,m,d, 13, 00), }); } It tries to use the FullCalendar's API method renderEvent so to create such an event. However, although my code runs without error and I can see the prompt saying which slot has been clicked, It wouldn't render such an new event on calendar. Is there another way to do this or my code does something wrong? Any suggestion would be much appreciated, thanks a lot in advance.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >