Wednesday, May 23, 2012

data source configuration wizard issue Could not get column information for database object named

I'm using Visual Studio 2010 and connecting to MySQL database through MySqlODBC 5.1 driver. The page is a reporting page (I'm using crystal report and devexpresss reporting tool).



I have successfully tested the ODBC connection to my MYSQL database using Data source Configuration wizard, and after creating connectionString I can see my database objects , i.e. Tables , Stored procedures, but when I select any table , it do not expand to show me columns and when i click on finish it gives me data source configuration wizard error message,



<tyrepro..vendor>
Could not get column information for database object named 'tyrepro..vendor'



*vendor is table name here.



I tried connecting to system database and select table , but got same issue.





not-read-only DataGridView, but don't show input in datagridview after leaving, only show programmatical input

In my DataGridView users are able to input data. The DataGridView automatically changes its content when one of the properties of a correspondent list of objects changes with the help of events.



Now I want to give the DataGridView the following behavior: when the user inserts data, and then leaves the cell, the input should be validated. If the validation gives a positive result, the input is saved to an object. The datagridview should then show the input value in the correct format (eg. for a date).



I can make this work: the events between the list of objects and the datagridview can manage this.



The problem is: If the validation gives a negative result, the previous cell value should be restored.



I tried to use DataGridView.CellValidating event, but this doesn't work. What should I do?



SOLVED: I used e.Cancel. This doesn't really do what I thought it promissed. When I use DataGridView1.CancelEdit(), it works like I wanted.





gunicorn + zope error handling

we are trying to setup gunicorn + plone. It works well so far, but fails to handle errors (404, 500 etc) and throws 'Internal Server Error' while it should return plone's error page.



Example case of requesting a page that doesn't exist is pasted below. The question is how should gunicorn be setup so that errors are handled themselves by zope/plone, as other requests?



Cheers and regards



==> var/log/gunicorn-stdout---supervisor-JhaTfg.log <==
2012-05-24 01:41:16 [15137] [ERROR] Error handling request
Traceback (most recent call last):
File "/home/user/testing/eggs/gunicorn-0.14.3-py2.6.egg/gunicorn/workers/sync.py", line 100, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/user/testing/eggs/repoze.retry-1.0-py2.6.egg/repoze/retry/__init__.py", line 90, in __call__
app_iter = self.application(environ, replace_start_response)
File "/home/user/testing/eggs/repoze.tm2-1.0b2-py2.6.egg/repoze/tm/__init__.py", line 24, in __call__
result = self.application(environ, save_status_and_headers)
File "/home/user/testing/eggs/repoze.vhm-0.14-py2.6.egg/repoze/vhm/middleware.py", line 106, in __call__
return self.application(environ, start_response)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/WSGIPublisher.py", line 255, in publish_module
response = _publish(request, 'Zope2')
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/WSGIPublisher.py", line 185, in publish
object = request.traverse(path, validated_hook=validated_hook)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/BaseRequest.py", line 518, in traverse
return response.notFoundError(URL)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/HTTPResponse.py", line 718, in notFoundError
"<p><b>Resource:</b> %s</p>" % escape(entry))
NotFound: <h2>Site Error</h2>
<p>An error was encountered while publishing this resource.
</p>




Using the login Details via Application

I have a CURL(in C++) to send my user and pass to remauth.php file so i think i do something wrong on remuth.php ( because i am basic in php and my program can not run because the auth not passed.)
I use login via Application.



my CURL:



bool Auth_PerformSessionLogin(const char* username, const char* password)
{
curl_global_init(CURL_GLOBAL_ALL);

CURL* curl = curl_easy_init();

if (curl)
{
char url[255];
_snprintf(url, sizeof(url), "http://%s/remauth.php", "SITEADDRESS.com");

char buf[8192] = {0};
char postBuf[8192];
_snprintf(postBuf, sizeof(postBuf), "%s&&%s", username, password);

curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, AuthDataReceived);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&buf);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "IW4M");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBuf);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

CURLcode code = curl_easy_perform(curl);
curl_easy_cleanup(curl);

curl_global_cleanup();

if (code == CURLE_OK)
{
return Auth_ParseResultBuffer(buf);

}
else
{
Auth_Error(va("Could not reach the SITEADDRESS.comt server. Error code from CURL: %x.", code));

}

return false;
}

curl_global_cleanup();
return false;
}


and my remauth.php:



<?php
ob_start();
$host=""; // Host name
$dbusername=""; // Mysql username
$dbpassword=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$dbusername", "$dbpassword") or die(mysql_error());
mysql_select_db("$db_name") or die(mysql_error());

// Define $username and $password
//$username=$username;
//$password=md5($_POST['password']);
//$password=$password;

$username=$_POST['username'];
$password=$_POST['password'];
//$post_item[]='action='.$_POST['submit'];


// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
$row = mysql_fetch_assoc($result);
if (md5(md5($row['salt']).md5($password)) == $row['password']){
session_register("username");
session_register("password");
echo "#";
return true;
}
else {
echo "o";
return false;
}
}
else{
echo "o";
return false;
}
ob_end_flush();
?>


///////////////////////////////////





Exception when trying to parse JSON from a MySQL query

I'm having a problem parsing the JSON response from MySQL in Java.



try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://parkfinder.zxq.net/default.php");
httppost.setEntity(new UrlEncodedFormEntity(coordinatesToSend));
HttpResponse response = httpclient.execute(httppost);
Log.d("HTTP Client", "HTTP Request made");

HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,
"iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(bufferedReader.readLine() + "\n");

String line = "0";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
bufferedReader.close();
result = sb.toString();
Log.d("RESULT", result);
JSONObject json_data = new JSONObject(result);
Log.d("JSON","Finished");
JSONArray nameArray = json_data.names();
JSONArray valArray = json_data.toJSONArray(nameArray);
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}

} catch (Exception e) {
// TODO: handle exception
}


This is the MySQL Accessing and retreiving info, and parsing it afterwars.
the



Log.d("RESULT", result);


line posts the correct results:



2[{"longtitude":"32.32","latitude":"33.12"}]


however the



Log.d("JSON","Finished");


Never gets called,
so the problem seems to be on this line



JSONObject json_data = new JSONObject(result);


This while thing is taken from a tutorial which I saw many examples of it over the internet and on this site, some stated errors, but not this one.



Any help would be great!
Thanks



EDIT:
The printStackTrace() output:



0`5-14 21:38:18.639: WARN/System.err(665): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of 2[{"longtitude":"32.32","latitude":"33.12"}]`


The php code:



<?php
$host = "localhost";
$user = "**MASKED**";
$password = "**MASKED**";
$database = "parkfinder_zxq_coordinates";
$connection = mysql_connect($host, $user, $password) or die("couldn't connect to server");
$db = mysql_select_db($database, $connection) or die("couldn't select database.");
//$request_parked = $_REQUEST['parked'];
$request_long = $_REQUEST['longtitude'];
$request_lat = $_REQUEST['latitude'];
//if ($request_parked == 'FIND') {
$q = mysql_query("SELECT * FROM Coordinates");
while ($e = mysql_fetch_assoc($q))
$output[] = $e;

print (json_encode($output));
//}

mysql_close();
?>




Read and Write Data to Excel without Installing Office

I am working on a WPF 4.0 application which uses the Microsoft Office Interop to read and write to Excel files. But I am facing a scenario where I need to read/write data from/to Excel files on systems that do not have Office installed.



This is somewhat a repeat of this question. The only reason I reposted this question because the earlier post was 3 years old and I just wanted to know if there is a better way available right now.



The requirement is that I need to write into and save the file as .xls/.xlsx formats and read from the same. I am supporting both the format using the Interop right now.




  • Buying a license is not an option.

  • Installing Excel is not an option.

  • Need to Support Read/Write from .xls/.xlsx formats.

  • Easy to Implement as I am a little behind schedule. Would not be able to give a lot of time on implementation.

  • Need a solution that is trustworthy and robust, meaning it should be something that you have used personally or have a good feedback about.

  • Would prefer a solution that can cater to both read/write and can support both .xls/.xlsx formats. If something like this doesn't exist, can use different solutions, but all the above points would apply to them individually.

  • Don't need suggestions, but more like guidance.



Please do not vote to close this question as duplicate as the other ones do not give a concrete solution. There are too many suggestions. I need a solution that you are confident about as this application goes into final build soon and if I do not get any robust solution to this, we might end up releasing as is.





android - one package replaces another

Android.
Eclipse.
Samsung S2
I have two apps I wrote.
Two different packages.
Both can be built and both run OK on the virtual and real device.
I want to leave both of them on the real device to play around with them for a couple of weeks.
Every time I install one, it replaces the other. Same happens whether I installing by running it from eclipse or by installing the APK straight on the phone.
The files have different names. The app names are different. I tried different package names. No luck.



