Tuesday, May 22, 2012

Why doesn't VC++ 2010 Express require stdio.h in this program but gcc++ does?

I have the following code



#include <iostream>

using namespace std;

void WaitForEnter()
{
while(1)
{
if('\n' == getchar())
{
break;
}
}
}

int main()
{
cout<< "Press Enter to Exit... ";
WaitForEnter();
}


This compiles on Microsoft Visual C++ 2010 Express and does what I expected. On Ubuntu using code::blocks and gcc++ 4.7 the build fails with the following error: 'getchar' was not declared in this scope. If I add the line #include "stdio.h", the program compiles and runs with the expected behavior. Why does this program compile using MVC++ 2010 Express without stdio.h but not for code::blocks with gcc++ 4.7 on Ubuntu.





How can a web shared local html file be opened via Safari?

From system preferences/Internet & Wireless/Sharing I selected Web Sharing then clicked on Open Personal Website Folder, and there is an existing index.html file there with address



http://my ip address/~myusername/sites/index.html if online or if offline then
http://MacBook-Pro/~myusername/sites/index.html


But if I try to open these URLs from Safari it doesn't work, perhaps as expected if using the http scheme, so I tried with file:// instead but it says



"No file exists at "/~myusername/sites/index.html". But the file does exist there, I can see it.



Are there some tricks involved in getting Safari to see this file?





GetElementsByTagName alternative to DOMDocument

I am creating an HTML file with DOMDocument, but I have a problem at the time of the search by the getElementsByTagName method. What I found is that as I'm generating the hot, does not recognize the labels that I inserted.



I tried with DOMXPath, but to no avail :S



For now, I've got to do is go through all the children of a node and store in an array, but I need to convert that score DOMNodeList, and in doing



return (DOMNodeList) $ my_array;


generates a syntax error.



My specific question is, how I can do to make a search for tags with the getElementsByTagName method or other alternative I can offer to achieve the task?



Recalling that the DOMDocument I'm generating at the time.



If you need more information, I'll gladly place it in the question.



Sure Jonathan Sampson.



I apologize for the editing of the question the way. I did not quite understand this forum format.



For a better understanding of what I do, I put the inheritance chain.



I have this base class



abstract class ElementoBase {
...
}


And I have this class that inherits from the previous one, with an abstract function insert (insert)



abstract class Elemento extends ElementoBase {
...
public abstract function insertar ( $elemento );
}


Then I have a whole series of classes that represent the HTML tags that inherit from above, ie.



class A extends Elemento {
}
...


Now the code I use to insert the labels in the paper is as follows:



public function insertar ( $elemento ) {

$this->getElemento ()->appendChild ( $elemento->getElemento () );
}


where the function getElemento (), return a DOMElement



Moreover, before inserting the element do some validations that depend on the HTML tag that is to be inserted,
because they all have very specific specifications.



Since I'm generating HTML code at the same time, it is obvious that there is no HTML file.



To your question, the theory tells me to do this:



$myListTags = $this->getElemento ()->getElementsByTagName ( $tag );


but I always returns null, this so I researched it because I'm not loading the HTML file, because if I



$myHtmlFile = $this->getDocumento ()->loadHTMLFile ( $filename );
$myListTags = $myHtmlFile->getElementsByTagName ( $etiqueta );


I do return the list of HTML tags



If you need more information, I'll gladly place it in the question.





Understandable explanation to a simple file writer?

I have been looking around the internet for a long time and i STILL havent found a sensible answer as to making a program that creates a file in a directory (Such as C:). So if you could please explain to me how i would do this it would be greatly appreciated! Thanks!
EDIT-Im using java and i want to write a text document. Probably should have said that before :/





TestFlight build, network calls don't work

This is driving me batty. I've used TestFlight on a few occasions with great success, but this time around I'm having issues.



The archive works, uploads to TestFlight just fine, installs to the target device just fine, but my network calls NEVER execute. E.G. You never see any network activity from the device and watching the backend the calls never arrive.



Debug builds on the same device work as expected.





Java Script code not running well on ie9

I have this code it suppose to display an ad for 10 seconds then load a embed code.
the thing is that it's working fine on firefox but not ie 9 it's run the ad and the embed code in the same time in the background.
Is there is anyway to resolve this problem.
the code is attached.
thank you