What am I doing wrong?





Setting up an Outlook email programmatically in Windows

How would I go about this? What language would I need to use (Python preferred, as the rest of my installation script is in Python)? Something with access to the .NET libraries (VB.NET, C#, IronPython, maybe PyWin32) or COM? Or is there just some easy command-line trick?



I'm not against using a .NET library or COM object, but my knowledge of them is limited and I'm using standard Python (and don't know C# or VB, though I'm not against learning).



I'm talking about mostly Outlook 2007 and Outlook 2010. The more generic the better, because it'll be used for users who will be assigned both.





How can I calculate the level of a node in a perfect binary tree from its depth-first order index?

I have a perfect binary tree, i.e. each node in the tree is either a leaf node, or has two children, and all leaf nodes are on the same level. Each node has an index in depth-first order.



(E.g. in a tree with 3 levels the root node has index 0, the first child has 1, the first child of the first child has 2, the second child of the first child has 3, the second child has 4, the first child of the second child has 5, the second child of the second child has index 6.



      0
/ \
1 4
/ \ / \
2 3 5 6


)



I know the size of tree (number of nodes/maximum level), but only the index of a particular node, and I need to calculate its level (i.e. its distance to the rootnode). How do I do this most efficiently?





MVC3 EF app in Azure, why do I have to warm it up every once a while?

I am testing my MVC3 + EF app hosted in Azure. The problem I am having now is that every once a while, say 4-5 hours or a day, when I try to visit the page, it is very slow. It takes about 6-8 seconds to load, then the second load would be a lot faster. I have static content cahced, js at the bottom of the page. So I suspect this is because of warm up, but my question here is why do I have to warm it up once a while.



PS: my app is deployed in production environment, I haven't launched it, so it is only me and my team mate been visiting it so far, it has less then 10-20 page requests from us in day, mostly happen at night time.





Want to do Fruite Ninja like swipe on Sprite?

I am new in cocos2d iphone game development.



And now a days I am stucked at a point i want to do fruit ninja like swipe on a sprite and



want to perform a function after swipe at sprite.I done Googling but did not get solution.i need your kind help.
Thanks



 CCSprite *object=[CCSprite spriteWithFile:@"shield.png"];
[self addRecognizers:object];
[object setPosition:ccp(166,160)];
[self addChild:object];

//now function add recognizers
- (void) addRecognizers:(CCSprite*)node
{
UISwipeGestureRecognizer *swipeMe=[[[UISwipeGestureRecognizer alloc ]init] autorelease];
[swipeMe setDirection:UISwipeGestureRecognizerDirectionRight|UISwipeGestureRecognizerDirectionLeft|UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown];
recognizer = [CCGestureRecognizer CCRecognizerWithRecognizerTargetAction:swipeMe target:self action:@selector(blink:node:)];

[node addGestureRecognizer:recognizer];
}


This is the code i am using





Click Event with fadeToggle() - what is wrong with my code?

I created an interactive map of London using the <map> tag which has 15 <area> tags defined. Upon clicking on any of the 15 areas, the source of the map is replaced by another, according to the area which was clicked on. All the areas have an individual id and the source changes according to that id.



Clicking again on the area reverts the map image back to its original source.



The simplified HTML for this is a bit like so:



<IMG id="londonmap" SRC="images/londonmap.png" USEMAP="#london">
<map name="london">
<area id="dalston" href="#" shape="rect" coords="364,75,500,200"
alt="Dalston Tube Stop" title="Dalston Area">
</map>


The jQuery I used for clicking and unclicking looks as follows:



$(document).ready(function()
{
$('#dalston').click(function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});


Everything up to here works just fine. Now, I thought it would be nice, for just a bit of an extra effect to have the changing images .fadeToggle() when clicked for a smoother transition and as such changed to code to this:



$(document).ready(function()
{
$('#dalston').click(function() {
$('#londonmap').fadeToggle('slow', function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});
});


The problem now is that only half the code reacts as I expected - the original image fades out, but the second one never takes its place. I'm guessing it has something to do with the order in which the events happen, but being a bit of a noob in jQuery I can't really tell what's going wrong.



Any help would be much appreciated as this is the last thing stopping me from finishing the map!





Convert code in MS Access to SQL server

The following two functions, I would like to convert them from Access into SQL server, how can I moddify my code? Thank you so much. I never use SQL server before, and trying to learn it hard. LIS is a drive



Public Function PathDate(Ndate As Date) As Long
PathDate = (Year(Ndate) * 10000) + (Month(Ndate) * 100) + Day(Ndate)
End Function

Public Function NormalDate(LISDate As Long) As Date

If (LISDate = -1) Then
NormalDate = "-1"
Else
NormalDate = MonthName(LISDate \ 100 Mod 100) & " " & LISDate Mod 100 & " ," & LISDate \ 10000
End If
End Function




Renaming Key of Item in Collection with VBA in Excel

I have a collection as follows:



Set NodeColl = New Collection
NodeColl.Add "Node 1", "Node 1"
NodeColl.Add "Node 2", "Node 2"
NodeColl.Add "Node 3", "Node 3"


I am wondering if there is an easy way to rename the keys of selective items without affecting other items or the collection itself. For example, something like NodeColl.Items("Node 1").Key = "Some string"





Saxon in Java: XSLT for CSV to XML

Mostly continued from this question: XSLT: CSV (or Flat File, or Plain Text) to XML



So, I have an XSLT from here: http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html



And it converts a CSV file to an XML document. It does this when used with the following command on the command line:




java -jar saxon9he.jar -xsl:csv-to-xml.csv -it:main -o:output.xml




So now the question becomes: How do I do I do this in my Java code?



Right now I have code that looks like this:



TransformerFactory transformerFactory = TransformerFactory.newInstance();
StreamSource xsltSource = new StreamSource(new File("location/of/csv-to-xml.xsl"));
Transformer transformer = transformerFactory.newTransformer(xsltSource);
StringWriter stringWriter = new StringWriter();
transformer.transform(documentSource, new StreamResult(stringWriter));
String transformedDocument = stringWriter.toString().trim();


(The Transformer is an instance of net.sf.saxon.Controller.)



The trick on the command line is to specify "-it:main" to point right at the named template in the XSLT. This means you don't have to provide the source file with the "-s" flag.



The problem starts again on the Java side. Where/how would I specify this "-it:main"? Wouldn't doing so break other XSLT's that don't need that specified? Would I have to name every template in every XSLT file "main?" Given the method signature of Transformer.transform(), I have to specify the source file, so doesn't that defeat all the progress I've made in figuring this thing out?



Edit: I found the s9api hidden inside the saxon9he.jar, if anyone is looking for it.





jQuery convert data-* attributes to lower cammel case properties

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?



$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();

var options = {};

if (data['class-name']) {
options.className = data['class-name'];
}

if (data['align-x']) {
options.alignX = data['align-x'];
}

if (data['align-y']) {
options.alignY = data['align-y'];
}

if (data['offset-y']) {
options.offsetY = data['offset-y'];
}

if (data['offset-x']) {
options.offsetX = data['offset-x'];
}

$this.poshytip(options);
});




jquery autocomplete custom result list

So having this next following code:



var obj = $("#search_input").autocomplete({
minLength: 2,
source: function(req, add) {
$.getJSON("do.php", { OP: "news_search", category: cat_id, get: req }, function(results){
var suggestions = [];
$.each(results, function(i, val){
suggestions.push(val)
});
add(suggestions);
});
},
select: function(event, ui){
console.log(ui);
$("#search_input").val(ui.item.label).attr('data-target', ui.item.value);
return false;
}
}).data("autocomplete");
obj && (obj._renderItem = function(ul, item) {
console.log(item);
return $("<li></li>")
.data("item.autocomplete", item)
.append('<p class="autocomplete-list"><img src="'+item.icon+'" alt="Icono Noticia" /> <a>'+ item.label+'</a></div><div class="clearfix"></div><hr size="1"/>')
.appendTo(ul);
});


As you can see, I am trying to achieve a custom autocomplete result list and by that I mean that on the left of the result list I want to display a photo related with the result, and on the right the text. On click/select it is supposed to set the input field with an extra field data-target where it should contain the article id.



The problem is that I can't get the select to work, I keep getting: d.item is undefined in firebug's console.



Any suggestions?



BTW, I use the var obj = $(...).data("autocomplete"); as it was suggested and accepted on a similar question on stackoverflow, but for me it doesn't work.





Using finally instead of catch

I've seen this pattern a few times now:



        bool success = false;
try
{
DoSomething();
success = true;
}
finally
{
if (!success)
Rollback();
}


And I've been wondering: Why is this better than using catch for rollbacks?



        try
{
DoSomething();
}
catch
{
Rollback();
throw;
}


What are the differences between the two ways of making sure changes are rolled back on failure?





do { } while(0) vs. if (1) { } in macros [closed]


Possible Duplicate:

Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?






When one needs to execute multiple statements within preprocessor macro, it's usually written like



#define X(a) do { f1(a); f2(a); } while(0)


so when this macro is used inside expressions like:



if (...)
X(a);


it would not be messed up.



The question is: wherever I've seen such expression, it's always do { ... } while(0);. Is there any reason to prefer such notion over (in my opinion more clear one) if (1) { ... }? Or am I wrong in my observations and they are equally popular?





How to force UIImagePickerController to record video in landscape mode

I my application is running potrate mode but I want to record video in landscape mode.



    self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.editing=FALSE;
//self.imgPicker.allowsImageEditing = YES;
self.imgPicker.delegate = (id)self;

[self.imgPicker shouldAutorotateToInterfaceOrientation: UIInterfaceOrientationLandscapeRight];
//self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
#if !(TARGET_IPHONE_SIMULATOR)
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;

Can this Recursive Solution be written up into a T-SQL Query using CTE or OVER?

Lets imagine you have the following table called Table1 of Orders in chronological order returned from an In-line UDF. Please note that the OrderID may be out of sync so I have intentionally created an anomaly there (i.e. I have not included the Date field but I have access to the column if easier for you).



   OrderID  BuySell  FilledSize  ExecutionPrice  RunningTotal AverageBookCost  RealisedPnL
339 Buy 2 24.5 NULL NULL NULL
375 Sell 3 23.5 NULL NULL NULL
396 Sell 3 20.5 NULL NULL NULL
416 Sell 1 16.4 NULL NULL NULL
405 Buy 4 18.2 NULL NULL NULL
421 Sell 1 16.7 NULL NULL NULL
432 Buy 3 18.6 NULL NULL NULL


I have a function that I would like to apply recursively from the top to the bottom that will calculate the 3 NULL columns, however the imputs into the function will be the outputs from the previous call. The function I have created is called mfCalc_RunningTotalBookCostPnL and I have attached this below



CREATE FUNCTION [fMath].[mfCalc_RunningTotalBookCostPnL](
@BuySell VARCHAR(4),
@FilledSize DECIMAL(31,15),
@ExecutionPrice DECIMAL(31,15),
@OldRunningTotal DECIMAL(31,15),
@OldBookCost DECIMAL(31,15)
)

RETURNS @ReturnTable TABLE(
NewRunningTotal DECIMAL(31,15),
NewBookCost DECIMAL(31,15),
PreMultRealisedPnL DECIMAL(31,15)
)
AS
BEGIN
DECLARE @SignedFilledSize DECIMAL(31,15),
@NewRunningTotal DECIMAL(31,15),
@NewBookCost DECIMAL(31,15),
@PreMultRealisedPnL DECIMAL(31,15)

SET @SignedFilledSize = fMath.sfSignedSize(@BuySell, @FilledSize)
SET @NewRunningTotal = @OldRunningTotal + @SignedFilledSize
SET @PreMultRealisedPnL = 0
IF SIGN(@SignedFilledSize) = SIGN(@OldRunningTotal)
-- This Trade is adding to the existing position.
SET @NewBookCost = (@SignedFilledSize * @ExecutionPrice +
@OldRunningTotal * @OldBookCost) / (@NewRunningTotal)
ELSE
BEGIN
-- This trade is reversing the existing position.
-- This could be buying when short or selling when long.
DECLARE @AbsClosedSize DECIMAL(31,15)
SET @AbsClosedSize = fMath.sfMin(ABS(@SignedFilledSize), ABS(@OldRunningTotal));

-- There must be Crystalising of PnL.
SET @PreMultRealisedPnL = (@ExecutionPrice - @OldBookCost) * @AbsClosedSize * SIGN(-@SignedFilledSize)

-- Work out the NewBookCost
SET @NewBookCost = CASE
WHEN ABS(@SignedFilledSize) < ABS(@OldRunningTotal) THEN @OldBookCost
WHEN ABS(@SignedFilledSize) = ABS(@OldRunningTotal) THEN 0
WHEN ABS(@SignedFilledSize) > ABS(@OldRunningTotal) THEN @ExecutionPrice
END
END

-- Insert values into Return Table
INSERT INTO @ReturnTable
VALUES (@NewRunningTotal, @NewBookCost, @PreMultRealisedPnL)

-- Return
RETURN
END


So the t-SQL command I am looking for (I dont mind if someone can creates an Outer Apply too) would generate the following Result/Solution set:



OrderID BuySell FilledSize ExecutionPrice RunningTotal AverageBookCost RealisedPnL
339 Buy 2 24.5 2 24.5 0
375 Sell 3 23.5 -1 23.5 -2
396 Sell 3 20.5 -4 21.25 0
416 Sell 1 16.4 -5 20.28 0
405 Buy 4 18.2 -1 20.28 8.32
421 Sell 1 16.7 -2 18.49 0
432 Buy 3 18.6 1 18.6 -0.29


A few notes, the above stored procedure calls a trivial function fMath.sfSignedSize which just makes ('Sell',3) = -3. Also, for the avoidance of doubt, I would see the solution making these calls in this order assuming I am correct in my calculations! (Note that I start off assuming the OldRunningTotal and OldBookCost are both zero):



SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',2,24.5,0,0)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',3,23.5,2,24.5)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',3,20.5,-1,23.5)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',1,16.4,-4,21.25)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',4,18.2,-5,20.28)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',1,16.7,-1,20.28)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',3,18.6,-2,18.49)


Obviously, the [fMath].[mfCalc_RunningTotalBookCostPnL] may need to be tweaked so that it can start off with NULL entries as the OldRunningTotal and OldBookCost but this is trivially done. The SQL Set theory of applying the resursive nature is a little harder.



Many thanks,
Bertie.





New Map Scheme of Bing Maps

How can I use New Map Scheme of Bing Maps in my Windows Phone Application



as you can see here:
http://pocketnow.com/phones/bing-maps-on-windows-phone-7-is-using-new-map-scheme





One hour offset in JSON dates

Why does this happen?



 new Date(2013, 5, 30).toJSON()
"2013-06-29T23:00:00.000Z"


It looks like one hour offset.



Thanks.





MySQL query to display periods between dates

In my table, I have two separate date fields, X and Y. In Field x I have the date of 13/08/2008 and in field Y I have the date of 13/08/2015.



I was wondering if there is a sql way working out what the six monthly date periods are between field X and Y, having the results displayed on separate lines? So, I was hoping to have the following results in two fields:



BEGIN     | END
13-Aug-08 | 13-Feb-09
13-Feb-09 | 13-Aug-09
13-Aug-09 | 15-Feb-10
15-Feb-10 | 13-Aug-10
13-Aug-10 | 14-Feb-11
14-Feb-11 | 15-Aug-11
15-Aug-11 | 13-Feb-12
13-Feb-12 | 13-Aug-12
13-Aug-12 | 13-Feb-13
13-Feb-13 | 13-Aug-13
13-Aug-13 | 13-Feb-14
13-Feb-14 | 13-Aug-14
13-Aug-14 | 13-Feb-15
13-Feb-15 | 13-Aug-15


Is this possible?



Thanks





How to call alarm from other application?

I'm creating Android App that will notify user to read book at given times, what I need to create so alarm and application will fire this alarm at given time, there can be more than 1 alarm and when dialog will appear it should show me 2 options like Read(this should go directly to MyApp) and Cancel, so my question is how can I do it in Android. Any ideas would be much more appreciated. Thanks beforehand





Tuesday, May 22, 2012

run javascript code on AJAX request

i have a upload dialog that allow me to upload files with plupload, but i have a problem,
when i load content directly, it work, but when i load it with an ajax request, javascript code will execute, but dom elements not ready yet, when i make a small delay with timeout, it worked, how i can run javascript code , after ajax dom ready?



blew code load with ajax request:



    <form enctype="multipart/form-data" method="POST" action="admin.php?do=media&action=file-upload">

<div id="uploadForm">

<div id="fileList">



</div>

<a href="#" id="selectFile">[Select File]</a>
<a href="#" id="uploadFile">[Start Upload]</a>

</div>

</form>

<script type="text/javascript">
// $(function(){}); not working when data loaded with ajax request
var ajaxUpload = new plupload.Uploader({

runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',

});


ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('selectFile'));
});

$('#uploadFile').click(function(){
alert('Something');
});

ajaxUpload.init();


</script>




Get Value of Propperty ( List<long>) in Post Action at ASP.NET MVC3

This is My model:



    public class MyModel {
public List<long> NeededIds { get; set; }
public string Name { get; set; }
}


My Controllers:



public ActionResult Create() {

MyModel model = new MyModel();
model.NeededIds = new List<long> { 1, 2, 3, 4 };
return View(model);
}