<script type="text/javascript">
var nbsec=10;
var c=0;
var t;
var timer_is_on=0;
var sum=0;
function timedCount()
{
c=c+1;
t=setTimeout("timedCount()",1000);
sum=nbsec-c;
document.getElementById('chrono').innerHTML="<br>Loading .. Please wait "+sum+"secondes";
if(c == nbsec){
stopCount();
document.getElementById('mypub').style.visibility = 'hidden';
document.getElementById('mygame').style.visibility = 'visible';
document.getElementById('mygame').style.display ='block';
document.getElementById('mygame').style.height = 'auto';
document.getElementById('mypub').style.height = '0px';
document.getElementById('mypub').style.padding = '0px';
document.getElementById('mypub').innerHTML="";
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>

<table border ="2" align="center" color="F2FC7E"><tr><td>
<div id="mypub" style="visibility: visible; text-align:center; padding:20px;">

<script>
..............
</script>

<div id="chrono" style="color:#FFF;"></div>
</div>
<div id="mygame" style="visibility: hidden;display:none; height:0px">
<param name="initial_focus" value="true">
<applet>
........................
</applet>
</div>
</td></tr></table>
</div>
<script type="text/javascript">
timedCount();
</script>




accessing vars inside a js function

So I have a psudo "Class" with functions and vars inside of it
for this question I'll just use an example:



function MyClass()
{
this.a = 0;
this.b = function(c)
{
this.a += c;
}
}


then when I go to use it later i'll do this:



var myObject = new MyClass();
myObject.b(3);
myObject.b(5);


but when I do this:



console.log("A: " + myObject.a);


I get:



A: 0


What am I doing wrong?





How to make CSS compatible with all browsers?

Basically what I mean is which CSS fields need "-moz-" and "-webkit" in front of them for them to work? I know "border-radius" and "box-shadow" do, but can anyone tell me all of them? Thanks a lot in advanced.





How to reuse JSON Object

Scenario:



The MVC web page gets JSON object with lots of data. Upon click of button (there are quiet a number of buttons) I would like to reuse this JSON object and select required JSON Properties (without making a request to server).



It's not HTML5 so can't use browser local storage. At the moment I'm storing the JSON object on GLOBAL variable and reusing it.



Are there any elegant options available to store and re-use returned JSON object on client side?





NSCache getting released randomly

so I had a category of NSCache:



@interface NSCache (SharedCache)
+(NSCache*)sharedCache;
@end

#import "NSCache+SharedCache.h"

@implementation NSCache (SharedCache)
+(NSCache*)sharedCache;
{
static NSCache* sharedCache = nil;
if (sharedCache == nil) {
sharedCache = [[self alloc] init];
[sharedCache setCountLimit:0];
}
return sharedCache;
}

@end


However ocasionnaly this gets deallocated and therefore my app crashes. If I retain sharedCache this problem is solved. What is the best way to have a shared NSCache to void crashes that it gets deallocated randomly?





Possible to initialize static variable by calling function

Is this possible?



static bool initialize()
{
TRC_SCOPE_INIT(...);
...
}

static bool initialized = initialize();


To make a very long story short, I need to call a series of macros (to initialize debugging messages) as early as possible (before thread X is started, and I don't have the ability to know when thread X is started).





Parsing html with Jsoup and removing spans with certain style

I'm writing an app for a friend but I ran into a problem, the website has these



<span style="display:none">&amp;0000000000000217000000</span>


And we have no idea even what they are, but I need them removed because my app is outputting their value.



Is there any way I can check to see if this is in the Elements and remove it? I have a for-each loop parsing however I cant figure out how to effectively remove this element.



thanks





Default value for height and width of components in UIPickerView

What is the default value of the height and width of the components in UIPickerView? ie., what is the value that iOS uses as height and width for the below, if the application has not implemented these methods?



pickerView:widthForComponent:
pickerView:rowHeightForComponent:


I tried the suggestion from the thread :
What is the default width of a UIPickerView component?
But that would give an array out of bound exception:



Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'


Any help appreciated.





Make persistent changes to init.rc

I want to change the init.rc file of an android pad. But after I change it and reboot the system, the original init.rc comes back.



How can I make the change to the init.rc persistently without rebuild the system (since I don't have the source code of the system)? Or is there any way to work around?





Difficulty parsing a double - String

Thanks for taking the time to answer my question.



I have a double value (let's say 22.35). I need to parse it into a String and get 2235. The following code is not working properly.



double totalPrice = 22.35;
DecimalFormat df = new DecimalFormat("#.##");
String[] temp = df.format(totalPrice).split(".");
String amount = temp[0] + temp[1];


I keep getting an exception ArrayIndexOutOfBounds. What is another way to do this? Thanks in advance!





Viewing database records realtime in WPF application

disclaimer: I must use a microsoft access database and I cannot connect my app to a server to subscribe to any service.



I am using VB.net to create a WPF application. I am populating a listview based on records from an access database which I query one time when the application loads and I fill a dataset. I then use LINQ to dataset to display data to the user depending on filters and whatnot.



However.. the access table is modified many times throughout the day which means the user will have "old data" as the day progresses if they do not reload the application. Is there a way to connect the access database to the VB.net application such that it can raise an event when a record is added, removed, or modified in the database? I am fine with any code required IN the event handler.. I just need to figure out a way to trigger a vb.net application event from the access table.



Think of what I am trying to do as viewing real-time edits to a database table, but within the application.. any help is MUCH appreciated and let me know if you require any clarification - I just need a general direction and I am happy to research more.



My solution idea:




  • Create audit table for ms access change

  • Create separate worker thread within the users application to query
    the audit table for changes every 60 seconds

  • if changes are found it will modify the affected dataset records

  • Raise event on dataset record update to refresh any affected
    objects/properties





GetAsyncKeyState() very CPU heavy? Am I using it correctly?

I am using GetAsyncKeyState() in a simple pong game of mine to check if the user has pressed the arrow keys. I read online that you need to use this function a certain way however I found out that it is very CPU heavy (using 50% of my CPU!). This was rather disconcerting, however, after some playing around I found out that if I added a sleep(1); then the CPU usage went down to 0% and everything still worked fine. There must be a better way of using this function or at least a better way of lowering CPU usage.



Any help here would be much appreciated!



My Code:



while(true)
{
for(i = 8; i < 191; ++i)
{
if(GetAsyncKeyState(i) == -32767)
{
if(i == VK_LEFT)
// do stuff
else if(i == VK_RIGHT)
// do stuff
else if(i == VK_UP)
// do stuff
else if(i == VK_DOWN)
// do stuff
}
}
Sleep(1);
}




jquery + hotkeys - supress open file dialog

i just discovered the jquery hotkeys plugin for adding global hotkeys.
i would like to use the ctrl-o hotkey for own purposes, unfortunately firefox keeps displaying the open file dialog. i've tried return false and stopPropagation within my bind function but unfortunately didn't help.
any ideas how to supress the browser's open file dialog?
thanks





Two Foreign Keys in one Column. How to split?

I have the following situation.



Combinations Table:

Combination ID | Option ID's


Options Table:

Option ID | Option Name | Option Value



The "Option ID's" column in the combinations table reads like "2345,3421" (in the one column) when refering to the two options associated to the combination.



Is it possible to generate a list that lists all possible combinations and values for each combination?



ie. combination1 | option1 | name:size | value:Small | option2 | name:color | value:Blue





Add mailto link to static email with JQuery

I'm trying to add a mailto link to static email addresses found within a list of results from a database, using JQuery. I was able to find the following excerpt online which works for the first result, but it does not work for any email addresses after the first one.



I'm curious why this is.. and how I can get it to apply the mailto: attribute to every email address found in the results. :-)



Current code:



<script type="text/javascript">
$(document).ready(function(){
var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;
$("table td").filter(function() {
return $(this).html().match(regEx);
}).each(function() {
$(this).html($(this).html().replace(regEx, "<a href=\"mailto:$1\">$1</a>"));
});
});




Thanks!





HTML5 and a Decibel meter

Is there anyway using HTML5 and Javascript to capture audio and get the live Decibel value of it? Can this be done on mobile devices using PhoneGap?





Debugging Rails with Passanger and Apache

Some of the threads I was following seem old, so maybe what I am trying to do has been superseded by something else--if that is the case, please let me know!



I just reinstalled a Rails app on a new server, but this time am using Apache and Passenger. Rails version 1.8.7, Apache2, and Passenger on a Ubuntu 12.04 server. I would like to still have a debugger, so I tried following this thread:



http://chrisadams.me.uk/2009/04/28/how-to-set-up-a-debugger-with-mod_railspassenger/
http://duckpunching.com/passenger-mod_rails-for-development-now-with-debugger
(the original article)



I'm pretty sure I followed this exactly, and my files are correct. But I am getting two discrepencies. First, when I refresh my webpage, my site does not hang (as stated on the duckpunching page)...second, when I put in:



rdebug -c


I get the following error:



/usr/lib/ruby/gems/1.8/gems/ruby-debug-0.10.4/cli/ruby-debug.rb:109:in initialize': Connection refused - connect(2) (Errno::ECONNREFUSED)
from /usr/lib/ruby/gems/1.8/gems/ruby-debug-0.10.4/cli/ruby-debug.rb:109:in
new'
from /usr/lib/ruby/gems/1.8/gems/ruby-debug-0.10.4/cli/ruby-debug.rb:109:in start_client'
from /usr/lib/ruby/gems/1.8/gems/ruby-debug-0.10.4/bin/rdebug:336
from /usr/bin/rdebug:23:in
load'
from /usr/bin/rdebug:23



So I feel like my terminal is not automatically connecting somehow? As I stated, I can't really find updated information online about this problem, so any help is appreciated in either making this work (console-type debugging for Apache / Passenger, like what I had with WEBrick) or current best-practices. Thanks!





Free XML formatter (indent) tool on Mac?

Need a tool that can format the xml in human readable format on Mac!





Debug a Java project which is invoked through a perl script

I am working on a big Java project which is on eclipse. To use the program we need to invoke a perl script in the terminal with the parameters then that script will call the program. In this case how can I debug the program in eclipse?



Thank you,
Regards,
Robo





Reading SMS from inbox in j2me

I am using j2me technology. My application is for sending and receiving sms. Sender can not send sms on specific port and sms always goes to inbox. Is it possible to read sms from inbox in j2me?





jquery shows wrong page

This is the jquery



$(document).on('change', '.ui-slider-switch', function () {

if ($(this).val() == 'on') {
$("#content1").hide();
$("#content2").show();

} else {
$("#content1").show();
$("#content2").hide();
}

});


My HTML



<div id="switch" data-role="fieldcontain">      
<select name="slider" id="flip-a" data-role="slider">
<option value="off"></option>
<option value="on"></option>
</select>
</div>


In my site I sometimes use a custom URL (And get data out of it with $ _GET).
When the page reload I'm always getting $("#content2").show(); instead of $("#content1").show();





Upload external file to AWS S3 bucket using PHP SDK

I want to upload a file from an external URL directly to an Amazon S3 bucket using the PHP SDK. I managed to do this with the following code:



$s3 = new AmazonS3();
$response = $s3->create_object($bucket, $destination, array(
'fileUpload' => $source,
'length' => remote_filesize($source),
'contentType' => 'image/jpeg'
));


Where the function remote_filesize is the following:



function remote_filesize($url) {
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : "unknown";
}


However, it would be nice if I could skip setting the filesize when uploading to Amazon since this would save me a trip to my own server. But if I remove setting the 'length' property in the $s3->create_object function, I get an error saying that the 'The stream size for the streaming upload cannot be determined.' Any ideas how to solve this problem?





Grab euro dollar conversion rate in Java

I have an application that has to convert dollar to euro and vice versa. Is there an interface or API I can use to grab the current conversion rate?





Wednesday, May 16, 2012

Azure toolkit for windows phone publish issue

I um using Windows Azure toolkit for Windows Phone from codeplex. After creating a Windows Phone Cloud Application from a template, I started it on localhost and it run succesfully. Then i followed instructions on Codeplex on how to deploy on Azure, and published it also succesfully - I got an url to the website, but after typing the url in browser the website didn't load, and after a while there was a timeout. I tried both production and staging deployment. Can't resolve why this happens - did anyone faced familiar problem?





Most simple code to populate JTable from ResultSet

I googled the whole day and no luck. I call getnPrintAllData() method after pressing OK button. So the code is:



public class DatabaseSQLiteConnection {
Connection conn = null;
PreparedStatement statement = null;
ResultSet res = null;

public DatabaseSQLiteConnection(){
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite");
statement = conn.prepareStatement("SELECT * from product_info;");
}
catch(Exception e){
e.printStackTrace();
}
}

public void getnPrintAllData(){
String name, supplier, id;
DefaultTableModel dtm = new DefaultTableModel();
Window gui = new Window(); //My JPanel class
try{
res = statement.executeQuery();
testResultSet(res);
ResultSetMetaData meta = res.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (res.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = res.getObject(i+1);
}
dtm.addRow(rowData);
}
gui.jTable1.setModel(dtm);
dtm.fireTableDataChanged();
//////////////////////////

}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
try{
res.close();
statement.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

public void testResultSet(ResultSet res){
try{
while(res.next()){
System.out.println("Product ID: "+ res.getInt("product_id"));
System.out.println("Product name: "+ res.getString("product_name"));
System.out.println("Supplier: "+ res.getString("supplier"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}


My testResultSet() method is working properly.
Now, how to change my code so that it works, or what is the most simple code to make DefaultTableModel from ResultSet ?
Thanks in advance.





SmartGWT - how to create a .jar file for a smartGWT UI dialog

I created a SmartGWT application that displays a UI dialog (shows some controls on a dialog).



This dialog app is tested and works well, but now I have to distribute this as a jar file, so that other SmartGWT projects can use this as a widget.



I am looking at a way, how to ship this component "RemoteFileDialog" as a jar file, so that any other SmartGWT web app can use it for showing a file browser. Is there any detailed document / reference which I can go through to understand fully?



I created the jar file for for this dialog application using jar cvf ... command.



When I use this .jar in a target smartGwt sample project, it is unable to find the classes contained in the .jar



To be sure, I did the following steps in my eclipse ide.




  1. Added the jar to build path via "add external jars"


  2. module inheritance:
    changes to gwt.xml file






3 Did gwtc to test if the module inherits properly. GWT compile works with no warnings or errors.



However, when I tried to create an instance of dialog class (part of the jar file) in the test code given below, eclipse doesn't recognize or prompt me to add the required import, like the way it does for all other jar files.
Code:



Even if I manually add the import statement myself, still it gives compile error at those lines.



I want to a proper way to create a .jar file from a SmartGWT project, so that it can be used as a .jar file in another smartGWT project.



Any help and clues are most appreciated..



This is my environment, if it makes sense:!



SmartGWT 3.0
GWT 2.4
Browser : Firefox 7.0.1
Dev environment: Eclipse Indigo on Ubuntu11.10



regards,
RV



Adding the contents of .gwt.xml files...



This one for the widget project file: RemoteFileBrowser.gwt.xml



<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='remotefilebrowser'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>

<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->

<!-- Other module inherits -->
<inherits name='com.smartgwt.SmartGwt'></inherits>
<inherits name="com.smartgwt.tools.SmartGwtTools"></inherits>
<!-- Specify the app entry point class. -->
<entry-point class='com.comviva.remotefilebrowser.client.RemoteFileBrowser'/>

<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>

</module>


this one for the host project that uses the widget:file: GWTSample.gwt.xml



    <?xml version="1.0" encoding="UTF-8"?>
<module rename-to='gwtsample'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User' />

<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean' />
<!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
<inherits name="com.smartgwt.SmartGwt" />
<!-- <inherits name="com.comviva.scheduler.SchedulerWidget"></inherits> -->
<inherits name="com.comviva.remotefilebrowser.RemoteFileBrowser"></inherits>
<inherits name="com.smartgwt.tools.SmartGwtTools"></inherits>

<!-- Other module inherits -->

<!-- Specify the app entry point class. -->
<entry-point class='com.rv.gwtsample.client.GWTSample' />

<!-- Specify the paths for translatable code -->
<source path='client' />
<source path='shared' />

</module>




Calling a combobox from another form

I have a combobox on form1 that I need to call on form2 to get the user selection. Can some one please give me an example on how to do this?



EDIT: Forgot to explain what Im trying to do. I have a readonly textbox....a user clicks edit to edit the text but I want the text they want/chose to edit to pop up right when form2 is called.



I have this code on form1



    public string SelectedComboValue
{
get { return comboBox1.SelectedItem.ToString(); }
}


And this code on form 2



    EDIT: Added Form1 form1 = null; BUT its still not returning the SelectedComboValue
public Form2(Form1 parentForm1) : this()
{
form1 = parentForm1;
}


But it gave me an error saying that form1 is not in this context





Installing GPG tools via terminal on mac

I am trying to install gpg tools on a mac mini i have ssh access to so i can then install s3cmd.



I know you can use the installer dmg here http://www.gpgtools.org/installer/index.html



But as i only have ssh access i need to install this via terminal and cant findout where to do this if i click source it take me to this page https://github.com/GPGTools/GPGTools which isnt helpful to me.



Can someone point me in the right direction.





Initializing a static pointer in C++

I have a class with a static member that's a pointer like so :



animation.h



class Animation
{
public:
Animation();
static QString *m;

};


animation.cpp



#include "animation.h"

QString* Animation::m = 0;

Animation::Animation()
{
}


When I try to initialize that 'm' pointer from another class like so :



Animation::m = new QString("testing");


It works.



But when I do it this way :



QString x("Testing");
Animation::m = &x;


The program crashes.



What is wrong with this second method ?



Also I would like to have that static pointer as private so I can make static getter and setter functions to it. The setter should use the second method as the 'x' will come in a parameter so I'm stuck.



Thanks for any help!





css table gets wrong properties

I have built a table which on of it's row is like so



<tr id="graphid+'" class="graphRow">
<td colspan="2" style="width:5%; max-width:5%;">
<div class="stockData">
<div class="stockDatatable">
<table class="stocktable">
<tr><td id="stockDBnameid+'"></td></tr>
<tr><td class="Desctitle">???? ?????:</td></tr>
<tr><td id="stockDBfieldid+'" class="stocktable"></td></tr>
<tr><td id="stockDBurlid+'" class="stocktable">????? ??? ?????</td></tr>
<tr><td class="Desctitle">??? ?????:</td></tr>
<tr><td id="stockDBvalueid+'" class="stocktable">??? ?????</td></tr>
<tr><td id="stockDBdescid+'" class="stocktable">????? ??????</td></tr>
</table>
</div>
</div>
</td>
<td colspan="8">
<table>
<tr>
<td>
<div id="graphDivid+'" class="GraphDiv"></div>
</td>
</tr>
</table>
</td>
</tr>


as you can see, The row has two coloumns.
I'm talking about the second one:
it's compiled from a div->div->table->rows..
the rows get their properties from the the class = "graphRow" and NOT from class ="stockTable".
The css is like so:



tr.graphRow td {background:lightgray;}
tr.stocktable td {background:blue;}


why is isn't working?



thanks.





Push APIs like gmail, twitter and facebook does

I want to create an application using pushing mechanism. i.e. without user interaction we can push the messages to the client when some thing is happend in the server, similar to what gmail is done for their emails and facebook recent activity messages.



How can i implement this one using java.



Please help, Thanks in advance.





Indices cycling

I have a array of 7 sets of data which are accessed through their indices 0-6. I need to use 6 for training and 1 for testing which need to be cycled until 7 combinations have been achieved like so.



Training - 0, 1, 2, 3, 4, 5
Testing - 6



Training - 1, 2, 3, 4, 5, 6
Testing - 0



Training - 2, 3, 4, 5, 6, 0
Testing - 1



....



Training 6, 0, 1, 2, 3, 4,
Testing - 5



The training data will be a queue of queues of ints and the testing is a queue of ints. My brain is fried I need to help desperately. I have resorted to simply hard coding them but it looks dreadful and if I want to change the amount of sets I have then it will require a rewrite.



A lot of answer using modulo!, I only used that for finding even numbers :) i'm testing now if it works your all gettin upvotes





Foreach in MYSQL

i am asked to Find the minimum age in each rating from a table with



table name ' SAILORS' and fields 'SID','SNAME','Rating','Age'



This can be done using PHP but i have to do this using a MYSQL Query.





Perl and MySQL - Return a field from last row of a table using DBI possibly with last_insert_id?

I am trying to return a members firstname field from the table users from the last row of users.



 my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
my $LastID = $dbh->last_insert_id(`firstname`); ##but I want from table users
print qq~$LastID~;


This error is returned from above:



DBI last_insert_id: invalid number of arguments: got handle + 0, expected handle + between 4 and 5
Usage: $h->last_insert_id($catalog, $schema, $table_name, $field_name [, \%attr ])


So, what would be the "best" way (best being best for server, fastest, least memory, load, least amount of overhead.. whatever) to get the field firstname from the last row in the table users?



Realize my example above is not to be taken seriously as I have no idea how to do this without just doing something like my crude, but functional:
(p.s. UserID is NOT assigned by auto increment but, is in numeric order and a new user gets a higher UserID. Just the way this was when I tackled the pre existing problem.)



my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
my $dsn = $dbh->prepare(qq{SELECT `firstname` FROM `users` ORDER BY ABS(UserID) DESC LIMIT ?,?});
$dsn->execute('1','1') or die "$DBI::errstr";
while(@nrow = $dsn->fetchrow_array()) {
$newestid = $nrow[0];
}


I assumed since I was using DBI that may provide the best solution but, I am inexperienced obviously and need some advice and guidance to learn the proper way to do this. Thanks for any assistance.





iPhone Certificate Fog




This question is, in some ways, a follow up on my earlier question regarding Push Notifications. After much time wasted I have more or less concluded that the issues I am running into, particularly with Titanium, are down to my not configuring my Keychain in the right order. I am now contemplating redoing it all from scratch but thought it best to first post a question here to establish the right way. Here is what I am planning to do




  1. Log in to my Apple iOS provisioning portal account, download and install the Apple WWDRCA cert

  2. Open up KeyChain and create a new certificate signing request. I call it myname.certS... .

  3. Go to the provisioning portal account and use the CSR created above to secure my development and production certificates.

  4. Download and install those certs on my machine by double clicking on them

  5. Back in the provisioning portal create my first appID - call it, com.example.push

  6. Back in KeyChain create a new csr - push.certSig... .

  7. Back in the provisioning portal choose the new appID and configure it for Push using the new csr

  8. Still in the provisioning portal select Devices and add the UUIDs for the devices on which I want to test my app

  9. Still in the provisioning portal select Provisioning and create a new development and production provisioning profile for the app. The latter has AdHoc selected. Use the certificates created earlier. At this stage assign only one device in each profile.

  10. Submit the profile, wait then edit it and add the remaining devices - I am doing this because I have read that there is bug somewhere that stops the provisioning profile from using the Push configuration for the appID in question the first time round

  11. Download and install the two provisioning profiles



Well as I write I have followed all of these steps. I then wrote and compiled a simple Titanium mobile project and tried the Install To Device option with the AdHoc profile created above. Everything went swimmingly well and I got my IPA. I took the IPA and fed it to TestFlightApp which reported Invalid Profile: developer build entitlements must have get-task-allow set to true. So I tried again with the Development profile. This time round TestFlightApp accepted the IPA. In installed it on my iPad but still find that registerForPushNotifications is going away into the ether with nothing being reported - no success, no erors... just a defeaning silence.



I have to admit that I am at my wits end here. I am clearly doing something wrong but I haven't got the foggiest idea what it could be. If I had a million dollars I would give em away to anyone who could set me on the right track. Well I don't so I hope someone just puts me on the right track out of sheer goodness





Box-shadow covered by content?

I have a div with a box shadow on it which looks great. The problem I am having is that when I add content to the div the content will cover the shadow. How to I have the box-shadow on my div and have it on top of any child content of that div?





Forming NSString "2012-06-29" into NSDate's "NSDateFormatterMediumStyle"?

I'm trying to separate the month and day from the following string.



2012-06-29


I've tried formatting the string into the medium style by doing the following:



//Setting Up My Formatter
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];

Forming String Into Formatted Date
NSDate *dateFromString = [formatter dateFromString:event.date];

//Separating Components
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateFromString];

//Assigning Each Component to my Cell's Labels
cell.dayLabel.text = [NSString stringWithFormat:@"%d", [components day]];
cell.monthLabel.text = [NSString stringWithFormat:@"%d", [components month]];


When I ran the NSLogs my "event.date" came back "2012-06-26 & dateFromString came back null. Can anyone help guide my in the right direction? Thanks a lot!



EDIT:



So I finally figured out from your help that I was setting the format incorrectly. Instead of using:



[formatter setDateStyle:NSDateFormatterMediumStyle];


I am now using:



[formatter setDateFormat:@"yyyy-MM-dd"];


Here is my question though, from the components, the month is coming back as an integer (1, 2, 3) but I want it to come back as "MMM" (Jan, Feb, Mar). Thanks!





Synchronizing alternatively two processes in Linux C

TI need two son processes to do this:




  • Son process 1 should printf even numbers between 0 and 100.

  • Son process 2 should printf odd numbers between 0 and 100.



What I should see in terminal after execution is: 0 1 2 4..100



How can I do this?



I tried this program, but it doesn't work, it only gives me the first integer 0:



#include <unistd.h>
#include <stdio.h>
#include <signal.h>

void handler1(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}

void handler2(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}

int main()
{
int i=-1;

if(fork()==0)
{
signal(SIGCONT,handler1);
while(1)
{

printf("%d\n",i+1);
pause();
kill(getpid()+1,SIGCONT);
}
}

if(fork()==0)
{
signal(SIGCONT,handler2);
while(1)
{
pause();

printf("%d\n",i+1);
kill(getpid()-1,SIGCONT);
}
}

}




How can i display date in a 1 by 1 array when i use datestr?

I use datestr to transfer 732154.873773148 into 26-Jul-2004 20:58:14, but when i ouput it to a .csv file, it will be an 1*20 array..., but what i want is to store it in a 1*1 array, how should i do?



And does there exist easy method to transfer 26-Jul-2004 20:58:14 to 2004/07/26 20:58:14?



Thanks:)



data = csvread('4.csv');
date = data(:, 1);
loc = data(:, 2);
record_num = size(loc, 1);

result = zeros(record_num, 2);
new_date = datestr(date);
csvwrite('4_res.txt', new_date);


what i want is
2004/07/26 20:58:14



but it will be
2,0,0,4,/,0,7,/,2,6, ,2,0,:,5,8,:,1,4





KendoUI grid display total number of records

I am using the kendoUI grid to show records from a table. I would like to display the total number of records so the table. something like



showing 1-20 of 1203 records



is there a way to show the total number of records using KendoUI grid?





Inheriting mapping annotations

I'm working on a JPA project in which I have some different Entities extending a super-class annotated as Entity:



@Entity
@Table(name = "export_profiles")
@NamedQueries({
@NamedQuery(name = "ExportProfile.getAll", query = "select ep from PersistentExportProfile ep"),
@NamedQuery(name = "ExportProfile.getByName", query = "select ep from PersistentExportProfile ep where ep.profileName = :name") })
public abstract class PersistentExportProfile extends AbstractExportProfile {

// other mappings...

}


I'd like to inherit mappings defined in my PersistentExportProfile into each sub-class.
Is it possible? What do I have to change in my super-class, and what do I have to add in my sub-entities?



NOTE all the sub-classes will be mapped on the same table.





access parent listview's dataitem from nested listviews EmptyDataTemplate

I need to set the visiblity of an element in my nested ListView's EmptyDataTemplate based on a property on the parent ListView's DataItem.



How do i go about it?



TIA





select with multiple dropdown list with condition php mysql

Sorry im a newbie looking for help from experts



what i have is a form to add customer details.



What i am looking is to add:



dropdown list #1
dropdown list #2
data in list#2 to be changed on the base of list#1 using php mysql



i have used a script Demo 3 of Three Multiple drop down list box from plus2net
http://www.plus2net.com/php_tutorial/dd3.php



however the issue with this script is that on each selection data for dropdown gets reload in my form and the data i have in other text boxes gets reset



The help will be much appreciated





Large scale deployment of a .net mono app on Linux/Ubuntu

We have a .net app written to be Mono and Linux compatible - written in Visual Studio 2010. For deployment on Windows, we use a Visual Studio Deployment project to build the installer and put files in the correct places.



Is there an equivalent for Linux? Some thing that's as easy and simple for the end user to install?



Thanks



Roberto





How To Pass "this" to a Function in a Nested .each() loop within a .getJSON() method

So I know what the problem is, but I don't know the proper way (the syntax) to fix it.



If you take the code from "myFunction" and put it inside the .each loop where I am calling "myFunction" then my code works because "this" is being defined and is within the scope of the JSON object that I am referencing.



But, when I write my function and declare it outside the scope of the JSON object, then it no longer knows what "this" is and returns a value of "undefined".



How do I pass "this" as an argument to my function so that I can properly grab the values?



    $.getJSON('labOrders.json', function(json) {
var aceInhibitors = "",
antianginal = "",
anticoagulants = "",
betaBlocker = "",
diuretic = "",
mineral = "",
myFunction = function () {
aceInhibitors += "<div class='row drugLineItem'>",
aceInhibitors += "<div class='columns moneydot' style='background:none;'></div>",
aceInhibitors += "<div class='columns drugTitleWrap'>",
aceInhibitors += "<div class='row drugTitle'>"+this.name+"</div>",
aceInhibitors += "<div class='row drugDose'>"+this.strength+"</div>",
aceInhibitors += "<div class='columns'></div>",
aceInhibitors += "<div class='columns orderDeets dxRefill'>"+this.refills+"</div>",
aceInhibitors += "<div class='columns orderDeets dxPillCount'>"+this.pillCount+"</div>",
aceInhibitors += "<div class='columns orderDeets dxSig'>"+this.sig+"</div>",
aceInhibitors += "<div class='columns orderDeets dxRoute'>"+this.route+"</div>",
aceInhibitors += "<div class='columns orderDeets drugTab'>"+this.dose+"</div>"
}

$.each(json.medications, function(index, orders) {
$.each(this.aceInhibitors, function() {
myFunction();

});
$.each(this.antianginal, function() {

});
});

$('#loadMedSections').append(aceInhibitors);



});




Navigating an XML file while keeping track of order

I need to convert an XML file in the IOB format.



The XML file represents the structure of a Latex-written paper, i.e. with sections and subsections. In this representation, sections are encoded as BODY, then I have a HEADER and then paragraphs or subsections.



Example:



<DIV DEPTH="1"> 
<HEADER ID="H-8"> Practical Results </HEADER>
<P TYPE="TXT">
<S ID="S-56" TYPE="TXT"> To assess its performance , <REF REFID="R-12" ID="C-36">Grover et al. 1993</REF> tried various methods . </S>
<S ID="S-57" TYPE="TXT"> The grammar is defined in metagrammatical formalism which is compiled into a unification-based ` object grammar ' -- a syntactic variant of the Definite Clause Grammar formalism <REF REFID="R-21" ID="C-37">Pereira and Warren 1980</REF> -- containing 84 features and 782 phrase structure rules . </S>
<DIV DEPTH="2">
<HEADER ID="H-9"> Comparing the Parsers </HEADER>
<P TYPE="TXT">
<S ID="S-61" TYPE="TXT"> In the first experiment , the ANLT grammar was loaded and a set of sentences was input to each of the three parsers . </S>
</P>
<IMAGE ID="I-0"/>
</DIV>


What I want to do is to keep all the text, but convert it to a different format, i.e. I want to remove the BODY structure, and just tag the HEADERs and the text part like this:



Practical/B-Header Results/I-Header ./O 
To/B-Text assess/I-Text its/I-Text performance/I-Text ,/I-Text Grover/I-Text et/I-Text al./I-Text tried/I-Text various/I-Text methods/I-Text ./O
The/B-Text grammar/I-Text ... ./O


And so on.



I know some DOM parsing in Java (for example, I have been using jdom2 for a little while) but I do not know how to keep the order of the text: for example, I want to fetch the content of the REF tag (which is inside S, look at the example), but the text from its parent extends before and after the REF tag.



Any pointers? Should be fairly simple, but searches like "strip XML tags after certain depth" did not help me :-(





Tomcat, Maven: executing tomcat7-maven-plugin with war file hangs

update: I ran this with exec-war instead of run-war and got a null pointer which indicates the "project.artifact" file in AbstractExecWarMojo was not set.



java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:134)
at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.execute(AbstractExecWarMojo.java:307)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)


executing tomcat7-maven-plugin from intellij. Compiled to target java 1.6 using java 1.7 compiler.



War file executes in tomcat6 using the tomcat6 plugin. Tomcat7 will execute correctly when not using the war file.



I'm getting no error message. After the line "[INFO] Creating Tomcat server configuration at..." in the console output, nothing happens.



Here's my tomcat7 plugin configuration with dependencies.



   <plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0-beta-1</version>
<!--tomcat7.version = 7.0.27-->
<configuration>
<port>34140</port>
<path>/${project.build.finalName}</path>
<warFile>****RedirectConfig.war</warFile>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat7.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version>${tomcat7.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>${tomcat7.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper-el</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-el-api</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-tribes</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina-ha</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-annotations-api</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>${tomcat7.version}</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<version>${tomcat7.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-log4j</artifactId>
<version>${tomcat7.version}</version>
</dependency>
</dependencies>
</plugin>


Here's the maven-war-plugin configuration.



    <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>

<webappDirectory>target</webappDirectory>
<!--<packagingExcludes>WEB-INF/web.xml</packagingExcludes>-->
<warName>****RedirectConfig</warName>
</configuration>
</plugin>


Here's the console output



        "C:\Program Files\Java\jdk1.7.0_01\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:6050,suspend=y,server=n -Djava.security.egd=file:/dev/./urandom -Dclassworlds.conf=C:\Utilities\Maven\apache-maven-2.2.1-bin\apache-maven-2.2.1\bin\m2.conf -Dmaven.home=C:\Utilities\Maven\apache-maven-2.2.1-bin\apache-maven-2.2.1 -Dfile.encoding=UTF-8 -classpath "C:\Utilities\Maven\apache-maven-2.2.1-bin\apache-maven-2.2.1\boot\classworlds-1.1.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 11.0.2\lib\idea_rt.jar" org.codehaus.classworlds.Launcher --no-plugin-registry --fail-fast --no-plugin-updates --strict-checksums --update-snapshots -f C:\****\*****\dev\trunk\****RedirectConfig\pom.xml org.apache.tomcat.maven:tomcat7-maven-plugin:2.0-beta-1:run-war

<snip/>
[INFO] [war:war {execution: default-war}]
[INFO] Packaging webapp
[INFO] Assembling webapp [****RedirectConfig] in [C:\****\*****\dev\trunk\VIPSRedirectConfig\target]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\****\*****\dev\trunk\****RedirectConfig\src\main\webapp]
[INFO] Webapp assembled in [534 msecs]
[INFO] Building war: C:\****\*****\dev\trunk\****RedirectConfig\target\****RedirectConfig.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] [tomcat7:run-war {execution: default-cli}]
[INFO] Running war on http://localhost:34140/****RedirectConfig
[INFO] Creating Tomcat server configuration at C:\****\******\dev\trunk\****RedirectConfig\target\tomcat




jQuery Mobile 1.1.0 Fixed Headers Browser Scrolling

I am developing an app that requires fixed headers and footers with the content scrolling in between. I was previously accomplishing this by giving the header and footer position:absolute and using iScroll4 to scroll a fixed height </div>. This works great on Mobile Safari, but I'm experiencing a lot of performance issues on Android Browser (I've tested against 2.2.X and 3.1.X).



I've switched to using JQM's new fixed toolbars implementation in 1.1.0 and while they work great, I now have the problem that the entire browser itself scrolls above and below the content (specifically in Mobile Safari) in an elastic fashion... not sure on the actual name of this behaviour.



Does anyone know how to prevent only the browser window from scrolling / moving while allowing the content within to use the native scroll + JQM fixed toolbars?



Any help would be greatly appreciated; thanks!





wpalchemy and datetime input

I'm trying to get to work a datetime input in a metabox with wpalchemy. The way I'm doing, I can get the date and time, but I need to pass this content, to a datetime object, using strtotime. And for this, I'm using the save_filter option. The function:



function save_datetime($meta, $post_id) {
// var_dump($meta);
//var_dump($post_id);
//exit;

$dd = $meta['start_day'];
$mm = $meta['start_month'];
$yy = $meta['start_year'];
$hh = $meta['start_hour'];
$mn = $meta['start_minute'];
$start_datetime = strtotime( $dd . $mm . $yy . $hh . $mn );

//$meta['start_datetime'] = $start_datetime;
update_post_meta($post_id, '_info_evento_start_datetime', $start_datetime);

return $meta;
}


But the information is not recorded at the database. The two files can be found here and here.



How can I write in database with this function?





Difference between Java DateUtils.ceiling and DateUtils.truncate

It's not clear in the java doc what the difference between DateUtils.ceiling and DateUtils.truncate is. Is the java doc wrong? Can someone clarify this?




ceiling



public static Date ceiling(Date date,
int field)



Ceil this date, leaving the field specified as the most significant field.



For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you
passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was
passed with MONTH, it would return 1 Mar 2002 0:00:00.000.




vs




truncate



public static Date truncate(Date date,
int field)



Truncate this date, leaving the field specified as the most
significant field.



For example, if you had the datetime of 28 Mar 2002 13:45:01.231,
if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.
If this was passed with MONTH, it would return 1 Mar 2002 0:00:00.000.






css - two inline-block, width 50% elements don't stack

I would like to have two columns of 50% width space, and avoid floats.
So i thought using display:inline-block.



When the elements add to 99% width (eg 50%, 49%, http://jsfiddle.net/XCDsu/2/ ) it works as expected.



When using 100% width (eg 50%, 50%, http://jsfiddle.net/XCDsu/3/ ) the second column breaks to the second line.



Why is that?





Conditional str_replace for pagination

H everyone,



I have the following:



$html = '<ul class="pagination-all">';
$html .= '<li class="pagination-start"><div class="img-start"></div>'.$list['start']['data'].'</li>';
$html .= '<li class="pagination-prev"><div class="img-prev"></div>'.$list['previous']['data'].'</li>';
$html .= '<ul class="pagination-data">';
foreach($list['pages'] as $page) {
$html .= '<li>'.$page['data'].'</li>';
}
$html .= '</ul>';
$html .= '<li class="pagination-next">'. $list['next']['data'].'<div class="img-next"></div></li>';
$html .= '<li class="pagination-end">'. $list['end']['data'].'<div class="img-end"></div></li>';
$html .= '</ul>';

return $html;


I was wondering how to make it so if it finds Start , string replaces "img-start" to "img-start-active". If it finds span class="pagenav"> End , string replaces "img-end" to "img-end-active".



I attempted:



$string = $html;
if(strstr($string, '<span class="pagenav"> Start </span>'))
{
echo str_replace("img-start", "img-start-active", $string);
}
else
{
echo " ";
}


Unfortunately, I don't believe I used this properly. What ended up was - while I got the desired string replacement given the condition, it echoed the whole pagination but without the formatting.



This is the image:enter image description here



So it was a mess.



Is there a way to do this search and replace but without creating a second "pagination"?





SwingUtilities.invokeLater in AWT Event Dispatching Thread

Should you use SwingUtilities.invokeLater(Runnable) if you're modifying the GUI and you're in the AWT Event Dispatching Thread, such as an ActionListener?





read and write in java

I want print in the file every time line
But every time i want print a new line printed on the same line the old.



I want to print lines in the file



This my code



         BufferedReader read = new BufferedReader(new FileReader (SecurityScreen.path.get("ScoreFile")));
FileWriter file ;
BufferedWriter write = new BufferedWriter ( new FileWriter(SecurityScreen.path.get("ScoreFile")));
String temp = "" ;
String output = "";
String newLine = System.getProperty("line.separator");
String score= SecurityScreen.getPlayer() + "@" +gameTime + newLine;
// if(read.readLine()==null){
// write.write(score);
// }
try{
if((temp = read.readLine()) != null){

while (true) {
output += temp + newLine;
file = new FileWriter(SecurityScreen.path.get("ScoreFile"));
//write = new BufferedWriter(file);
write.write(output + newLine) ;
//score = SecurityScreen.getPlayer() + "@" +gameTime ;
write.write(score) ;
}
}
else {
write.write(score);
}

write.close();
}catch(IOException e){

}




How to get the type of the returned object from .POST ajax call?

Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code



 $.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {

if (output == "true"){


and here is the php script that being called



include_once('class.MySQL.php');

$userid = $_POST['action'];

$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;


if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();

}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();

}


I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true



Thanks in advance!





knockout checkboxlist with dynamic data

sup guys, my english is not good.. but i'll try my best



I'm new with knockout, I'm really impressed with this tool.
I'm using this framework on my new page in my MVC 3 application. But i just faced a problem on how to mark my checkboxlist with data from the database.



<div data-bind="foreach: listPeople">
<div>
<label>
<input type="checkbox" data-bind="attr: { value: id_person}, checked: $parent.checkedPeople " />
<span data-bind="text: name_person"></span>
</label>
</div>
</div>


as u guys can see, im using the checked tag to "hold" the id_person information to save im my database.



listPeople is an observableArray with my people.
and checkedPeople is an observableArray with those chosed people.



while inserting its working like a piece of cake.
the problem is when im tryin to "edit". When i try to previous populate "checkedPeople".



isnt knockout supposed to recognize it ?





How do I add a src in style class?

<div><img class="imgClose"></div>


I tried adding like this, but it does not show the image:



<style type="text/css">
.imgClose
{
float: right;
margin-top: -15px;
background: 16px 16px no-repeat url(_assets/img/close.png);
}
</style>


If I add in the HTML, then it works, but I would like to put the src in style class instead.



<div><img class="imgClose" src="_assets/img/close.png"></div>




sending an image from iphone to rails. using RestKit

I am trying to send a sample Image to rails application and this is what i get for the parameters.



Started POST "/itemposts.json" for 127.0.0.1 at 2012-05-15 04:39:46 +0530
Processing by ItempostsController#create as JSON
Parameters: {"carryItem"=>"0", "description"=>"Hkhgcgc ", "makeOffer"=>"1", "price"=>"11336655", "title"=>"hkvlhkv", "assets_attributes"=>#<ActionDispatch::Http::UploadedFile:0x007fa5924327d8 @original_filename="
assets_attributes", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"assets_attributes\"; filename=\"assets_attributes\"\r\nContent-Type: image/png\r\n", @tempfile=#<File:/var/folders/26/
yjdt74rx3cbg69hznd37fmyc0000gp/T/RackMultipart20120515-21256-630xb6>>}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 's4cUEfOHhnhID6pFAOlk2w' LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 's4cUEfOHhnhID6pFAOlk2w' LIMIT 1
Completed 500 Internal Server Error in 22ms

ArgumentError (Hash or Array expected, got ActionDispatch::Http::UploadedFile (#<ActionDispatch::Http::UploadedFile:0x007fa5924327d8 @original_filename="assets_attributes", @content_type="image/png", @headers="Cont
ent-Disposition: form-data; name=\"assets_attributes\"; filename=\"assets_attributes\"\r\nContent-Type: image/png\r\n", @tempfile=#<File:/var/folders/26/yjdt74rx3cbg69hznd37fmyc0000gp/T/RackMultipart20120515-21256-
630xb6>>)):
app/controllers/itemposts_controller.rb:15:in `create'


Rendered /Users/rajeshmedampudi/.rvm/gems/ruby-1.9.2-p318@global/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (3.2ms)
Rendered /Users/rajeshmedampudi/.rvm/gems/ruby-1.9.2-p318@global/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.1ms)
Rendered /Users/rajeshmedampudi/.rvm/gems/ruby-1.9.2-p318@global/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (12.5ms)


This is the response for the following code at the iPhone. using RestKit.



        NSDictionary *paramsDictionary=[NSDictionary dictionaryWithObjectsAndKeys: TitleField.text,@"title", PriceField.text,@"price",DescriptionField.text,@"description",[NSNumber numberWithBool:makeOfferButton.selected],@"makeOffer",[NSNumber numberWithBool:carryItemButton.selected],@"carryItem",nil];

RKParams *params=[RKParams paramsWithDictionary:paramsDictionary];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:@"2009-08-24 13.05.44.jpg"]);
[params setData:imageData MIMEType:@"image/png"forParam:@"assets_attributes"];
// [params setData:imageData MIMEType:@"image/png"forParam:@"assets"];
// [params setFile:@"bio.txt"forParam:@"attachment"];

[[RKClient sharedClient] post:@"/itemposts.json"params:params delegate:self];


The set up at the rails side strictly follows the tutorials from



http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads
http://www.emersonlackey.com/article/paperclip-with-rails-3



and i have also tried out the example in http://brainbowapps.com/articles/2010/uploading-files-from-iphone-to-rails.html with no desired output.



What i need is basically to upload images and video files to s3 using paperclip gem...



The rails app is deployed in heroku.





how to merge rows in datatable which had same value (VB)

I have one datatable tempDT with value :



Serial_No                      testong
---------------------------------------
DTSHCSN001205035919201 [ OUT ] <br/> Partner : 90000032 <br/> Date : 16 Feb 2012
DTSHCSN001205035919201 [ IN ] <br/> Partner : 90000032 <br/> Date : 16 Feb 2012
DTSHCSN001205035919201 [ OUT ] <br/> Partner : 80000869 <br/> Date : 31 Mar 2012
DTSHCSN001205035919201 [ IN ] <br/> Partner : 80000869 <br/> Date : 31 Mar 2012


The problem is I want merge duplicate serial_no into one row which the value of testong adding to new column.



I have tried many ways, but I can't find the solution.



Here is my code behind :



    Dim tempDt = GetItemDataTable()
Dim dtData As New DataTable

dtData.Columns.Add("Serial_No")
Dim i As Integer = 0
Dim row As DataRow

For Each row In tempDt.Rows
i += 1
Dim dr As DataRow = dtData.NewRow
dr("Serial_No") = row(0)
If dr("Serial_No") = row(0) Then
Dim colBaru As GridViewDataTextColumn = New GridViewDataTextColumn()
colBaru.Caption = i
colBaru.FieldName = i
colBaru.CellStyle.HorizontalAlign = HorizontalAlign.Center
colBaru.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
colBaru.Width = 150

colBaru.UnboundType = DevExpress.Data.UnboundColumnType.Integer
colBaru.VisibleIndex = grid.VisibleColumns.Count
colBaru.PropertiesTextEdit.DisplayFormatString = "d1"
colBaru.PropertiesTextEdit.EncodeHtml = True
grid.Columns.Add(colBaru)
dtData.Columns.Add(i)
dr(i) = row(3)
dtData.Rows.Add(dr)

Else
dr("Serial_No") = row(0)
dtData.Rows.Add(dr)
End If


When I debug the result is :
wrong result



But I wanted the result is like this :
enter image description here





Can I get a method attribute from a generic delegate?

I'm sure there's an answer already on the forum somewhere, but I haven't been able to find it so far. As per this example I am using anonymous methods in conjunction with a delegate in order to have different methods with the different parameters but the same return type all work as function parameters:



public delegate TestCaseResult Action();
...

[TestDescription("Test whether the target computer has teaming configured")]
public TestCaseResult TargetHasOneTeam()
{
// do some logic here and return
// TestCaseResult
}

[TestDescription("Test whether the target computer has the named team configured")]
public TestCaseResult TargetHasNamedTeam(string teamName)
{
// do some logic here and return
// TestCaseResult
}
...

public static void TestThat(TestCaseBase.Action action)
{
TestCaseResult result = action.Invoke();

// I want to get the value of the TestDescription attribute here
}
...

// usage
TestThat(() => TargetHasOneTeam());

TestThat(() => TargetHasNamedTeam("Adapter5"));


As you can see from the example, I'd really like to be able to get the TestDescriptionAttribute attribute from within the TestThat() function. I've already poked through the Action parameter which contains my method but haven't been able to "find" my TargetHasOneTeam() method.





cancelling bath request in AFNetworking

So I have a batch request which is the following code:



[[AHClient sharedClient] enqueueBatchOfHTTPRequestOperationsWithRequests:requestArray progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {


} completionBlock:^(NSArray * operations){

dispatch_async(dispatch_get_main_queue(), ^(void){
//update the UI
});
}];


I tried cancelling the request by saving the path of the url in an array and do the following:



for (NSString * urlPath in self.currentRequestArray_){
[[AHClient sharedClient] cancelAllHTTPOperationsWithMethod:@"GET" path:urlPath];
}


but it seems that it still goes to the completed block, i.e: updates the UI. Thoughts or suggestions?





Trouble Installing Ruby 1.9.2 on OSX - Readline and Make errors

I keep getting these errors:



Error running 'make ', please read /Users/jason*/.rvm/log/ruby-1.9.2-p320/make.log
There has been an error while running make. Halting the installation.
ls: /Users/jason*
/.rvm/rubies/*/bin/ruby: No such file or directory



I've tried installing readline and making sure I have the latest GCC version.
This is the error log.



/usr/bin/gcc-4.2 -dynamic -bundle -o ../../../.ext/x86_64-darwin11.3.0/racc/cparse.bundle cparse.o -L. -L../../.. -L/Users/jasonvdm/.rvm/usr/lib -L. -L/usr/local/lib -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -Wl,-flat_namespace  -lruby.1.9.1  -lpthread -ldl -lobjc 
compiling readline
/usr/bin/gcc-4.2 -I. -I../../.ext/include/x86_64-darwin11.3.0 -I../.././include -I../.././ext/readline -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/jasonvdm/.rvm/usr/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -fno-common -O3 -ggdb -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-missing-field-initializers -Wshorten-64-to-32 -Wno-long-long -fno-common -pipe -o readline.o -c readline.c
readline.c: In function 'username_completion_proc_call':
readline.c:1386: error: 'username_completion_function' undeclared (first use in this function)
readline.c:1386: error: (Each undeclared identifier is reported only once
readline.c:1386: error: for each function it appears in.)
make[1]: *** [readline.o] Error 1
make: *** [mkmain.sh] Error 1




MSChart DateTime only shown as OLE-Automation

I have 3 ChartAreas in 1 Chart each is initalized the same way (only other names). Each ChartArea has its own Series (still initialized the same way) which are filled as follows:



DateTime Datum = Pair.Key;
if (Datum1_gewählt.Contains(Datum))
{
foreach (Tuple<DateTime, int> t in Pair.Value)
{
//Füge Messwert mit Zeit der aufzeichnung hinzu
mySeriesHRM1.Points.AddXY(t.Item1, t.Item2);
}
}
if (Datum2_gewählt.Contains(Datum))
{
foreach (Tuple<DateTime, int> t in Pair.Value)
{
//Füge Messwert mit Zeit der aufzeichnung hinzu
DataPoint pt = new DataPoint(t.Item1, t.Item2);
mySeriesHRM2.Points.Add(pt);
}
}
if (Datum3_gewählt.Contains(Datum))
{
foreach (Tuple<DateTime, int> t in Pair.Value)
{
//Füge Messwert mit Zeit der aufzeichnung hinzu
mySeriesHRM3.Points.AddXY(t.Item1, t.Item2);
}
}


As you see each Series is filled with die actual Date(x axis) and an double value (y axis).
My Problem is that in Chartarea 1 all Dates are displayd correctly, but in the other areas as OLE automation. Anyone know why?
Thanks.





sqlite via c++, opening multiple sqlite files

How do I connect multiple sqlite files into a single sqlite3* handle, in C/C++? I'm thinking it's possible considering there's a command called ATTACH, but do not know how to do so in C++. Thanks in advance.





How can I change the ethernet settings on an arch-arm device from my application?

How can I change the ethernet settings on an arch-arm device from my application? I am using android-15 sdk.



The reason I ask is, my application does UDP socket Tx/Rx in native code, but in order to start the socket service the device (FriendlyARM Tiny210) needs to have DHCP enabled, and whenever the device is rebooted the ethernet settings are reset and I have to manually go in to Ethernet Settings and refresh it. Otherwise I get errno 19 Device Not Found when connecting the socket.



There is no EthernetManager that I can find, but surely there is a way, otherwise it is a huge oversight from the Android team.





Shutdown message while running the program in Cocos2d for MacOS X

Currently i'm developing a Cocos2d application for Mac OS X using xCode 4.2.1.So my problem is,sometimes while running the program the system get's stuck and show me a message like this- "You need to restart your computer.Hold down the power button until it turns off.Then press the power button again". After receiving this message i can't proceed further without restarting the computer. What might be the problem behind this issue. Can anyone help me out.





3d Math Library For Python

i'm looking for a 3d math library in python or with python bindings.



it needs to handle rotation, translation, perspective projection, everything basically.



what im NOT looking for is a library aimed at drawing on the screen, googling for hours only led to 3d libraries bent on rendering something to the screen. i dont want any visualization whatsoever, all i need is to be able feed a library x,y,z coordinates and recieve the x,y screen coordinates.



i dont mind if its a visualization library, as long as it can be used without rendering anything to the screen.



is there anything like this for python?



Edit:
please dont recommend scipy/numpy as they arent aimed at 3d math but at math in general, they look like great tools if i wanted to build the library myself, which i dont. thanks.





Detail Information about classfactory?

Can u explain me indetail about classfactory with simple examples by using c#?
Thank u.





learn a bit on asp.net and c#

I want to do more and more projects in c# and asp.net? I can also do an apprentice work for anyone. All I wish is to get a good grip in asp.net. I guess this might not be a right question, any guidance would be appreciated.





JS timeout not firing

Just can't seem to figure this out, how to prevent the outer loop continuing until the inner loop has executed using setTimeout:



    function $(s) { return document.getElementById(s); }
var i = 0;
for (i=0; i<6; i++){
$('t'+i).className = 'show';
cl('t'+i);
for (var j=0; j<50; j++){
cl('b'+i+'='+j+'%');
setTimeout(function(){ $('b'+i).style.width = j+'%';},200);
}
}


This little bit of code is supposed to first make elements t0 visible, and then set the width of another element b0 in 1% steps with a time interval of 200ms, and then continue with t1,b1, t2,b2 etc etc.



But there's no 200ms delay, the whole code executes immediately.





iPhone pathfinding implementation

I am trying to create a Pacman AI for the iPhone, not the Ghost AI, but Pacman himself. I am using A* for pathfinding and I have a very simple app up and running which calculates the shortest path between 2 tiles on the game board avoiding walls.



So running 1 function to calculate a path between 2 points is easy. Once the function reaches the goalNode I can traverse the path backwards via each tiles 'parentNode' property and create the animations needed. But in the actual game, the state is constantly changing and thus the path and animations will have to too. I am new to game programming so I'm not really sure the best way to implement this.



Should I create a NSOperation that runs in the background and constantly calculates a goalNode and the best path to it given the current state of the game? This thread will also have to notify the main thread at certain points and give it information. The question is what?



At what points should I notify the main thread?



What data should I notify the main thread with?



...or am I way off all together?



Any guidance is much appreciated.





ajaxified php mail not working

I'm running on a MAC and I am trying to use php mail with ajax implementation.



I have simplified my code to the point that it was reduced to strings:



In my .js file :



function ajaxMail2() {



$('#sending').show();


$.ajax({

type:'POST',
url:'ajax/mail.php',

success:function(data, status) {
$('#sending').hide();
$('#success').fadeIn(1000,function() {
//$(this).delay(200).fadeOut(1000);
});
},

error:function(data, status, e) {
$('#sending').hide();
$('#fail').fadeIn(1000,function() {
$(this).delay(200).fadeOut(1000);
});
}

});


}


and on my .php file :



<?php



$to = 'foo@gmail.com';
mail($to,'test','test');



?>


When the form is submitted, it goes to the success function but no email was sent to $to. Any ideas?





Get unknown exception while rewriting text file

So i have a function call classifier that basically check all text file in a directory, if there is any text file contains more than 50 line of words, then classify that text file into a type using other class called Text_Classification which i am sure its correct and error free. After classification, i will need to clean that text file and write a "Lines" as a first new line on that text file.(this is for other class, so dont bother :) )
But i got an exception, which mean there is something wrong in the try{} block.
Any idea why?



private static void classifer(object state)
{

Console.WriteLine("Time to check if any log need to be classified");

string[] filename = Directory.GetFiles(@"C:\Users\Visual Studio 2010\Projects\server_test\log");
foreach (string textfile_name in filename)
{
var lineCount = File.ReadAllLines(textfile_name).Length;
if (lineCount > 50)
{
Console.WriteLine("Start classifying 1 of the logs");
Text_Classification classifier = new Text_Classification(textfile_name, 1);
string type = classifier.passBack_type(); //this function passes back the type of the log(text file)
Console.WriteLine(type);

try
{
TextWriter tw = new StreamWriter(textfile_name); //clean the text file
tw.WriteLine(" ");
tw.Close();


TextWriter tw2 = new StreamWriter(textfile_name, true); //append <Lines> as the first new line on the text file
tw2.WriteLine("Lines");
tw2.Close();
}
catch {
Console.WriteLine("cant re-write txt");
}

}

}
}




Monday, May 14, 2012

Eclipse error- Google Map View failed to instantiate

I am making project on Google map that displays 10 nearest position in map,
Today Morning, My project works fine but than after, when I lounch my eclipse it displays dialog box that "Internal Error"
"com.google.android.maps.MapView failed to instantiate"
"java.lang.StackOverflowError"



and than pressing ok on dialog box,
says me to you are recommanded to exit the workbench..
I am afraid, that it might delete or crash my project,
What to do?? plz help me someone.



I should reinstall eclipse??