[HttpPost]
public ActionResult Create(MyModel model) {

string name = model.Name;
List<long> ids = model.NeededIds;


return RedirectToAction("Index");
}


And View:



@model TestMVC.Models.MyModel

@using(Html.BeginForm()) {

<table>
<thead>
<tr>
<th>
Id
</th>
</tr>
</thead>
<tbody>
@foreach(long id in Model.NeededIds) {
<tr>
<td>
@id
</td>
</tr>
}
</tbody>
</table>

@Html.ValidationSummary(true)
<fieldset>
<legend>MyModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}


I set NeededIds in Get action and in view I can see NeededIds also I need it in Post action but in post action the NeededIds is always null, how can I get the property value in post action when i set it in get action? what is your suggestion?





Test notification bar in Android

I am writing testing framework to test an application.This application receives IM(audio/video) and then notifies the user through notification bar.



I have to automate the part that if a notification is received , I click on that notification item , is there any way to do it through testing framework in android.





LINQ2SQL Stack overflow

I am getting a stack overflow with the following code. I know what the problem is, that it executes all "GetAllPages" in the



           Children = new LazyList<Page>(from p in GetAllPages(language)
where p.ParentPage == s.Id
select p)


before it adds the p.ParentPage == s.Id



private IQueryable<Page> GetAllPages(string language)
{
return from s in context.Pages
where (from c in GetAllContent()
where c.PageId == s.Id &&
c.Language.ToLower() == language.ToLower()
select c).Any()

let contents = (from c in GetAllContent()
where c.PageId == s.Id
select c)
select new Page()
{
Id = s.Id,
SiteId = s.SiteId,
Type = s.Type,
Template = s.Template,
ParentPage = s.ParentPage,
Visible = s.Visible,
Order = s.Order,

Contents = contents.ToList(),
Children = new LazyList<Page>(from p in GetAllPages(language)
where p.ParentPage == s.Id
select p)
};
}


How can i do this, correctly?



UPDATE:
The reason behind the code is that, i have a tree structured menu, where one menu item can have 0 to many child items.
The language part can be skipped, but my site support multiple languages, and with the language parameters do i only want menu items there have a content of the given language.





Disable @Webservice loading during start up

How to disable @Webservice loading during start up to save some loading time in xfire?



I have a bunch of services with @Webservice annotation. They are all being loaded during the startup and causing a slow startup. I don't want to load these if I test non-services in dev instance. I am wondering if there is a way to disable this by setting system property or something .





How can we count the number of check boxes checked inside a grid view in asp.net using javascript?

I asked this question in an interview. In asp.net how can we check the no. of checked boxes using javascript.





C# Regex - Split and Keep Splitter

Related:
http://stackoverflow.com/a/2910549/194031



I have a string like:



"abc defgh <!inc(C:\my files\abc.txt)!>kdi kdkd<!inc(C:\my files\abc.txt)!>"


and I want to get:



["abc defgh ", "C:\my files\abc.txt", "kdi kdkd", "C:\my files\abc.txt"]


Also, I don't want



"abc <!inc(C:\my files\abc.txt adf" (missing end bracket) 


to get split.



Based on the related question and other similar answers, I need to use look aheads, but I can't figure out how to use them while accomplishing removing the tags and not splitting if part of the tags are missing.





What is the difference between access specifiers and access modifiers?

In Java, are access specifiers and access modifiers the same thing?





MS Build copy a list of directories stored in Item

I have a text file which contains some locations of the files which I want to copy to a temp directory



---- List.txt ----
Build\Java
Build\Classes


Now, I am fetching this list into an Item



<ReadLinesFromFile File="List.txt" >
<Output TaskParameter="Lines"
ItemName="DirectoryList" />
</ReadLinesFromFile>


Now, In order to append the full path, and add some excludes, I am again storing it into another ItemGroup:



<ItemGroup>
<PackageList Include="$(BuildPath)\%(DirectoryList.Identity)\**\*.*"
Exclude="$(BuildPath)\%(DirectoryList.Identity)\**\*.pdb" />
</ItemGroup>

<Copy SourceFiles="%(PackageList.Identity)"
DestinationFolder="$(PackageTemp)\%(RecursiveDir)" />


ISSUE:



Actual Dir -



C:\Work\Build\Java\Debug
C:\Work\Build\Java\Release
C:\Work\Build\Classes\*.class


Content in O/p



C:\temp\Debug
C:\temp\Release
C:\temp\*.class


How to make it copy the corresponding "Java" and "Classes" folder also?





FileInputStream using package path

I am trying to read a file like :



FileInputStream fileInputStream = new FileInputStream("/com/test/Test.xml");


I am always getting the file not found exception. How can i make it work? Will the inputstream takes the relative path or not?





How to reset auto increment column in mysql table

Here item_category_id is auto increment value in the mysql table. Now i need to delete all the values & next insertion should start from 1. Now if i delete all values & try to insert a new row then it starts with some 30's & 40's.



  item_category_id  item_category_name
1 qqq
25 ccc
32 vvv
29 bb
4 bbb
31 hhh
34 mmm
33 rrr




Change the author name of power point file

Can I change the author of a power point file using PHP or any other language ?





Redirecting to previous URL after login - Rails

For the app that I am writing, I am using simple hand made authentication (as described on Railscast.com). Using some code from Ryan Bates' NiftyGenerators gem, I have an authentication model that has some useful methods for authentication. This module is included into application_controller.rb.



One of the methods that I want to use is called redirect_to_target_or_default. I know this is what I need to redirect a user to the page that they were on once they have authenticated but I don't know where I should call this method? If someone could give me an idea on how to use this method, I would greatly appreciate it.



ControllerAuthenticaion Module Code



enter image description here





Method not found using DigestUtils in Android

I am trying to use the library DigestUtils in Android 2.3.1 using JDK 1.6, however I get the following error when executing the app:



Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex



Here you have the stacktrace:



02-03 10:25:45.153: I/dalvikvm(1230): Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex
02-03 10:25:45.153: W/dalvikvm(1230): VFY: unable to resolve static method 329: Lorg/apache/commons/codec/binary/Hex;.encodeHexString ([B)Ljava/lang/String;
02-03 10:25:45.153: D/dalvikvm(1230): VFY: replacing opcode 0x71 at 0x0004
02-03 10:25:45.153: D/dalvikvm(1230): VFY: dead code 0x0007-0008 in Lorg/apache/commons/codec/digest/DigestUtils;.shaHex ([B)Ljava/lang/String;
02-03 10:25:45.163: D/AndroidRuntime(1230): Shutting down VM
02-03 10:25:45.163: W/dalvikvm(1230): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-03 10:25:45.173: E/AndroidRuntime(1230): FATAL EXCEPTION: main
02-03 10:25:45.173: E/AndroidRuntime(1230): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString
02-03 10:25:45.173: E/AndroidRuntime(1230): at org.apache.commons.codec.digest.DigestUtils.md5Hex(DigestUtils.java:226)
02-03 10:25:45.173: E/AndroidRuntime(1230): at com.caumons.trainingdininghall.ConnectionProfileActivity.onCreate(ConnectionProfileActivity.java:20)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.os.Looper.loop(Looper.java:123)
02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.main(ActivityThread.java:3647)
02-03 10:25:45.173: E/AndroidRuntime(1230): at java.lang.reflect.Method.invokeNative(Native Method)
02-03 10:25:45.173: E/AndroidRuntime(1230): at java.lang.reflect.Method.invoke(Method.java:507)
02-03 10:25:45.173: E/AndroidRuntime(1230): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-03 10:25:45.173: E/AndroidRuntime(1230): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-03 10:25:45.173: E/AndroidRuntime(1230): at dalvik.system.NativeStart.main(Native Method)


The line of code which causes the exception is:



String hash = DigestUtils.shaHex("textToHash");



I have executed the same code in a Java class outside Android and it works! So, I do not know why when working with Android it does not work... I put the libraty inside a new libs/ folder in my app and updated the BuildPath to use it. If I try to use md5 instead of sha1 I get the same exception. Any help would be appreciated! Thank you.





Create long types in JPA entities

I'm trying to generate JPA entities from tables using eclipse plugins, I defined some BIG INT and Date columns. I would like to have long properties in Entity class for those BIGINT columns, But It generates as String. Please help me how to resolve it?





OpenCV frame capture from AVI

I am working on a project with openCV 2.2. I need to do processing on each frame of an AVI file but when I run my code it only grabs the first frame of the file. The CV_CAP_PROP_POS_FRAMES does not seem to be working. Any ideas why not?



    CvCapture* capture = cvCaptureFromAVI("test1.avi");

IplImage *img = 0;

if (!cvGrabFrame(capture)) {
printf("Error: Couldn't open the image file.\n");
return 1;
}

int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
int posFrame = 1;
for(int i =0; i <= numFrames; i++){
cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, i);
posFrame = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES);

img = cvGrabFrame(capture);
cvNamedWindow("Image:", CV_WINDOW_AUTOSIZE);
cvShowImage("Image:", img);
printf("%i\n",posFrame);

cvWaitKey(0);

cvDestroyWindow("Image:");
}




Inspecting a .exe to understand with what version of Visual C++ it was built

Is there a way to check what version of Visual C++ was used to build a given .exe?



I know that if the .exe uses dynamic link with CRT that is easy: I can just use Dependency Walker and read the MSVCRxx.DLL version, e.g. a dependency on MSVCR90.DLL means that the .exe is built with Visual C++ 2008 i.e. VC9; but what about the case of static linking with CRT?





How to decide between abstract and interface?

What is difference between following interface and abstract class:



 public interface MyInterface
{
public int get1();
public int get2();
public int get3();
}

public abstract class MyAbstract
{
public abstract int get1();
public abstract int get2();
public abstract int get3();
}


Interviewer was not convinced with following answers, he wanted to hear something else:




  1. I have to extend MyAbstract and then I cannot have more extends, whereas in case of implementing MyInterface I am open to have inheritance.


  2. I have to provide implementation of all three methods if used "implements MyInterface", whereas in case of "extends MyAbstract" I am open to carry forward abstractness.


  3. Design perspective: All libraries work on interfaces not on abstract classes, it is good design practice to use interfaces so that at any time in future I can create any class (implements MyInterface) that can be used in some method of library. (basically same as point one)




What else there could be? I am not concerned with the variables in interface/abstract class etc. How to decide which one to use?





filling a array with random numbers between 0-9 in c# [closed]


Possible Duplicate:

filling a array with uniqe random numbers between 0-9 in c#






I have a array like "page[100]" and i want to fill it with random numbers between 0-9 in c#...
how i can do this?
i used :



IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
{
List<int> candidates = new List<int>();
for (int i = minInclusive; i <= maxInclusive; i++)
{
candidates.Add(i);
}
Random rnd = new Random();
while (candidates.Count > 1)
{
int index = rnd.Next(candidates.Count);
yield return candidates[index];
candidates.RemoveAt(index);
}
}


this way :



int[] page = UniqueRandom(0,9).Take(array size).ToArray();


but it just gave me 9 unique random numbers but i need more.
how i can have a array with random numbers that are not all the same?





how to accept file or path as arguments to method in python

I am trying to write a method that will accept either an opened file



myFile = open("myFile.txt")
obj.writeTo(myFile)
myFile.close()


or a string with a path



obj.writeTo("myFile.txt")


The method is implemented as follows:



def writeTo(self, hessianFile):
if isinstance(hessianFile,file):
print("File type")
elif isinstance(hessianFile,str):
print("String type")
else:
pass


But this raises an error



NameError: global name 'file' is not defined


why is file type not defined? Shouldn't file be defined all the time? How should the implementation be corrected to properly handel both path an file as valid argument types





Monday, May 21, 2012

rails - how to make a GET request to action with parameters

I'm hoping this problem is a fairly simple one as I am relatively new to rails development.
I am trying to make a get request from a controller with a specified action and pass required parameters. This is the relevant code in the helper class:



module ChartsHelper
def chart_tag (action, height, params = {})
params[:format] ||= :json
path = charts_path(action, params)
content_tag(:div, :'data-chart' => path, :style => "height: #{height}px;") do
image_tag('loading.gif', :size => '32x32', :class => 'spinner')
end
end
end


and the corresponding action in the ChartsController:



class ChartsController < ApplicationController

def week_events_bar_chart
days = (params[:days] || 30).to_i
render :json => {
:type => 'AreaChart',
:cols => [['string', 'Date'], ['number', 'subscriptions']],
:rows => (1..days).to_a.inject([]) do |memo, i|
date = i.days.ago.to_date
t0, t1 = date.beginning_of_day, date.end_of_day
subscriptions = Kpsevent.all.count
memo << [date, subscriptions]
memo
end.reverse,
:options => {
:chartArea => { :width => '90%', :height => '75%' },
:hAxis => { :showTextEvery => 30 },
:legend => 'bottom',
}
}
end
end


The routes file has the following:



resource :charts do
get 'week_events_bar_chart'
end


However I get the following output when trying to perform this request:



 Started GET "/charts.week_events_bar_chart?days=14" for 127.0.0.1 at Tue May 22 00:31:48 +1200 2012
Processing by ChartsController#index as
Parameters: {"days"=>"14"}


And the controller action is never called.
Is anyone able to help with this problem?



EDIT: rake routes output:



week_events_bar_chart_charts GET    /charts/week_events_bar_chart(.:format) {:controller=>"charts", :action=>"week_events_bar_chart"}
POST /charts(.:format) {:controller=>"charts", :action=>"create"}
new_charts GET /charts/new(.:format) {:controller=>"charts", :action=>"new"}
edit_charts GET /charts/edit(.:format) {:controller=>"charts", :action=>"edit"}
GET /charts(.:format) {:controller=>"charts", :action=>"show"}
PUT /charts(.:format) {:controller=>"charts", :action=>"update"}
DELETE /charts(.:format) {:controller=>"charts", :action=>"destroy"}




Open two jquery datepickers simultaneously

I have two input fields containing a class that triggers a datepicker to open. Both work fine independently, i.e when I click on one or the other but I want for both datepickers to open when either input field is clicked.



Here is the script part of the code



    $(document).ready(function() {

$( ".datefields" ).datepicker({ dateFormat: 'dd/mm/yy',numberOfMonths: 1, yearRange: "2012:2014", changeYear: true, changeMonth: true});


and this is the html



<div id="quoteformcollection">
<h1>Collection</h1>

<input type"text" class="startTbl locationfields" id="AutoLocStart" value="Please Type a Collection Location"onclick="clearVal(this);"/>
<input type="hidden" id="DepotStart" value=""/></td>

<input type="text" class="datefields" id="collectiondate" value="21/05/2012"/>
<input type"text" class="timefields" value="12:00" />
</div>

<div id="quoteformreturn">
<h1>Return</h1>

<input type"text" class="locationfields" value="Enter the city or location for return" />
<input type"text" id="returndate" class="datefields" value="21/05/2012" />
<input type"text" class="timefields" value="12:00" />
</div>


I have tried looking for an answer myself but am quite new to jquery and struggling a bit so any help would be much appreciated.



I would also like for whatever value is selected in the first datepicker, for the default date in the second to be incremented by x number of days, which again I am not sure of the best way to go about it.



Any advice would be hugely appreciated!





Edit all files in subdirectories with python

I am trying to recursively loop through a series of directories (about 3 levels deep). In each directory is a series of text files, I want to replace a line of text with the directory path if the line contains a certain string so for example.



/path/to/text/file/fName.txt


If a line in fName in fName.txt text contains the string 'String1' I want to replace this line with 'some text' + file where file is the last part of the path.



This seems like it should be easy in python but I can't seem to manage it.



Thanks.





Double and tripple button is shown (DOMNodeInserted)

I have a weird problem:



I am developing a chrome extension that adds a custom button beside the "like" button in facebook. Until now, with alot of help I found a way to run the script even when posts are added to the news feed (without a page refresh). But the problem is that in the timline/ ticker (live feed window in the right) the button duplicates itself over time.



My current script:



$(document).ready(function(){
$(".like_link,.cmnt_like_link").after(
'<span class="dot"> · </span>' +
'<button class="taheles_link stat_elem as_link" title="???? ???&acute;?" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{&quot;tn&quot;:&quot;&gt;&quot;,&quot;type&quot;:22}">' +
'<span class="taheles_default_message">???&acute;?</span><span class="taheles_saving_message">?? ????</span>' +
'</button>'
);

$(".taheles_saving_message").hide();

$(document).bind('DOMNodeInserted', function(event) {
$(event.target).find(".like_link,.cmnt_like_link").after(
'<span class="dot"> · </span>' +
'<button class="taheles_link stat_elem as_link" title="???? ???&acute;?" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{&quot;tn&quot;:&quot;&gt;&quot;,&quot;type&quot;:22}">' +
'<span class="taheles_default_message">???&acute;?</span><span class="taheles_saving_message">?? ????</span>' +
'</button>'
);
$(event.target).find(".taheles_saving_message").hide();
});
});


like_link is the button that is shown in posts/comments in the news feed/any other place. cmnt_like_link is the button that is shown in comments.



If I use #contentArea in the selectors, the custom button is not even added to the ticker. If I use document (current) it is shown in the ticker but duplicates itself. I am wondering what the problem is. I tried to look at the chrome developer panel but with no luck.





Typing generic interfaces

I'm trying to create two interface hierarchies, one for the business model objects and one for the ui. I know it's important to have loose coupling between the layers but part of the application will require drawing diagrams so I need the model objects to be readily available to their corresponding graphical representations and I have a common layer holding interfaces for the model objects..



Common class library code:

Public interface IBase {}
Public interface IBookObject : IBase {}
Public interface ITapeObject : IBase {}

Public class Book : IBookObject {}

Graphics layer code:

Public interface IModelObject<T>

{

T ModelObject { get; set; } // might be a book or tape , etc

}


Public class GraphicObject<T> : IModelObject<T>

{

Public T ModelObject { get; set; }

}


Code use:

IBookObject bk = new Book();

Var go = new GraphicObject<IBookObject>(); // will fail later

//var go = new GraphicObject<IBase>(); // will succeed later

go.ModelObject = bk;

If( go is IModelObject<IBase>) // can't use is IModelObject<IBookObject> as go might be GraphicObject<ITapeObject>

{
Debug.WriteLine("Success");
}


So if I want to test for IBase (and then access ModelObject), I have to make sure that the original object was created with IBase and not a derived interface, and this seems like a cause of bugs later. my questions are:



1) Am I doing something horrible?! :) I might be overlooking a better approach..



2) failing that, is there some way of using the new contravariance c# 4 techniques to make the is line test for any interface deriving from IBase? Alternatively I think it would work if IBook didn't inherit from IBase, but Book (and Tape) implemented both IBook and IBase separately.



3) failing that, is there any way to prevent construction of GraphicObject<IBookObject>() and GraphicObject<ITapeObject>()?



Thank you!





Is const_cast(iterator->second) safe?

I want to know if this code is safe and doesnt have any undefined behavior.



 QueueMap::const_iterator it = m_3playersQueue.find(s->m_GameCode);
if(it == m_3playersQueue.end())
{
std::deque<Session*> stack;
stack.push_back(s);

m_3playersQueue[s->m_GameCode] = stack;
return;
}

const_cast<std::deque<Session*>&>(it->second).push_back(s);

QueueMap is of type std::tr1::unordered_map< uint32, std::deque<Session*> >


Thanks





How to insert a block into a node or template in Drupal 7?

In Drupal 6, it was easy to insert a block into a template with the following code:



$block = module_invoke('views', 'block', 'view', 'block_name');
print $block['content'];


However, using the same instructions in Drupal 7 does not seem to work. I have looked around and cannot find the new method.



Does Drupal 7 have a routine that can allow for pro grammatically inserting a block into a template or node?





Finding the right way to store data

I had planned on using a Dictionary or SortedList for this but as the project evolved while planning it, I'm not sure what to do.



My site will load a bunch of results from a DB Query and I need to be able to store these results somewhere.



Here's how the results look like:



What type of Dictionary/List should be used for this?



So, here's what I am storing:



Result #1 (int) > Name > Value
> Title > Value
> Message > Value
> Date > Value
> Email > Value

Result #2 (int) > Name > Value
> Title > Value
> Message > Value
> Date > Value
> Email > Value

Result #3 (int) > Name > Value
> Title > Value
> Message > Value
> Date > Value
> Email > Value

Result #4 (int) > Name > Value
> Title > Value
> Message > Value
> Date > Value
> Email > Value


... and so on. My main concern is that most of the Dictionaries and Lists and Sorted/Linked lists cannot have dupliate keys or values. So I can't use them for this, because each Result will have all the same Key names, like Name, Title, Message, etc. Values may differ, though many of the values such as Name and Date and other ones will be dupes. So I'm kinda stuck with not knowing which kind of Dictionary/List to choose which allows duplicate keys/names and _not knowing how to get that 'one to many' relationship thing going on so i can store these results properly.



Can someone please help me with what would be the best way to go about this?





Create function that accepts function

I have a function that runs some fairly generic code that does a lot of work connection to a database and setting up different configuration variables. Lets not get into the ethics of this, please bare with me. I have within a couple of if statements of this top-level function code that I run that is actually different from function to function.



This is how it looks now.



function get_users(){
// config
// set application keys
// connect to database
// retrieve user data
// authentication to foreign api
if(something){
// some more red-tape
if(something){
//more more
if(something){
/* finally the good stuff */

// the code here varies from function to function
// eg. get users
// probably will run: inner_get_users();

}
}
}
}

function get_data(){
// config
// set application keys
// connect to database
// retrieve user data
// authentication to foreign api
if(something){
// some more red-tape
if(something){
//more more
if(something){
/* finally the good stuff */

// the code here varies from function to function
// eg. get data
// probably will run: inner_get_data();

}
}
}
}


How I want it to work:



function instance($inner){
// config
// set application keys
// connect to database
// retrieve user data
// authentication to foreign api
if(something){
// some more red-tape
if(something){
//more more
if(something){
/* finally the good stuff */

Call inner

}
}
}
}

function get_data(){


instance(function(
// get the data
));

}


or maybe



function get_users(){

$var = function(
// get the users
);

instance($var);

}


I'm looking for better, dryer, and more maintainable code.





how to solve this error of Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Source type 1 not available'

I have working on pick the photo from gallery and save in gallery



my code is



-(void)onclicksave:(id)sender
{
NSLog(@"onclicksave");
UIImagePickerController *picker=[[UIImagePickerController alloc]init];
picker.delegate=self;

if((UIButton *)sender== openLibrary)
{
picker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;

}
else
{
picker.sourceType=UIImagePickerControllerSourceTypeCamera;
}

[self presentModalViewController:picker animated:YES];

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
imagedisplay.image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];

}


but in this code run time error like



Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Source type 1 not available'



so give any suggestion and source code which is apply in my code





SQL Server 2005 RANK function

I have a problem in SQL Server 2005:



Suppose I have the table PLAYER (string player, int score, bool Active) and the this query :



SELECT PLAYER.player AS NAME,
PLAYER.score AS SCORE,
POSITION = CASE WHEN PLAYER.Active THEN RANK()OVER(ORDER BY score desc) else NULL end
from PLAYER


The problem is that when the player is not active, the positions generated are not consecutive.



For example :



JOHN,10000,1
PETER,5000,NULL (NOT ACTIVE)
CHARLES,2500,3 (SHOULD HAVE POSITION 2, NOT 3)


Sorry for my terrible English, I hope I have explained my point





EXTJS, Unable to bind event handler to controller

I'm using EXTJS with Node.JS and am having difficulty with handling events in the context of the EXTJS MVC framework.



I've been able to easily register click events when defining the Event Listener in the Class Definition of the view, but can't seem to move this code into the controller.



Here's a look at my current code:



//Icon.JS (VIEW)

Ext.define('GeekFlicks.view.Icon', {
extend: 'Ext.button.Button',
alias: 'widget.icon',
height: 48,
width: 48,
text: 'icon',
draggable: true
});


//Icon.JS (CONTROLLER)



Ext.define('GeekFlicks.controller.Icon', {
extend: 'Ext.app.Controller',

models: ['Icon'],
stores: ['Icons'],
views: ['Icon'],

init: function () {
this.control({
'listener': {
click: function(c) {
alert('working');
}
}
});
},
});


Any help or explanations around how EXTJS deals with these sort of events is will be extremely helpful and much appreciated! Thanks.





convert ant script into gradle script

How do you convert ant script into gradle script?
Hi,
Can you please help me to convert ant script into gradle script. I am new user of gradle.







<property name="pm-dir"                value="${PM-DIR}/${BUILD_NUM}" />
<property name="leis-dir" value="${LEIS_DIR}/${BUILD_NUM}" />

<property name="proxy-name" value="${PROXY_JAR_NAME}"/>
<property name="proxy-client-name" value="${PROXY_CLIENT_JAR_NAME}"/>

<property environment="env"/>
<property name="java-home" value="${env.JAVA_HOME}"/>

<condition property="build-pm">
<equals arg1="True" arg2="${BUILD_PM}" />
</condition>

<condition property="build-LEIS">
<equals arg1="True" arg2="${BUILD_LEIS}" />
</condition>


<target name="build-LEIS-components" if="build-LEIS">

<ant antfile="build.xml"
target="clean"
dir="${leis-dir}/LEIS"
inheritAll="false"/>
<ant antfile="build.xml"
target="ejbdoclet"
dir="${leis-dir}/LEIS/BusinessServices"
inheritAll="false"/>
<ant antfile="build.xml"
target="jar"
dir="${leis-dir}/LEIS"
inheritAll="false"/>

<ant antfile="build.xml"
target="clean"
dir="${leis-dir}/ETS/trunk/Entitlements"
inheritAll="false"/>
<ant antfile="build.xml"
target="build"
dir="${leis-dir}/ETS/trunk/Entitlements"
inheritAll="false"/>

<mkdir dir="${leis-dir}/JARS/APP-INF/lib/"/>

<jar jarfile="${leis-dir}/JARS/APP-INF/lib/LEISConfig.jar">
<fileset dir="LEIS/" includes="datetime.properties"/>
<fileset dir="LEIS/" includes="log4j.properties"/>
<manifest>
<attribute name="Built-By" value="${user.name}"/>
</manifest>
</jar>
</target>


<!--========================================================================
Builds pm using the supplied RE build files, modified by us.
========================================================================-->
<target name="build-pm" if="build-pm">




<!-- SPPResourceBundle Overrides -->
<mkdir dir="${pm-dir}/pm2/deploy/propertyoverrides"/>
<copy todir="${pm-dir}/pm2/deploy/propertyoverrides" overwrite="true">
<fileset dir="olwpmconfig/propertyoverrides"/>
</copy>

<!-- copy build.properties into pm dir, complete with kodo key -->
<copy file="olwpmconfig/build.properties" todir="${pm-dir}/pm2/" overwrite="true">
<filterchain>
<replacetokens>
<token key="LOGGINGFLOOR" value="${PERFORMANCE_LOGGING_FLOOR}"/>
<token key="BEADIR" value="${BEA_HOME}"/>
</replacetokens>
</filterchain>
</copy>

<!--the actual Retail Express build scripts to create the pm-main.ear-->
<echo message="Calling pm Build Script"/>
<ant antfile='${pm-dir}/pm2/build/build.xml' target='clean-build' inheritAll="false"/>

<!--delete the extra copy of jdo.dtd-->
<delete file="jdo.dtd" />

<fileset id="required-pm-client-libs" dir="${pm-dir}/pm2/deploy/lib">
<include name="*.jar"/>
<include name="client/*.jar"/>
<exclude name="*tests.jar"/>
</fileset>

<!-- Used to populate value of MANIFEST.MF Class-path attribute. Turns our set of "required" libs
into a nice space separated string to place in the MANIFEST.MF. Property is used in the "dist"
task's jar command. -->
<pathconvert property="client-classpath"
refid="required-pm-client-libs"
pathsep=" "
dirsep="/">
<map from="${pm-dir}/pm2/deploy/lib/" to=""/>
</pathconvert>

<jar update="true" jarfile="${pm-dir}/pm2/deploy/lib/pm-core.jar">
<manifest>
<attribute name="Class-Path" value="${client-classpath}"/>
<attribute name="Main-Class" value="com.retailexp.pm.ui.util.SPPClientStartUp"/>
</manifest>
</jar>

<!-- Creates a file Marimba/BigFix/WhatEver can use to track the version of pm installed on a machine -->
<echo message="${pm_MAJOR_VERSION}.${BUILD_NUM}" file="${pm-dir}/pm2/deploy/lib/version.txt" append="false"/>

<!-- Remove files we place on classpath from ears, Mantis 10624 -->
<!-- pm -->
<move file="${pm-dir}/pm2/deploy/dist/pm-main.ear" tofile="${pm-dir}/pm2/deploy/dist/old-pm-main.ear"/>
<unzip src="${pm-dir}/pm2/deploy/dist/old-pm-main.ear" dest="${pm-dir}/pm2/deploy/dist/">
<patternset>
<include name="lib/pm-server-conf.jar"/>
</patternset>
</unzip>
<move file="${pm-dir}/pm2/deploy/dist/lib/pm-server-conf.jar" tofile="${pm-dir}/pm2/deploy/dist/lib/old-pm-server-conf.jar"/>
<zip file="${pm-dir}/pm2/deploy/dist/lib/pm-server-conf.jar">
<zipfileset src="${pm-dir}/pm2/deploy/dist/lib/old-pm-server-conf.jar">
<exclude name="log4j.properties"/>
<exclude name="ehcache-transactional.xml"/>
</zipfileset>
</zip>
<zip file="${pm-dir}/pm2/deploy/dist/pm-main.ear">
<zipfileset src="${pm-dir}/pm2/deploy/dist/old-pm-main.ear">
<exclude name="lib/pm-server-conf.jar"/>
</zipfileset>
<zipfileset dir="${pm-dir}/pm2/deploy/dist/lib/" includes="pm-server-conf.jar" fullpath="lib/pm-server-conf.jar"/>
</zip>
<!-- EDM -->
<move file="${pm-dir}/pm2/deploy/dist/pm-edm.ear" tofile="${pm-dir}/pm2/deploy/dist/old-pm-edm.ear"/>
<unzip src="${pm-dir}/pm2/deploy/dist/old-pm-edm.ear" dest="${pm-dir}/pm2/deploy/dist/">
<patternset>
<include name="lib/pm-server-conf.jar"/>
</patternset>
</unzip>
<move file="${pm-dir}/pm2/deploy/dist/lib/pm-server-conf.jar" tofile="${pm-dir}/pm2/deploy/dist/lib/old-pm-server-conf.jar"/>
<zip file="${pm-dir}/pm2/deploy/dist/lib/pm-server-conf.jar">
<zipfileset src="${pm-dir}/pm2/deploy/dist/lib/old-pm-server-conf.jar">
<exclude name="log4j.properties"/>
</zipfileset>
</zip>
<zip file="${pm-dir}/pm2/deploy/dist/pm-edm.ear">
<zipfileset src="${pm-dir}/pm2/deploy/dist/old-pm-edm.ear">
<exclude name="lib/pm-server-conf.jar"/>
</zipfileset>
<zipfileset dir="${pm-dir}/pm2/deploy/dist/lib/" includes="pm-server-conf.jar" fullpath="lib/pm-server-conf.jar"/>
</zip>
</target>

<!--========================================================================
Builds LEIS
========================================================================-->
<target name="build-proxy" if="build-LEIS">

<!--copy deploy.properties with the proper jar names and locations-->
<copy file="LEIS/deploy.properties" todir="${leis-dir}/proxy/config/build/" overwrite="true">
<filterchain>
<replacetokens>
<token key="pmCORE" value="${pm_CORE_NAME}"/>
<token key="pmTRANSFER" value="${pm_TRANSFER_NAME}"/>
<token key="PROXYJARNAME" value="${PROXY_JAR_NAME}"/>
<token key="PROXYCLIENTJARNAME" value="${PROXY_CLIENT_JAR_NAME}"/>
<token key="PROXYLIBSDIR" value="${leis-dir}/JARS/"/>
</replacetokens>
</filterchain>
</copy>

<ant antfile="build.xml" target="clean" dir="${leis-dir}/proxy" inheritAll="false" />
<ant antfile="build.xml" target="prod-dist" dir="${leis-dir}/proxy" inheritAll="false">
<property name="build.name" value="${pm_MAJOR_VERSION}.${BUILD_NUM}"/>
</ant>

<ear destfile="${ear-name}" appxml="LEIS/application.xml">
<metainf dir="${leis-dir}/LEIS/conf/EAR/META-INF" includes="weblogic-application.xml"/>
<fileset dir="${leis-dir}/JARS/" includes="*.jar"/>
<fileset dir="${leis-dir}/JARS/" includes="APP-INF/**" excludes="APP-INF/lib/wlfullclient.jar"/>
</ear>

<!-- Place the proxy-client jar in the pm ear-->
<zip update="true" destfile="${pm-dir}/pm2/deploy/dist/pm-main.ear">
<zipfileset dir="${leis-dir}/proxy/dist/" includes="${proxy-client-name}" fullpath="APP-INF/lib/${proxy-client-name}"/>
</zip>

</target>

<target name="build-cpc">
<copy file="${pm-dir}/pm2/deploy/lib/${pm_TRANSFER_NAME}" todir="${leis-dir}/cpc-web-app/webapp/lib/cpc"/>
<ant antfile="build.xml" target="build-all-environments" dir="${leis-dir}/cpc-web-app/webapp" inheritAll="false"/>
</target>

<target name="build-all">
<antcall target="build-LEIS-components"/>
<antcall target="build-pm"/>
<antcall target="build-proxy"/>
<antcall target="build-cpc"/>
</target> </condition>

<condition property="build-LEIS">
<equals arg1="True" arg2="${BUILD_LEIS}" />
</condition>


<target name="build-LEIS-components" if="build-LEIS">

<!--Go through and build the LEIS modules-->
<ant antfile="build.xml"
target="clean"
dir="${leis-dir}/LEIS"
inheritAll="false"/>
<ant antfile="build.xml"
target="ejbdoclet"
dir="${leis-dir}/LEIS/BusinessServices"
inheritAll="false"/>
<ant antfile="build.xml"
target="jar"
dir="${leis-dir}/LEIS"
inheritAll="false"/>



<ant antfile="build.xml"
target="clean"
dir="${leis-dir}/ETS/trunk/Entitlements"
inheritAll="false"/>
<ant antfile="build.xml"
target="build"
dir="${leis-dir}/ETS/trunk/Entitlements"
inheritAll="false"/>


<mkdir dir="${leis-dir}/JARS/APP-INF/lib/"/>


<jar jarfile="${leis-dir}/JARS/APP-INF/lib/LEISConfig.jar">
<fileset dir="LEIS/" includes="datetime.properties"/>
<fileset dir="LEIS/" includes="log4j.properties"/>
<manifest>
<attribute name="Built-By" value="${user.name}"/>
</manifest>
</jar>
</target>


<target name="build-pm" if="build-pm">



<mkdir dir="${pm-dir}/amp2/deploy/propertyoverrides"/>
<copy todir="${pm-dir}/amp2/deploy/propertyoverrides" overwrite="true">
<fileset dir="olwAMPconfig/propertyoverrides"/>
</copy>

<ant antfile='${pm-dir}/amp2/build/build.xml' target='clean-build' inheritAll="false"/>

<!--delete the extra copy of jdo.dtd-->
<delete file="jdo.dtd" />

<fileset id="required-amp-client-libs" dir="${pm-dir}/amp2/deploy/lib">
<include name="*.jar"/>
<include name="client/*.jar"/>
<exclude name="*tests.jar"/>
</fileset>

<!-- Used to populate value of MANIFEST.MF Class-path attribute. Turns our set of "required" libs
into a nice space separated string to place in the MANIFEST.MF. Property is used in the "dist"
task's jar command. -->
<pathconvert property="client-classpath"
refid="required-amp-client-libs"
pathsep=" "
dirsep="/">
<map from="${pm-dir}/amp2/deploy/lib/" to=""/>
</pathconvert>

<jar update="true" jarfile="${pm-dir}/amp2/deploy/lib/amp-core.jar">
<manifest>
<attribute name="Class-Path" value="${client-classpath}"/>
<attribute name="Main-Class" value="com.retailexp.amp.ui.util.SPPClientStartUp"/>
</manifest>
</jar>

<!-- Creates a file Marimba/BigFix/WhatEver can use to track the version of AMP installed on a machine -->
<echo message="${AMP_MAJOR_VERSION}.${BUILD_NUM}" file="${pm-dir}/amp2/deploy/lib/version.txt" append="false"/>

<!-- Remove files we place on classpath from ears, Mantis 10624 -->
<!-- AMP -->
<move file="${pm-dir}/amp2/deploy/dist/amp-main.ear" tofile="${pm-dir}/amp2/deploy/dist/old-amp-main.ear"/>
<unzip src="${pm-dir}/amp2/deploy/dist/old-amp-main.ear" dest="${pm-dir}/amp2/deploy/dist/">
<patternset>
<include name="lib/amp-server-conf.jar"/>
</patternset>
</unzip>
<move file="${pm-dir}/amp2/deploy/dist/lib/amp-server-conf.jar" tofile="${pm-dir}/amp2/deploy/dist/lib/old-amp-server-conf.jar"/>
<zip file="${pm-dir}/amp2/deploy/dist/lib/amp-server-conf.jar">
<zipfileset src="${pm-dir}/amp2/deploy/dist/lib/old-amp-server-conf.jar">
<exclude name="log4j.properties"/>
<exclude name="ehcache-transactional.xml"/>
</zipfileset>
</zip>
<zip file="${pm-dir}/amp2/deploy/dist/amp-main.ear">
<zipfileset src="${pm-dir}/amp2/deploy/dist/old-amp-main.ear">
<exclude name="lib/amp-server-conf.jar"/>
</zipfileset>
<zipfileset dir="${pm-dir}/amp2/deploy/dist/lib/" includes="amp-server-conf.jar" fullpath="lib/amp-server-conf.jar"/>
</zip>
<!-- EDM -->
<move file="${pm-dir}/amp2/deploy/dist/amp-edm.ear" tofile="${pm-dir}/amp2/deploy/dist/old-amp-edm.ear"/>
<unzip src="${pm-dir}/amp2/deploy/dist/old-amp-edm.ear" dest="${pm-dir}/amp2/deploy/dist/">
<patternset>
<include name="lib/amp-server-conf.jar"/>
</patternset>
</unzip>
<move file="${pm-dir}/amp2/deploy/dist/lib/amp-server-conf.jar" tofile="${pm-dir}/amp2/deploy/dist/lib/old-amp-server-conf.jar"/>
<zip file="${pm-dir}/amp2/deploy/dist/lib/amp-server-conf.jar">
<zipfileset src="${pm-dir}/amp2/deploy/dist/lib/old-amp-server-conf.jar">
<exclude name="log4j.properties"/>
</zipfileset>
</zip>
<zip file="${pm-dir}/amp2/deploy/dist/amp-edm.ear">
<zipfileset src="${pm-dir}/amp2/deploy/dist/old-amp-edm.ear">
<exclude name="lib/amp-server-conf.jar"/>
</zipfileset>
<zipfileset dir="${pm-dir}/amp2/deploy/dist/lib/" includes="amp-server-conf.jar" fullpath="lib/amp-server-conf.jar"/>
</zip>
</target>

<!--=============== Builds LEIS ========================================================================-->
<target name="build-proxy" if="build-LEIS">


<ant antfile="build.xml" target="clean" dir="${leis-dir}/proxy" inheritAll="false" />
<ant antfile="build.xml" target="prod-dist" dir="${leis-dir}/proxy" inheritAll="false">
<property name="build.name" value="${AMP_MAJOR_VERSION}.${BUILD_NUM}"/>
</ant>

<!--copy the proxy jar to the LEIS jars library-->
<copy todir="${leis-dir}/JARS" flatten="true">
<fileset dir="${leis-dir}/proxy/dist/" >
<include name="${proxy-name}"/>
</fileset>
</copy>

<!--create a directory to hold the LEIS ear contents-->
<property name="ear.dir" value="${leis-dir}/bin"/>
<property name="ear-name" value="${ear.dir}/LEIS_AMP.ear"/>
<mkdir dir="${ear.dir}"/>

<!--create the ear from the directories contents-->
<ear destfile="${ear-name}" appxml="LEIS/application.xml">
<metainf dir="${leis-dir}/LEIS/conf/EAR/META-INF" includes="weblogic-application.xml"/>
<fileset dir="${leis-dir}/JARS/" includes="*.jar"/>
<fileset dir="${leis-dir}/JARS/" includes="APP-INF/**" excludes="APP-INF/lib/wlfullclient.jar"/>
</ear>

<!-- Place the proxy-client jar in the amp ear-->
<zip update="true" destfile="${pm-dir}/amp2/deploy/dist/amp-main.ear">
<zipfileset dir="${leis-dir}/proxy/dist/" includes="${proxy-client-name}" fullpath="APP-INF/lib/${proxy-client-name}"/>
</zip>

</target>

<target name="build-cpc">
<copy file="${pm-dir}/amp2/deploy/lib/${AMP_TRANSFER_NAME}" todir="${leis-dir}/cpc-web-app/webapp/lib/cpc"/>
<ant antfile="build.xml" target="build-all-environments" dir="${leis-dir}/cpc-web-app/webapp" inheritAll="false"/>
</target>

<!--========================================= Build AMP and LEIS --!>

<target name="build-all">
<antcall target="build-LEIS-components"/>
<antcall target="build-pm"/>
<antcall target="build-proxy"/>
<antcall target="build-cpc"/>
</target>






FormClosing shutdown event doesnt write to a file

I have a backup power supply for my computer which is attacted inline with it and the wall. When I pull the power cord from the wall, I have 2-5 minutes before the backup supply shuts down the computer. It is during this time that I want to write data to a file with the code below:



private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
{
writeContents("Interrupted");
sendMessage("PWR - The Spring Test Machine has stopped"); return;

}



if (e.CloseReason.Equals(CloseReason.UserClosing))
{
if (MessageBox.Show("You are closing this application.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)
{
writeContents("Interrupted");
return;
}

else
e.Cancel = true;
}

}


The problem is that it didn't work. I dont think the the closing event ever got called. Any ideas would greatly be appreciated. Thank you.





Unable to convert string (containing a number) to int?

I have a very silly problem .. I have a string containing "800.0000" (without the quotes), which I'm trying to convert to the number 800. I'm using this command, but its not working:



int inputNumber = Int32.Parse(inputString);



I get the FormatException, with the message "Input string was not in a correct format."





From where to upload app binary file on App store

I have followed all the steps to upload my first application on "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa"



at last i had uploaded the Large image & Screenshots.



I had not an option to upload the Binary file.



Now application status is "Waiting For Upload".



I am right now confuse about to upload my binary file, from where & how i can upload it?



is appliacation under review? is everything ok? or I will have to do any change?



Please, help me out, i am new to upload application.



All related helps are appreciated & thanks in advance.





How do I undeploy a meteor application?

I've deployed an application with:
meteor deploy a-meteor-app.meteor.com.



Is there a way for me to undeploy from meteor.com?