text stringlengths 8 267k | meta dict |
|---|---|
Q: Problems watching non-trivial expressions in visual studio debugger Basically my problem is that I expect Visual Studio (2010 Professional) to be able to evaluate any Visual C++ expression in the watch window that it handles in the code I'm debugging, but apparently there's something preventing this from happening. For example, when dealing with CStrings, evaluating the method IsEmpty on the CString in the watch window gives me a Member function not found error, as does a basic equality comparison (in the code being debugged obviously no problems).
Am I missing something here, or is what I'm asking for too much? Obvious solution would be to put debugging statements in my code for whatever CString operation I'm looking for, but I would prefer not to have to do this.
Update/Example:
CString blah = _T("blah");
Calling blah.IsEmpty() in my code works fine, but in the watch window of the debugger I get the error above (CXX0052). The contents of the variable blah can be seen the watch window.
A: I could reproduce your problem, and, indeed, the VS watch window shows Member function not found alongside with the error code CXX0052.
In the MSDN documentation I found that this problem arises due to a call of a inlined function, the CString::IsEmpty() member function is probably somehow inlined (this is what the Watch Window evaluator sees), to solve the problem, first open your project Configuration and disable inlining
Second, still in the project Configuration, choose Use MFC in a Static Library (somehow the Watch Window keep seeing the called function as an inlined one if you use it as shared library, maybe this is because in the Shared Library the code is inlined and the Watch Window evaluator don't use the Debug builds of such runtime libraries).
Third, clean and Rebuild your Solution.
After that, the problem should be fixed (remember to refresh the expression if you see the value grayed out in the watch panel) during debugging. Remember to switch back to your original Debug options or better, create a new Debug profile to keep this settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Retrieve the dimensions of an image in the filesystem How can I retrieve the dimensions of an image (typically jpeg, png, jpg and gif), in the local filesystem with Java?
A: You can use java's image class to get image attributes. Here is the sample -
BufferedImage img = ImageIO.read(new File("imageFilePath"));
int height = img.getHeight();
int width = img.getWidth();
A: how about this: getting image metadata
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Java: How to detect if a key has been held down over a certain time without checking every loop EDIT: Notice to others, premature optimisation is the root of all evil! Had I not been busily attempting to optimise every aspect of my code (it was a phase OK!) I'd have made a nice, readable program that could be maintained and understood by others.
Each loop (1/60th of a second) the Player class checks the Game class to see which key is down, If the player is not facing the right way it turns to face the right way, else it moves in that direction.
Sadly this means that if you want to turn and not move you have to tap the key for less than 2/60ths of a second (two loops). The code for checking which key is held down is below
and a link to the full source code and a built example is below that.
public class Game extends RenderableObject
{
public static final byte NONE = 0;
public static final byte UP = 1;
public static final byte RIGHT = 2;
public static final byte DOWN = 3;
public static final byte LEFT = 4;
public byte key = NONE;
public Game()
{
}
@Override
public void keyPressed(KeyEvent ke)
{
if (!paused)
{
if (ke.getKeyCode() == 38) // '^ key'
{
key = UP;
return;
}
else if (ke.getKeyCode() == 40) // 'v key'
{
key = DOWN;
return;
}
if (ke.getKeyCode() == 37) // '< key'
{
key = LEFT;
return;
}
else if (ke.getKeyCode() == 39) // '> key'
{
key = RIGHT;
return;
}
}
}
@Override
public void keyReleased(KeyEvent ke)
{
if (ke.getKeyCode() == 38) // '^ key'
{
if (key == UP)
key = NONE;
return;
}
else if (ke.getKeyCode() == 40) // 'v key'
{
if (key == DOWN)
key = NONE;
return;
}
if (ke.getKeyCode() == 37) // '< key'
{
if (key == LEFT)
key = NONE;
return;
}
else if (ke.getKeyCode() == 39) // '> key'
{
if (key == RIGHT)
key = NONE;
return;
}
}
Link to full source code and built example: (well a link to the page with a link to the download anyway!
WARNING: I am a NOOB, if my naming conventions are off... please don't hurt me!
http://troygametwodee.blogspot.com/2011/09/latest-build-21092011.html
So I have toyed with a few ideas already, but none seem particularly gracefull, and all become very messy very quickly,
I'd ideally like to be able to check some sort of boolean in the game class so the player only moves in that direction when the bool is true, but I failed at that too :(
So if anyone has any suggestions I would be very happy :)
Thanks a bunch in advance
A: Ok, so how I solved the issue while keeping fluid motion possible:
First I added a boolean variable called "held". This on it's own was useless so I also added
a numerical variable, called "timeHeld". Each time a key was pressed I reset "timeHeld" to zero and made "held" == false, and put the following code into my loop.
if (timeHeld < 20)
timeHeld++;
else
held = true;
So in my player class, when deciding which way to move it calls "Game.key" to asses which key is down, then if the "held" boolean is true (which it is after one third of a second) the player walks in that direction, Otherwise the player stayed where it is on screen and just changed the direction it was looking.
This worked to an extent, but each time I change direction the "held" variable was set to zero again. This means each time I turned I was delayed by a third of a second, very annoying!
So I did this:
if (ke.getKeyCode() == 38) // '^ key'
{
if (key == NONE)
{
held = false;
timeHeld = 0;
}
key = UP;
return;
}
this means that as long as an arrow key is down "held" remains true, so once the player gets moving there is no delay when turning a corner.
This worked absolutely perfectly as it was, so that is the answer, however I also added another variable. Because I only use my middle finger for both the UP and DOWN key while I play using the arrow or 'wasd' keys, I end up letting go of all of the keys when I switch from moving north to south. In this case with the code as described above I end up stopping for a third of a second SO to fix this I added a variable called "delay"
When a key is let go of, delay is set to 10 (loops), each loop I call:
if (delay > 0)
delay--;
then when a key is pressed I call:
if (ke.getKeyCode() == 38) // '^ key'
{
if (key == NONE && delay == 0)
{
held = false;
timeHeld = 0;
}
key = UP;
return;
}
This means that "held" is only ever set to false when a direction key is pressed and there were no other direction keys down at the time it was pressed AND delay is 0. this gives me a 10 loop delay between letting go of all the arrow keys and pressing another one before "held" is set to false.
Confused? I am! but it works, anyone else who has this problem can either follow the link to my blog, which should have the latest working source, or just ask me to explain the bits you don't get :D
A: A clearer description of what you are trying to achieve would help.
However, if I understand correctly, you could keep a short history of which key is down, e.g. keep the key value for the last five loops. Then you could execute certain actions if at least a certain number of the previous values match a particular key.
A: try holding a value object with boolean value for all of your actions/keypresses in it. The boolean will be true for keydown and false for keyup. When the key actions are handled you can then update the value object to true/false for the relevant key only.
Then when your game update loop runs you can check which key(s) are currently down.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how are integers stored in memory? I'm confused when I was reading an article about Big/Little Endian.
Code goes below:
#include <iostream>
using namespace std;
int i = 12345678;
int main()
{
char *p = (char*)&i; //line-1
if(*p == 78) //line-2
cout << "little endian" << endl;
if(*p == 12)
cout << "big endian" << endl;
}
Question:
*
*In line-1, can I do the conversion using static_cast<char*>(&i)?
*In line-2, according to the code, if it's little-endian, then 78 is stored in the lowest byte, else 12 is stored in the lowest byte. But what I think is that, i = 12345678; will be stored in memory in binary.
If it's little-endian, then the last byte of i's binary will be stored in the lowest byte, but what I don't understand is how can it guarantee that the last byte of i is 78?
Just like, if i = 123;, then i's binary is 01111011, can it guarantee that in little-endian, 23 is stored in the lowest byte?
A: *
*I'd prefer a reinterpret_cast.
*Little-endian and big-endian refer to the way bytes, i.e. 8-bit quantities, are stored in memory, not two-decimal quantities. If i had the value 0x12345678, then you could check for 0x78 and 0x12 to determine endianness, since two hex digits correspond to a single byte (on all the hardware that I've programmed for).
A: There are two different involved concept here:
*
*Numbers are stored in binary format. 8bits represent a byte, integers can use 1,2,4 or even 8 or 1024 bytes depending on the platform they run on.
*Endiannes is the order bytes have in memory (less significant first - LE, or most significant first - BE)
Now, 12345678 is a decimal number whose binary (base2) representation is 101111000110000101001110. Not that easy to be checked, mainly because base2 representation doesn't group exactly into one decimal digit. (there is no integer x so that 2x gives 10).
Hexadecimal number are easyer to fit: 24=16 and 28=162=256.
So the hexadecimal number 0x12345678 forms the bytes 0x12-0x34-0x56-0x78.
Now it's easy to check if the first is 0x12 or 0x78.
(note: the hexadecimal representation of 12345678 is 0x00BC614E, where 0xBC is 188, 0x61 is 97 and 0x4E is 78)
A: *
*static_cast is one new-style alternative to old-fashioned C-style casts, but it's not appropriate here; reinterpret_cast is for when you're completely changing the data type.
*This code simply won't work -- bytes don't hold an even number of decimal digits! The digits of a decimal number don't match up one-to-one with the bytes stored in memory. Decimal 500, for example, could be stored in two bytes as 0x01F4. The "01" stands for 256, and the "F4" is another 244, for a total of 500. You can't say that the "5" from "500" is in either of those two bytes -- there's no direct correspondence.
A: It should be
unsigned char* p = (unsigned char*)&i;
You cannot use static_cast. Only reinterpret_cast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: FolderNameEditor.FolderBrowser with FolderBrowserStyles.ShowTextBox - Automatically create new folder from TextBox.Text I'm showing a FolderBrowser to the user in my application and then promotes him with a ShowDialog() which has m_dialog.Style = FolderBrowserStyles.ShowTextBox;
Thus, allowing the user to manually enter path for the folder he wants to choose.
The problem is that when the user types a path for a folder which doesn't exists and clicks OK, the dialog returns with some default DirectoryPath value.
What I want is the selected folder to be created (if it doesn't exists, and by promoting the user first) and then have the (now valid) path inside the DirectoryPath property.
Any way to do it?
A: The FolderNameEditor.FolderBrowser class makes use of the SHBrowseForFolder shell function. The default functionality based on the user entering an invalid path is to return the default selected item (which in this case is the Desktop folder).
The SHBrowseForFolder shell function expects an argument of type BROWSEINFO (structure).
This structure allows for the definition of a callback function (a pointer to an application-defined function that the dialog box calls when an event occurs) and it is in this callback that the possibility lies of achieving what you require.
This callback function is set to null when FolderBrowser invokes this shell function, so there is no possible way of achieving what you require using the FolderNameEditor class.
However there is a library on codeproject you can make use of which uses the SHBrowseForFolder and wraps the event callback, providing access to the invalid folder entry through an event (OnValidateFailed). See: C# does Shell, Part 1
Within this event (after some validation (as the user can input anything)) you could use the path entered to create the directory.
Here is an example:
using ShellLib;
...
public class OpenFolderDialog
{
ShellBrowseForFolderDialog folderDialog;
string selectedPath;
public OpenFolderDialog()
{
folderDialog = new ShellBrowseForFolderDialog();
folderDialog.OnValidateFailed += new ShellBrowseForFolderDialog.ValidateFailedHandler(dialog_OnValidateFailed);
}
int dialog_OnValidateFailed(ShellBrowseForFolderDialog sender, ShellBrowseForFolderDialog.ValidateFailedEventArgs args)
{
selectedPath = args.invalidSel;
//Use selectedPath here to create the directory.
return 0;
}
public string GetFolder()
{
selectedPath = string.Empty;
folderDialog.ShowDialog();
return selectedPath == string.Empty ? folderDialog.FullName : selectedPath;
}
}
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting request attributes in freemarker How do I check a value from the request attribute in freemarker?
I tried <#if *${RequestParameters['servicesettings']} ??> but getting errors ->
Encountered "*" at line
Can anyone help?
A: It depends on the Web application framework, because FreeMarker itself doesn't expose the request parameters. (Well, except if the framework uses freemareker.ext.servlet.FreemarkerServlet which is kind of an extension to FreeMarker.) Also, usually you shouldn't access request parameters directly from an MVC template, or anything that is HTTP/Servlet specific.
As of the error message, what you have written has a few syntax errors... probably you meant <#if RequestParameters.servicesettings??> (it's not JSP - don't use ${...}-s inside FreeMarker tags). This will require that you have RequestParameters in the data-model, that I can't know for sure...
A: We should write like this:
${Request.requestattribute}
A: You can use
${requestParameters.servicesettings}.
A: According to the JavaDoc of the FreemarkerServlet:
It makes all request, request parameters, session, and servlet context attributes available to templates through Request, RequestParameters, Session, and Application variables.
The scope variables are also available via automatic scope discovery. That is, writing Application.attrName, Session.attrName, Request.attrName is not mandatory; it's enough to write attrName, and if no such variable was created in the template, it will search the variable in Request, and then in Session, and finally in Application.
You can simply write:
${attrName}
to get the value of a request attribute (that you might have set in a servlet request filter using request.setAttribute('attrName', 'value')
Worked for me with Freemarker 2.3.27-incubating
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why in Android NDK not Install Software? I Start the Android NDK and create error in Console "ObjectAid Sequence Diagram is not available because no valid license was found"..
Please give me Solution.
A: That has most likely nothing to do with the Android NDK, but another software called ObjectAid Sequence Diagram which requires an evaluation or paid license:
Note that you need a license to use the Sequence Diagram Editor. To obtain a license, first create an account by clicking on Account. Once your account has been activated, you can request a single evaluation license or purchase single-user licenses for 19 USD each.
from http://www.objectaid.com/download
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL LIKE vs LOCATE Does anyone know which one is faster:
SELECT * FROM table WHERE column LIKE '%text%';
or
SELECT * FROM table WHERE LOCATE('text',column)>0;
A: +1 to @Mchl for answering the question most directly.
But we should keep in mind that neither of the solutions can use an index, so they're bound to do table-scans.
Trying to decide between a cloth or plastic adhesive bandage is kind of silly, when you're trying to patch the hull of the Titanic.
For this type of query, one needs a full-text search index. Depending on the size of the table, this will be hundreds or thousands of times faster.
A: I did some tests as Mchi did.And I think it's hard to say which one is faster. It looks like depending on the first occurrence of the substring.
mysql> select benchmark(100000000, 'afoobar' like '%foo%');
+----------------------------------------------+
| benchmark(100000000, 'afoobar' like '%foo%') |
+----------------------------------------------+
| 0 |
+----------------------------------------------+
1 row in set (9.80 sec)
mysql> select benchmark(100000000, locate('foo', 'afoobar'));
+------------------------------------------------+
| benchmark(100000000, locate('foo', 'afoobar')) |
+------------------------------------------------+
| 0 |
+------------------------------------------------+
1 row in set (8.08 sec)
mysql> select benchmark(100000000, 'abfoobar' like '%foo%');
+-----------------------------------------------+
| benchmark(100000000, 'abfoobar' like '%foo%') |
+-----------------------------------------------+
| 0 |
+-----------------------------------------------+
1 row in set (10.55 sec)
mysql> select benchmark(100000000, locate('foo', 'abfoobar'));
+-------------------------------------------------+
| benchmark(100000000, locate('foo', 'abfoobar')) |
+-------------------------------------------------+
| 0 |
+-------------------------------------------------+
1 row in set (10.63 sec)
mysql> select benchmark(100000000, 'abcfoobar' like '%foo%');
+------------------------------------------------+
| benchmark(100000000, 'abcfoobar' like '%foo%') |
+------------------------------------------------+
| 0 |
+------------------------------------------------+
1 row in set (11.54 sec)
mysql> select benchmark(100000000, locate('foo', 'abcfoobar'));
+--------------------------------------------------+
| benchmark(100000000, locate('foo', 'abcfoobar')) |
+--------------------------------------------------+
| 0 |
+--------------------------------------------------+
1 row in set (12.48 sec)
mysql> select @@version;
+------------+
| @@version |
+------------+
| 5.5.27-log |
+------------+
1 row in set (0.01 sec)
A: Added April 20th, 2015: Please read also Hallie's answer below
First one but marginally. Mostly because it doesn't have to do an extra > 0 comparison.
mysql> SELECT BENCHMARK(100000000,LOCATE('foo','foobar'));
+---------------------------------------------+
| BENCHMARK(100000000,LOCATE('foo','foobar')) |
+---------------------------------------------+
| 0 |
+---------------------------------------------+
1 row in set (3.24 sec)
mysql> SELECT BENCHMARK(100000000,LOCATE('foo','foobar') > 0);
+-------------------------------------------------+
| BENCHMARK(100000000,LOCATE('foo','foobar') > 0) |
+-------------------------------------------------+
| 0 |
+-------------------------------------------------+
1 row in set (4.63 sec)
mysql> SELECT BENCHMARK(100000000,'foobar' LIKE '%foo%');
+--------------------------------------------+
| BENCHMARK(100000000,'foobar' LIKE '%foo%') |
+--------------------------------------------+
| 0 |
+--------------------------------------------+
1 row in set (4.28 sec)
mysql> SELECT @@version;
+----------------------+
| @@version |
+----------------------+
| 5.1.36-community-log |
+----------------------+
1 row in set (0.01 sec)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Are these ways of writing function prototype equivalent? I have always used to write function prototype declaration in this way:
var O = function () {};
O.prototype.fn = function () {}
But Some developer write in this way:
var O = function () {};
O.prototype.fn = function fn () {}
Are these way equivalent? If not, what is the advantage for using the second way?
var O = function () {};
O.prototype.fn = function fn () {}
A: var a = function _a() { }
vs
var a = function () { }
The former is called a named function expression,
The latter is just a function assignment.
A NFE has two advantages
*
*It has a name which is shown in a stack trace. This improves debugging significantly
*It has a name you can use within the function for recursion
A NFE has disadvantages. Kangax talks about them in depth.
Personally I use NFE everywhere and ignore the memory leaks IE makes. However since IE leaks these function names into global scope, an effort should be made to make them unique.
Because IE has a habit of leaking these names into global scope, I try to make them unique.
This is why I prepend function declaration names with _
var doSomeLogic = function _doSomeLogic() {
};
As a side-note there's an alternative pattern to
var O = function () {};
O.prototype.fn = function fn () {}
var obj = new O();
Which is
// prototype object
var O = {
fn: function _fn() { }
};
// factory
var o = function _o() { return Object.create(O); }
var obj = o();
A: If you use a name when you create an anonymous function, you can use that name inside the function:
var x = function y() {
y(); // here it exists
}
y(); // here it doesn't exist
The use for that is of course limited. You can use it for recursion, or if you hook up the method as a callback function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: history.back only if referrer same website I'd like to display a back button with the help of history.back, but it should only be displayed if the history page is within the same website / domain. So it should not be displayed if referrer is e.g. google.com. Couldn't find a working solution yet.
Is this possible?
Thx
A: Referer in javascript is tricky because different browsers support it differently. My preferred method is to catch
the referrer using code behind of whatever language I'm using to produce the page and then pass it into the page as a javascript variable. A C# example:
<script language="javascript" type="text/javascript">
var referer = '<%= Request.UrlReferrer %>';
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to rewrite the username in addition to the email adress in postfix? Following setup: Two servers, one with the (rails) web application and the other which actually sends the emails to the internet through postfix. Which means that any emails created by the web application get sent to the email server who processes them again.
Now, this means that emails got sent out with an email adress like "user@webserver.localdomain", which promptly led to the rejection of the emails by the target mail servers, due to the obviously missing mx record.
That one I fixed, though, with smtp_generic_maps, rewriting the sender adress to a valid one.
However, the sender name displayed in the email consists of two parts - and the first part seems to be automatically set by postfix by the username of the webserver creating the email. In this case "nginx".
So, how do I rewrite the displayed user name in addition to the email adress? Can anyone point me in the right direction, please?
To my defense: I did not setup this system myself, so I'm a bit of a beginner at all things sendmail.
A: Easy, connect via TCP/IP to 127.0.0.1 port 25, and submit the mail using SMTP. that way you can set the from address to whatever you want. Currently you are submitting mail via the sendmail command, which is picking up the from address from user.
ps. sendmail != postfix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Posting JSON strings with Kohana 3.2 in PHP When running normal post operations I use the following code:
$request = Request::factory($url)->method(Request::POST)->post($params);
$response = $request->execute();
I'm not sure what it is I need to change though to enable me to POST a json string instead of an array variable.
My json string is basically created using the json_encode() function on an array of parameters, like so:
$params = array(
'var1' => $var1,
'var2' => $var2,
// etc
);
$json = json_encode($params);
Any help would be greatly appreciated.
A: I have found these solutions.
Using PUT:
$request = Request::factory('http://example.com/put_api')->method(Request::PUT)->body(json_encode('the body'))->headers('Content-Type', 'application/json');
Using POST:
$request = Request::factory('http://example.com/post_api')->method(Request::POST)->body(json_encode('the body'))->headers('Content-Type', 'application/json');
From here: http://kohanaframework.org/3.2/guide/kohana/requests#external-requests
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I stop MediaStore.ACTION_IMAGE_CAPTURE duplicating pictures I am using the following code to take a picture:
private static final int TAKE_PHOTO_CODE = 1;
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tFile));
startActivityForResult(intent, TAKE_PHOTO_CODE);
This code works fine however I am getting a copy of every picture I take automatically appearing in the "Camera Shots" gallery as well as where I want the picture to go.
How do I stop it automatically copying my picture?
The file name is not even the same as the one I specified so it is not like I can delete it easily.
Thanks for any help!
A: I have found a answer.
Following function delete the last photo saved to media storage.
public void deleteLastCapturedImage() {
String[] projection = {
MediaStore.Images.ImageColumns.SIZE,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATA,
BaseColumns._ID
};
Cursor c = null;
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
try {
if (u != null) {
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToLast())) {
ContentResolver cr = getContentResolver();
int i = cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, BaseColumns._ID + "=" + c.getString(c.getColumnIndex(BaseColumns._ID)), null);
Log.v(LOG_TAG, "Number of column deleted : " + i);
}
} finally {
if (c != null) {
c.close();
}
}
}
Please call above function within onActivityResult.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails3, JQuery and RJS (UJS) I am trying to get ajax callbacks working on a href using remote. I have the rails.js and
JQuery1.6 installed.
Here is the attempt to catch the callback:
$('#choo').bind('ajax:success', function(){
alert("Success!");
});
Here is my div and AJAX link
<%= link_to "Choose", {:action => "choose", :id => 538}, :remote => true, :id => "choo" %>
When I click the link the ajax fires hits the server and returns the response but the callback is not working...
I have followed everything in this guide but with little by the way of success. In other words "!ajax:success" :-).
Any ideas what I am doing wrong?
EDIT++++++++++++++++++++==
I updated to 3.1 and it worked.
Cheers,
s
A: Try to "live"
$('#choo').live('ajax:success', function(){
alert("Success!");
});
or this:
$('a[data-remote],input[data-remote]').live('ajax:success', function() {
alert('success');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: socket.io - works first time, not second time onwards When I start my node.js server and client gets connected, I am able to send a request from client (socket.emit) and get a response (socket.on('rentsAround'....)). But when I connect 2nd time onwards, the client is able to send, but server can not send or emit. So I have to restart the server again. I understand that it is working as expected, but somehow my understanding is wrong somewhere... Would someone please point out.
client side:
========
var socket = new io.Socket();
socket = io.connect();
socket.on('rentsAround', function(data){
registration.handleRentsAround(data);
});
socket.on('locationDetailsRes', function(data){
registration.handleRentsAround(data);
});
socket.on('connect', function(data){
alert('inside connect on client side');
});
socket.on('disconnect', function(){
// do something, if you want to.
});
.............
socket.emit("searchRent", {"lat":lat, "lng":lng});
server side:
========
socket.sockets.on('connection', function(client){
client.on('searchRent', function(msg){
console.log('inside on connection');
// do something and reply back
client.emit('rentsAround',{"totalRents":docs.length, "rents":docs});
});
client.on('disconnect', function(){
sys.puts("client disconnect");
mongoose.disconnect();
});
A: Socket.io 0.7 onwards will try and reuse connections to the same host. In my experience I've found this behaviour can be a little flakey.
I can't tell from the small code sample you provided, but I suspect the problem is that the second call to connect() is trying to reuse the first (closed) connection.
The workaround is to pass the 'force new connection' option when you call connect(). Eg:
io.connect("http://localhost", {'force new connection': true});
A: Your second line discards the object created in the first line. Simply doing this should work:
var socket = io.connect();
The problem with first send and second fail could be due to browser/protocol. I have seen such behaviour with Internet Explorer and XHR transport, and also with Opera using JSONP.
If you are using IE, try switching to JSONP and it should work properly. This can be done on the server side, by supplying the transport list to configuration. Just make sure JSONP comes before XHR. Something like this:
sio.set('transports', [
'websocket'
, 'flashsocket'
, 'jsonp-polling'
, 'xhr-polling'
, 'htmlfile'
]);
A: As of socket.io 1.0, two settings control this behaviour:
*
*"force new connection":true, on the client connect() call.
*"cookie":false, on the server Server() constructor.
Apparently, both produce the exact same behaviour.
The second method is, as of today, undocumented. However, looking at the source code you can see that all options passed to socket.io Server() are passed to the internal Engine.io library Server() constructor, which lets you change any of the options there. These options are documented here:
https://github.com/LearnBoost/engine.io
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: jQuery Mobile: Same page with different data-urls I have a web application made with jQuery Mobile beta 2. The start page of the application has the URL http://server/mob/start.php and its page div has ID 'frontpage' and data-url is also 'frontpage'.
When I click a link from the start page and from the just opened page click Home button which points back to URL /mob/start.php, I end up with two frontpage divs in my DOM. The newly added frontpage has the same ID but its data-url is '/mob/start.php/'.
I could of course remove the page divs where I'm navigating away from but after the above described navigation the browser is pointed at URL /mob/start.php#/mob/start.php. Thus when I reload the page, I end up with same situation again.
What am I doing wrong because this problem doesn't seem to appear in jQueryMobile.com site?
UPDATE: Each page is an independent page and contains only one page div so links are not made by ID but by local relative URL.
A: I updated jQuery Mobile to beta 3 and can no longer reproduce the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need to escape non-ASCII characters in JavaScript Is there any function to do the following?
var specialStr = 'ipsum áá éé lore';
var encodedStr = someFunction(specialStr);
// then encodedStr should be like 'ipsum \u00E1\u00E1 \u00E9\u00E9 lore'
I need to encode the characters that are out of ASCII range, and need to do it with that encoding. I don't know its name. Is it Unicode maybe?
A: If you need hex encoding rather than unicode then you can simplify @Domenic's answer to:
"aäßåfu".replace(/./g, function(c){return c.charCodeAt(0)<128?c:"\\x"+c.charCodeAt(0).toString(16)})
returns: "a\xe4\xdf\xe5fu"
A: This should do the trick:
function padWithLeadingZeros(string) {
return new Array(5 - string.length).join("0") + string;
}
function unicodeCharEscape(charCode) {
return "\\u" + padWithLeadingZeros(charCode.toString(16));
}
function unicodeEscape(string) {
return string.split("")
.map(function (char) {
var charCode = char.charCodeAt(0);
return charCode > 127 ? unicodeCharEscape(charCode) : char;
})
.join("");
}
For example:
var specialStr = 'ipsum áá éé lore';
var encodedStr = unicodeEscape(specialStr);
assert.equal("ipsum \\u00e1\\u00e1 \\u00e9\\u00e9 lore", encodedStr);
A: Just for information you can do as Domenic said or use the escape function but that will generate unicode with a different format (more browser friendly):
>>> escape("áéíóú");
"%E1%E9%ED%F3%FA"
A: This works for me. Specifically when using the Dropbox REST API:
encodeNonAsciiCharacters(value: string) {
let out = ""
for (let i = 0; i < value.length; i++) {
const ch = value.charAt(i);
let chn = ch.charCodeAt(0);
if (chn <= 127) out += ch;
else {
let hex = chn.toString(16);
if (hex.length < 4)
hex = "000".substring(hex.length - 1) + hex;
out += "\\u" + hex;
}
}
return out;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Repeated occurrence of C2275 Error I am using Microsoft Visual Studio 2010 on Windowns 7. For some un-understandable reason i keep getting the C2275 error when i try to compile the following code:
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node
{
int x;
struct list_node *next;
}node;
node* uniq(int *a, unsigned alen)
{
if (alen == 0)
return NULL;
node *start = (node*)malloc(sizeof(node)); //this is where i keep getting the error
if (start == NULL)
exit(EXIT_FAILURE);
start->x = a[0];
start->next = NULL;
for (int i = 1 ; i < alen ; ++i)
{
node *n = start;
for (;; n = n->next)
{
if (a[i] == n->x) break;
if (n->next == NULL)
{
n->next = (node*)malloc(sizeof(node));
n = n->next;
if (n == NULL)
exit(EXIT_FAILURE);
n->x = a[i];
n->next = NULL;
break;
}
}
}
return start;
}
int main(void)
{
int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
/*code for printing unique entries from the above array*/
for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
printf("%d ", n->x); puts("");
return 0;
}
I keep getting this error "C2275: 'node' : illegal use of this type as an expression" when i compile. However, i asked one of my friends to paste the same code in his IDE it compiles on his system!!
I would like to understand why the behaviour of the compiler is different on different systems and what influences this difference in behavior.
A: You can't declare a variable node * start after other code statements. All declarations have to be at the start of the block.
So your code should read:
node * start;
if (alen == 0)
return;
start = malloc(sizeof(*start));
A: I have no idea why you have **node there.
You simply need node *start;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the best way to handle collision detection between bodies efficiently? I am new to Cocos2d, Box2d and game development all together, but I have read a good bit of tutorials to at least have a good start on a game set up and working...
Im now at the point where I need to start adding more bodies to a layer and need to check and see if and when my main avatar will collide with any of them..
Common sense seems to tell me that the more bodies I add and the more cases I add checking to see if fixture1 is colliding with fixture2 for instance will bog down the processor at some point..
Are there any best practices and/or efficient algorithms to make these checks more efficient over time as the number of bodies grow?
Any links or direction would be appreciated! thank you!
A: You can use QuadTree to divide the scene and get a list of bodies that needs to be checked.
(There are a lot of articles shows how QuadTree works, just google it:D )
And if that's a little complex for you. Then you can try to divide your scene into many grid, and make a loop to put bodies in their grid based on their 2d position. Then just check bodies in each grid. It's a lot faster than normal loop.
http://i.stack.imgur.com/W5cBT.png
A: As of iOS 7 you can use Sprite Kit to handle collisions:
https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Physics/Physics.html#//apple_ref/doc/uid/TP40013043-CH6-SW14
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The namespace of a Coded UI Test Map (UIMap.uitest)? Does anybody know how one can change the namespace of a "Coded UI Test Map" also known as UIMap?
Or how the designer does the naming?
When adding a UIMap to your project, you get to cs-files:
e.g.
*
*UIMap.cs
*UIMap.Designer.cs
The designer file is auto generated (thus not for editing yourself) and the other file is for own customizations.
In my case I want to change the namespace of both files because I added some folders to organise stuff.
What I did was manually changing the namespace of both files. But since the designer generates file 2) the namespace was also changed again, screwing up my references.
Now I hoped to find a property to enter my own namespace naming. The property I found was for the file "UIMap.uitest", named "Custom Tool Namespace". This property didn't do the trick.
I also had a look in the xml of "UIMap.uitest" to find a namespace reference but again no success.
So I guess the naming is hardcoded by the designer...
The designer always generates this namespace:
namespace TestProject.UIMaps.UIMapClasses
*
*"TestProject" is the default sln namespace
*"UIMaps" is my added folder
*"UIMapClass": don't no the origin but seem to be auto-generated from the name of the "Coded UI Test Map" (here UIMap) + "Classes".
Can anybody confirm the namespace naming convention by the designer? Or knows a way to manually fix it?
A: If you are talking about the root namespace, it's in the project properties dialog
*
*right click the project
*select the properties menu item
*on the application tab, look for the Default namespace: text box and put what you want in there. It can consist of several levels
e.g.
BigNamespace.CompanyNamespace.ITProject.Solution.Project..... etc.
when you perform any action that will require a rewrite of the file, those namespace lines get rewritten. Or you can do it by hand.
I looked it up because it was giving me heartburn too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenGL/GLEW: How to choose the correct/existing enum without provoking a compile time error I am currently using glew to detect some GPU features of the bound openGL context.
Imagine a texture class where I want to use the openGL 3.0 enums if available and fallback to extensions if opengl 3.0 is not in place but the extension is i.e:
uint32 chooseGlInternalFormat(uint32 _pixelType, uint32 _pixelFormat)
{
uint32 ret;
//...
if(GLEW_EXT_texture_integer || GLEW_VERSION_3_0)
{
bool bUseExt = !GLEW_VERSION_3_0; //if only the extension is available but not gl 3.0, fallback
ret = bUseIntEXT ? GL_LUMINANCE8UI_EXT : GL_R8UI;
}
//...
}
obviously this causes a compile time error since GL_R8UI won't exist if opengl 3.0 is not supported.- What is the common way to solve this?
A: Some larger applications take the newest enum specification and add their own enums based on it. If you only need it this one time you can just define your own enum for this single case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# app + upload video to Youtube I need to create a c# application where I can upload a video ( I give the path for the video which is .mp4) to Youtube.
How can I do that? I need to add a reference in my project of Google Data .NET Client library and I also have to obtain a Developer key.
In order to add reference such as:
using Google.GData.Client;
// I need to have a method authentificate :
YouTubeRequestSettings settings =
new YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request =
new YouTubeRequest(settings);
Also if I have the video .mp4 do I need to have a model for uploading it on youtube? Model such Tile, Description....?
Moreover in order to add reference suh as Google Data Core API LIBRARY I need to build Google Data api sdk . In order to do that, I need to add reference to Nunit. but for moment, the download site doesn't work. I do need to build the sdk in order to add reference to my project , right?
Need help please
A: once you have downloaded the library you mentioned, Google Data .NET, here is a snippet to upload a video from a local file, you should include such snippet in your application.
Video newVideo = new Video();
newVideo.Title ="My Test Movie";
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "cars, funny";
newVideo.Description = "My description";
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource("c:\\file.mov",
"video/quicktime");
Video createdVideo = request.Upload(newVideo);
For extensive documentation and samples refer to the official, public, .NET Developer's Guide: YouTube APIs and Tools - Developer's Guide: .NET
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery validate checks the form prematurely i have a jquery validate setup on the form.
whil the form is being filled out, i ajax 2 of the field values to see if the form is acceptable or not, and as a result disable/enable the submit button of the form.
it seems like as a result - the form is premateurly validated - which shoudl only happen when the submit button is hit.
can anyone suggest a fix?
thanks!
Here is some code:
//validate form:
$("#ftblSubGroupsadd").validate({
showErrors: function(){
this.defaultShowErrors();
alert('Note, a few mandatory fields remain un-answered.');
$("label.error").closest("div[class=inside]").css("display","block");
$("label.error").closest("div.boxed").removeClass().addClass('box');
}
});
//check input of 2 fields, while form is still being filled out:
$("#x_ShortFileName, #x_URL").change(function(){
var fileName = $("#x_ShortFileName").val();
var location = $("#x_URL").val();
var sendStr = "fileName="+fileName+"&location="+location;
//alert(sendStr);
$("#locationResponse").load("/system/checkFileExists.asp",sendStr, function(response, status, xhr){
var responseArr = response.split("|");
if (responseArr[0] == "error") {
//alert("probem");
$("#locationResponse").removeClass().addClass('red');
$("#locationResponse").html(responseArr[1]);
$("#btnAction").attr("disabled","disabled");
$("#finalURL").html(''); //(responseArr[2]);
} else {
//alert("all good");
$("#locationResponse").removeClass().addClass('green');
$("#locationResponse").html(responseArr[0]);
$("#btnAction").removeAttr("disabled");
$("#finalURL").html(responseArr[1]);
}
});
});
HTML form code:
<form name="ftblSubGroupsadd" id="ftblSubGroupsadd" action="tblSubGroupsadd.asp" method="post" enctype="multipart/form-data">
<table class="ewTable">
<tr>
<td width="30%" class="ewTableHeader"><strong>Full Sub-Group Name</strong><span class='ewmsg'> *</span></td>
<td class="ewTableAltRow"><span id="cb_x_FullName">
<input type="text" name="x_FullName" id="x_FullName" size="30" maxlength="500" value="" class="required" title=" "></span></td>
</tr>
<tr>
<td class="ewTableHeader"><strong>Short file name</strong> or<strong> access code</strong><span class='ewmsg'> *</span><br />
<span class="grey">This will be used to create the file name </span></td>
<td class="ewTableAltRow"><span id="cb_x_ShortFileName">
<input type="text" name="x_ShortFileName" id="x_ShortFileName" size="30" maxlength="30" value="" class="required" title=" " />
</span>
<div id="locationResponse"></div></td>
</tr>
<tr>
<td class="ewTableHeader">Location of file<span class='ewmsg'> *</span><br />
<span class="grey">Such as: /<strong>groups</strong>/xxxx.asp</span></td>
<td class="ewTableAltRow"><span id="cb_x_URL">
<input type="text" name="x_URL" id="x_URL" size="30" maxlength="255" value="" class="required" title=" " />
<div id="finalURL" class="green"></div>
</span></td>
</tr>
<tr>
<td class="ewTableHeader">Display Program Dates? <span class="ewmsg"> *</span></td>
<td class="ewTableAltRow"><span id="cb_x_optDisplayProgramDates">
<input type="radio" name="x_optDisplayProgramDates" id="x_optDisplayProgramDates" value="0" class="required" title="*">
No <input type="radio" name="x_optDisplayProgramDates" id="x_optDisplayProgramDates" value="1" class="required" title="*">
Yes
</span></td>
</tr> </table>
<p align="center">
<input type="submit" name="btnAction" id="btnAction" value="ADD">
</form>
Possible ajax return data:
error|Warning, the file groups/hop.asp already exists!
or
The file name is available.|The location of your file will be: www.site.com/y/tyu.asp
A: By default, the plugin activates validation on user input. You should deactivate those options :
$("#ftblSubGroupsadd").validate({
onfocusout: false,
onkeyup: false,
onclick: false,
showErrors: function(){
this.defaultShowErrors();
alert('Note, a few mandatory fields remain un-answered.');
$("label.error").closest("div[class=inside]").css("display","block");
$("label.error").closest("div.boxed").removeClass().addClass('box');
}
});
Hope this helps, d.
Edit for comments:
I'm not 100%, but it seems the handler (either your own defined via the showErrors option, or the default one) is called again when all errors have been corrected. The full handler signature has two parameters:
showErrors: function(errorMap, errorList) { ... }
First argument is a map of the errors, second is an array of errors.
So your best bet would be to check the amount of errors:
showErrors: function(errorMap, errorList) {
var len = errorList.length; // or var len = this.numberOfInvalids();
if(len > 0) {
this.defaultShowErrors();
alert('Note, a few mandatory fields remain un-answered.');
$("label.error").closest("div[class=inside]").css("display","block");
$("label.error").closest("div.boxed").removeClass().addClass('box');
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Enable auditing only for a specific sharepoint library programatically - SharePoint 2010 How can I enable auditing for a specific SharePoint library in SharePoint 2010 through code?
A: There is dedicated article:
Activating Auditing Programmatically for a Single Document Library in Windows SharePoint Services 3.0
Its for WSS v3 but should work for SP 2010 as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Value of type 'System.Collections.ArrayList' cannot be converted to 'System.Collections.Generic.List(Of iTextSharp.text.IElement)' I'm having a problem with this code in the highlighted line(*); getting the error in the heading. Any help would be appreciated as I cant get the solution.
Dim htmlarraylist As New List(Of iTextSharp.text.IElement)
htmlarraylist = *HTMLWorker.ParseToList(New StreamReader(tempFile), New StyleSheet())*
document.Open()
For Each element As iTextSharp.text.IElement In htmlarraylist
document.Add(element)
Next
document.Close()
A: Right, so it sounds like ParseToList returns a non-generic ArrayList. The simplest way of fixing that - assuming .NET 3.5 - is probably to use Cast and ToList:
Dim htmlarraylist As List(Of iTextSharp.text.IElement)
htmlarraylist = HTMLWorker.ParseToList(New StreamReader(tempFile), _
New StyleSheet()) _
.Cast(Of iTextSharp.text.IElement) _
.ToList
Note how I've also change the first statement so it no longer creates an instance of List(Of T) only to immediately throw it away.
That's assuming you really want it as a List(Of T). If you don't mind it just been an ArrayList, you can just change the declaration:
Dim list As ArrayList = HTMLWorker.ParseToList(New StreamReader(tempFile), _
New StyleSheet())
You're only iterating over it in the code you've shown, after all. (You could equally change the declaration to use IEnumerable.)
A: Shorten your code to just
document.Open()
For Each element As iTextSharp.text.IElement In HTMLWorker.ParseToList(New StreamReader(tempFile), New StyleSheet())
document.Add(element)
Next
document.Close()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make my dynamic table scrollable when mouse clicked? I have a html table:
<table id="my-table" class="my-table">
<tr class="head">
<th class="name">Name:</th>
<th class="age">Age:</th>
</tr>
<tr class="row">
<td class="name">John</td>
<td class="age">19</td>
</tr class="row">
<tr class="row">
<td class="name">Kate</td>
<td class="age">16</td>
</tr>
...
...
</table>
The table can have several rows which fits 100px height area.
Then, I defined a mouse click event, that's when mouse click on each row's name column, there will be some content be appended after the clicked row:
function addContent(evt){
$('.row').after("<tr>"+SOME_CONTENT+"</tr>");
}
$(".name").click(addContent);
It works and the above click event could make the table much longer, since extra content row are appended after each row if mouse clicked.
My Question is, how to make the table scrollable (scroll bar) when mouse clicked on the "name" column? (That's by default, not scrollable, only when mouse clicked on "name" which triggered extra content appended, then makes it scrollable), so that the table area has the fixed height 100 px always.
I tried in CSS:
.my-table{
overflow:scroll;
height: 100px;
width: 600px;
overflow:auto;
}
but it does not work...
A: table elements don't overflow, but you could use a wrapper surrounding the table and add your css to that:
http://jsfiddle.net/2ezdx/1/
A: With Jquery, you could add
$(".my-table").css('overflow','hidden')
and when you want it to be scrollable (with a javascript event)
$(".my-table").css('overflow','scroll')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help needed:Analyze the dump file in WinDbg I failed to analyze the dump file using Windbg.
Any help would be greatly appreciated.
Here are my WinDbg settings:
Symbol Path: C:\symbols;srv*c:\mss*http://msdl.microsoft.com/download/symbols
(C:\symbols contains my own exe and dll symbols, map,pdb etc etc)
Image Path: C:\symbols
Source Path: W:\
loading crash dump(second chance) shows:
WARNING: Unable to verify checksum for nbsm.dll GetPageUrlData failed,
server returned HTTP status 404 URL requested:
http://watson.microsoft.com/StageOne/nbsm_sm_exe/8_0_0_0/4e5649f3/KERNELBASE_dll/6_1_7600_16385/4a5bdbdf/e06d7363/0000b727.htm?Retriage=1
FAULTING_IP:
+3a22faf00cadf58 00000000 ?? ???
EXCEPTION_RECORD: fffffffffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 000000007507b727
(KERNELBASE!RaiseException+0x0000000000000058) ExceptionCode:
e06d7363 (C++ EH exception) ExceptionFlags: 00000009
NumberParameters: 3
Parameter[0]: 0000000019930520
Parameter[1]: `0000000001aafb10`
Parameter[2]: 000000000040c958
DEFAULT_BUCKET_ID: STACKIMMUNE
PROCESS_NAME: nbsm_sm.exe
ERROR_CODE: (NTSTATUS) 0xe06d7363 -
EXCEPTION_CODE: (NTSTATUS) 0xe06d7363 -
EXCEPTION_PARAMETER1: 0000000019930520
EXCEPTION_PARAMETER2: 0000000001aafb10
EXCEPTION_PARAMETER3: 000000000040c958
MOD_LIST:
NTGLOBALFLAG: 0
APPLICATION_VERIFIER_FLAGS: 0
ADDITIONAL_DEBUG_TEXT: Followup set based on attribute
[Is_ChosenCrashFollowupThread] from Frame:[0] on
thread:[PSEUDO_THREAD]
LAST_CONTROL_TRANSFER: from 000000007324dbf9 to 000000007507b727
FAULTING_THREAD: ffffffffffffffff
PRIMARY_PROBLEM_CLASS: STACKIMMUNE
BUGCHECK_STR: APPLICATION_FAULT_STACKIMMUNE_ZEROED_STACK
STACK_TEXT: 0000000000000000 0000000000000000 nbsm_sm.exe+0x0
STACK_COMMAND: .cxr 01AAF6E8 ; kb ; ** Pseudo Context ** ; kb
SYMBOL_NAME: nbsm_sm.exe
FOLLOWUP_NAME: MachineOwner
MODULE_NAME: nbsm_sm
IMAGE_NAME: nbsm_sm.exe
DEBUG_FLR_IMAGE_TIMESTAMP: 4e5649f3
FAILURE_BUCKET_ID: STACKIMMUNE_e06d7363_nbsm_sm.exe!Unknown
BUCKET_ID:
X64_APPLICATION_FAULT_STACKIMMUNE_ZEROED_STACK_nbsm_sm.exe
FOLLOWUP_IP: nbsm_sm!__ImageBase+0
00400000 4d dec ebp
WATSON_STAGEONE_URL:
http://watson.microsoft.com/StageOne/nbsm_sm_exe/8_0_0_0/4e5649f3/KERNELBASE_dll/6_1_7600_16385/4a5bdbdf/e06d7363/0000b727.htm?Retriage=1
========================
Any ideas?
Thanks in advance!
Sandeep
A: If this crash dump has come from a user and it is either reproducible on their system or happens relatively often then you could ask them to download procdump and run a command such as this:
procdump -e 1 -w nbsm_sm.exe c:\dumpfiles
This will create a dumpfile on the first chance exception which may give you more useful information than you have at the moment. Sometimes the dump from a second chance exception is just produced too late to be useful.
A: You can try to run 'kb' in WinDbg to see the actual stack trace. If you don't see any valuable information, assuming you are developing a native/managed C++ application, you can turn on stack checks (/GS on the cl command line) and re-run the program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Tips and steps for setting up ruby on rails continuous integration server with github integration I'm still new with ruby on rails and am tasked with setting up a continuous integration server/service that uses the code hosted on github and alerts when the tests fails. Amazon EC2 was recommended as a service to use as platform for the service.
I did some research and tried to set up the system using a step by step tutorial but I'm not used to work with Amazon EC2, so I kinda failed doing that.
Can you help me with some advices or first steps to take?
Thanks
A: For CI server you can use CruiseControl developed by ThoughWorks
. Its open source as well . You can get it from github as well.
And pretty much simple to set up only takes 10 min to setup and as its written in ruby its pretty much simple to hack and customize to as per your need .
Reply me if you find anything problem in setup CI
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS image right align - extra line in Firefox 6.02 I have a right aligned image, which works fine in IE9 and Chrome 14. In Firefox 6.02 I do get an extra line. Application is using jQuery UI. How could I avoid this? Is my CSS somehow wrong, or is Firefox 6 known to be different - as far as I remember it was the same as in Chrome with FF5.
<tr class="ui-widget-content sideBarTopAlign">
<td>Data file:</td>
<td colspan="3"><div id="inputDatafileInfo">not read</div>
<button class="ui-button sideBarRightAlign">
<span class="ui-icon ui-icon-link" title="Show data file"></span></button>
</td>
</tr>
with:
/* align some elements explicitly right */
.sideBarRightAlign { float: right; margin-right: 1px; }
/* align some elements explicitly right */
.sideBarTopAlign { vertical-align: top; }
The styles from jQuery UI
button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
.ui-button { cursor: pointer; display: inline-block;
margin-right: 0.1em; overflow: visible; padding: 0;
position: relative; text-align: center; text-decoration: none !important;}
Another finding, it seems to be related to the colspan, if I move it in the last of 4 columns it displays as intended.
A: There was a no-wrap applied to a parent div section. I do not understand why this resulted in the extra line break - and only in FF - but it was the root cause.
A: simple
give the time span a width and display:inline-block
also for the 743 label
the problem is that the span it too long and doesnt give the img to be floated right and top
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to call autoit executable in Junit Selenium test I hope everyone is having a most excellent day and any and all help is appreciated.
I am running an automated Selenium Junit4(remote control) test in internet explorer 7. To do this I utilized the following tutorial: http://qtp-help.blogspot.com/2009/07/selenium-handle-dialogs.html.
The test is being run from my springsource ide on my mac and is being executed through my virtual box ( windows xp sp 3 ) to internet explorer 7. When the test is run, following the directions in the tutorial explicitly, when it gets to the step that is marked with an asterisk:
Thread.sleep(2000);
String browser = selenium.getEval("navigator.userAgent");
if(browser.contains("IE")){
System.out.print("Browser= IE "+browser);
* String[] dialog = new String[]{ "Save_Dialog_IE.exe","Download","Save" };
Runtime.getRuntime().exec(dialog);
I get the error: can not find file or directory
If I call the Save_Dialog_IE.exe inside of a command prompt manually the process runs and interaction with the IE7 browser dialogs are successful. But when attempting to call it while executing the selenium test it does not.
The only step in the tutorial I am not sure I did correctly was placing the executable (Save_Dialog_IE.exe in the project directory). I am not sure exactly where in the project to place the file. I placed it in both the root directory of the project as well as the folder in the project where I created the class for the junit test. A little fuzzy as to exactly where it needs to go.
Anybody got any ideas how to make this work? Or even any idea's as to how to interact with IE7 browser dialogs running a selenium test on a mac to a virtual VMware box running windows xp sp3?
A: The .exe file needs to be in the same directory as from where your program (its own .exe is run). I'm not sure how it works with selenium, but you may just need to do:
1) The .exe file needs to go in the root of your project. Then you have to get its properties, and make sure that the .exe is copied to the project output. Usually this is the /bin/Debug/ (or /Release/) folder, but I'm not sure how that works with selenium.
Or 2) Put the .exe file along with your selenium test application, wherever that is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to center align IMG in div? How to center align IMG in div?
<div id="head">
<div id="panel">
<img/>
<a href="#"><img/></a>
<a href="#"><img/></a>
<a href="#"><img/></a>
</div>
</div>
Img have different Width and Height.
css:
#head{
float:right;
margin:15px 100px 30px 30px;
text-align:center;
height:20px;
width:160px;
}
#panel img{
margin-left:10px;
text-align:center;
}
A: May be this is what you're looking for:
#panel img {
vertical-align: middle;
}
demo
A: Set the width of the "#panel" div so there is room for it to be centered.
A: You need to give #panel a width before the image will center.
A: Give the <div id="panel" align="center">. Images will come in center
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to control tabbing order without disabling all focus for controls in this scenario I got a control that looks like this , it has several text boxes
[1 ][2 ][3 ][4 ]
Now in my app those controls are forming a somekind of a matrix like
[1 ][2 ][3 ][4 ]
[1 ][2 ][3 ][4 ]
[1 ][2 ][3 ][4 ]
Now I wanted to set 1 3 and 4 IsTabStop = false so user can tab through 2nd textboxes only.
After I have done that I found out that 1 3 4 now cannot be focused. And to my surprise in WPF this is not true, so its just another Silverlight unexpected limitation!
http://msdn.microsoft.com/ru-ru/library/system.windows.controls.control.istabstop(v=vs.95).aspx
How to proceed with my initial tabbing through [2 ] plan?
A: I believe you can extend the TextBox control to have it focusable. See this post.
Attached Property
public class Ex
{
public static bool GetIsTabStop(DependencyObject obj)
{
return (bool)obj.GetValue(IsTabStopProperty);
}
public static void SetIsTabStop(DependencyObject obj, bool value)
{
obj.SetValue(IsTabStopProperty, value);
}
// Using a DependencyProperty as the backing store for IsTabStop. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsTabStopProperty =
DependencyProperty.RegisterAttached("IsTabStop", typeof(bool), typeof(Ex), new PropertyMetadata(true, Callback));
private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as Control;
if (control != null)
{
control.IsTabStop = (bool)e.NewValue;
control.MouseLeftButtonDown += (sender, args) =>
{
if (!control.IsTabStop)
{
control.IsTabStop = true;
control.Focus();
control.IsTabStop = false;
}
};
}
}
}
XAML
<TextBox HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Margin="215,49,0,0" RenderTransformOrigin="0,7.25"/>
<TextBox HorizontalAlignment="Left" local:Ex.IsTabStop="False" TextWrapping="Wrap" Text="TextBox" Margin="215,96,0,0" VerticalAlignment="Top"/>
<RadioButton Content="RadioButton" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="210,144,0,0"/>
<RadioButton Content="RadioButton" local:Ex.IsTabStop="False" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="213,183,0,0"/>
You can basically attach this to anything that's inherited from Control.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to access a function defined in app_controller from a ctp I have function in app_controller.php.The function is like:
function globalSum($Var1,$Var2)
{
$Var3 = $Var1 + $Var2;
return $Var3;
}
Now I want to access this function from any CTP file to get the value after sum.when I call this function the arments will be send from the ctp file.
So,anybody can tell me how to call this function with arguments from the ctp file??
Thanks in advance..
A: The way you're trying to do this probably isn't the best, seeing as it's working against the MVC architecture that CakePHP uses.
In MVC, the ctp file is your view and should only act as a template, to the greatest extent possible, with any values that you need in the view should be passed to it from the controller.
You have a number of simple solutions to your problem.
One is simply to do the addition in the view:
index.ctp
<?php
echo $var1 + $var2
?>
For such a simple operation, why bother with a separate function?
If your function is more complicated, you can put it in the AppController and then set the view variable in the controller that the action belongs to. For example:
app_controller.php
<?php
function globalSum($Var1,$Var2) {
$Var3 = $Var1 + $Var2;
return $Var3;
}
?>
posts_controller.php
<?php
function index() {
$this->set('var3', $this->globalSum($var1,$var2));
}
?>
index.ctp
<?php
echo $var3;
?>
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inserting into two tables (same DB) how do I get the unique ID from one table? Firstly please excuse my lack of knowledge for SQL, I have only done basic inserts before.
I am currently improoving a little system that I have, and I want to insert some data that is obtained via _GET (php) into two tables. My problem is as follows.
My first table (table_one) has an auto incrementing value called "id", which I need to obtain, and post over to my second table (table_two).
Because of the way data will be updated at the later date, the ID in table two, is a reference to the ID that is automatically generated upon insert in table one (hence no ID in the code below). (I will be using the ID in table one to do a for loop for each matching ID instance in table_two)
How can I run one query to update one table, then update the 2nd with the unique id obtained from the first table?
My current code is this...
INSERT INTO table_one (valueone,valuetwo,valuethee) VALUES ('$v1','$v2','$v3')
A: you can use mysql_insert_id() built in command of php this will give you the id of the recently inserted data
mysql_query("insert into.... ");
$a = mysql_insert_id();
A: mysql_insert_id() after first query will give you id
I want to insert some data that is obtained via _GET
that's wrong. this data should be obtained via POST
A: Expanding on @Ujjwal's answer, you can do the same just using SQL.
INSERT INTO table1 (x,y) VALUES ('x','y');
INSERT INTO table2 (t1_id, z) VALUES (LAST_INSERT_ID(), 'z');
See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spawning threads in a JSF managed bean for scheduled tasks using a timer I would like to know if it's ok to use Timer inside application scoped beans.
Example, lets say that I want to create a timer task that sends out a bunch of emails to every registered member one time per day. I'm trying to use as much JSF as possible and I would like to know if this is acceptable (it sounders a bit weird, I know).
Until now I have used all of the above inside a ServletContextListener. (I don't want to use any application server or cron job and I want to keep
the above things inside my web app.)
Is there a smart JSF way of doing this or should I stick with the old pattern?
A: Introduction
As to spawning a thread from inside a JSF managed bean, it would only make sense if you want to be able to reference it in your views by #{managedBeanName} or in other managed beans by @ManagedProperty("#{managedBeanName}"). You should only make sure that you implement @PreDestroy to ensure that all those threads are shut down whenever the webapp is about to shutdown, like as you would do in contextDestroyed() method of ServletContextListener (yes, you did?). See also Is it safe to start a new thread in a JSF managed bean?
Never use java.util.Timer in Java EE
As to using java.util.Timer in a JSF managed bean, you should absolutely not use the old fashioned Timer, but the modern ScheduledExecutorService. The Timer has the following major problems which makes it unsuitable for use in a long running Java EE web application (quoted from Java Concurrency in Practice):
*
*Timer is sensitive to changes in the system clock, ScheduledExecutorService isn't.
*Timer has only one execution thread, so long-running task can delay other tasks. ScheduledExecutorService can be configured with any number of threads.
*Any runtime exceptions thrown in a TimerTask kill that one thread, thus making Timer dead, i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want. Task which threw exception will be canceled, but other tasks will continue to run.
Apart from the book quotes, I can think of more disadvantages:
*
*If you forget to explicitly cancel() the Timer, then it keeps running after undeployment. So after a redeploy a new thread is created, doing the same job again. Etcetera. It has become a "fire and forget" by now and you can't programmatically cancel it anymore. You'd basically need to shutdown and restart the whole server to clear out previous threads.
*If the Timer thread is not marked as daemon thread, then it will block the webapp's undeployment and server's shutdown. You'd basically need to hard kill the server. The major disadvantage is that the webapp won't be able to perform graceful cleanup via e.g. contextDestroyed() and @PreDestroy methods.
EJB available? Use @Schedule
If you target Java EE 6 or newer (e.g. JBoss AS, GlassFish, TomEE, etc and thus not a barebones JSP/Servlet container such as Tomcat), then use a @Singleton EJB with a @Schedule method instead. This way the container will worry itself about pooling and destroying threads via ScheduledExecutorService. All you need is then the following EJB:
@Singleton
public class BackgroundJobManager {
@Schedule(hour="0", minute="0", second="0", persistent=false)
public void someDailyJob() {
// Do your job here which should run every start of day.
}
@Schedule(hour="*/1", minute="0", second="0", persistent=false)
public void someHourlyJob() {
// Do your job here which should run every hour of day.
}
@Schedule(hour="*", minute="*/15", second="0", persistent=false)
public void someQuarterlyJob() {
// Do your job here which should run every 15 minute of hour.
}
}
This is if necessary available in managed beans by @EJB:
@EJB
private BackgroundJobManager backgroundJobManager;
EJB unavailable? Use ScheduledExecutorService
Without EJB, you'd need to manually work with ScheduledExecutorService. The application scoped managed bean implementation would look something like this:
@ManagedBean(eager=true)
@ApplicationScoped
public class BackgroundJobManager {
private ScheduledExecutorService scheduler;
@PostConstruct
public void init() {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS);
}
@PreDestroy
public void destroy() {
scheduler.shutdownNow();
}
}
where the SomeDailyJob look like this:
public class SomeDailyJob implements Runnable {
@Override
public void run() {
// Do your job here.
}
}
If you don't need to reference it in the view or other managed beans at all, then better just use ServletContextListener to keep it decoupled from JSF.
@WebListener
public class BackgroundJobManager implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: Problem debugging hang-dump in windbg After I've loaded sosex, I'm getting the following error. Any ideas? The hang dump is from a 32 bit machine, mine is 64-bit. Do I need to install something?
!clrstack
CLR DLL status: ERROR: Unable to load DLL mscordacwks_x86_x86_2.0.50727.3623.dll, Win32 error 0n2
A: The problem is the version of mscordacwks on your machine is a different version than the one from the crash dump. It's not a bitnesss issue - even though your machine is 64-bit, you have a 32-bit .NET installed. Mine is under C:\Windows\Microsoft.NET\Framework\v2.0.50727.
The copy you have won't have that long name, it'll just be called mscordacwks.dll. When the debugger sees your "active" copy is different, it'll search for one with the long name (avoiding dll hell) and that also tells you what version you need to get. After I get the correct mscordacwks.dll (eg from the original machine), I copy it into my framework directory and name it as it shows in the error message. I also set the image path of windbg to include the framework directory.
sos must use the mscordacwks framework assembly to understand the in memory data structures. This is all explained in the blog post “Failed to load data access DLL, 0x80004005” – OR – What is mscordacwks.dll? on the Notes from a dark corner blog.
You'll find the internet littered with questions about how to get various versions of that dll. Assuming you can't get the one from the machine that created the crash dump and it doesn't get downloaded from the microsoft symbol server, what I've done in the past is search microsoft.com for mscordacwks and the version I need (eg 2.0.50727.3623). It's usually in a security patch you can download.
If you don't have an appropriate system to install it on, I've had luck opening the install exe with 7zip. I've found the mscordacwks file in a cab that was in a patch file (an MSP file) that was in the security patch install executable. Each of those can be opened with 7zip.
When you hit a CAB file, sometimes it's better to use expand.exe as it can decompress files 7zip (v4.65) doesn't. If you open a CAB with 7zip that has an _manifest_.cix.xml, use expand instead as it uses the manifest to extract, decompress and rename the contents. 7zip (doing a simple extract to...) leaves it raw with bunches of files named numerically, literally 1, 2, etc. Those files may still be compressed. The way you know is if you open them (eg with SciTE),they'll start with a signature like PA30 (it will match the source "type" attribute from the manifest).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with IE position: absolute I have this code it works quite well in Firefox; but shoots to the right on Explorer. Is there anything wrong with this code that I can't see?
Your help is appreciated
<div style="position: absolute; top: 170px"><a href="http://www.mysite.com"><img src="images/sponsor.png" /></a></div>
What I'm expecting is for the image to show on top of the main header image- which works alright on Firefox, but moves to the far right in IE causing the site to break. Not sure why this is happening.
A: Add left: 0px; as well, IE probably won't give it such default value:
<div style="position: absolute; top: 170px; left: 0px;">
A: I found out that IE won't recognize properties declared like :
top:(space)20px;
- so if you have a space between : and 20px IE will ignore that property. I hope this helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to connect android device with local network I am using android 2.2 for application development.
Now I want to communicate with web service. The web service is running on my laptop and IP is 192.168.1.15.
But device not communicate.
How to communicate with local network?
A: From inside the Android emulator, your laptop is actually 10.0.2.2.
A: try to pass 192.168.1.15/yourwebservice in device web browser. If it does not runs, then you should switch off your laptops firewall.(if using windows OS).
And if it runs then there might be some problem with ur application.
Paste code in that case for further help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting CodeMirror to follow a TextArea How can I get CodeMirror to sync with a TextArea, so that the cursor position, selection & data stay the same on the both of them?
I'm using CodeMirror with MobWrite. CodeMirror only uses a textArea to read input & MobWrite can handle the selection, etc over a given TextArea, the problem is to get CodeMirror to sync with a TextArea.
A: Extended the ModWrite code to support CodeMirror & it works like a charm.
It can also be found on GitHub. Details on the CodeMirror Group.
Code dumped below for all who may tread this path:
// CODEMIRROR INPUTS : Aped from Neil's code
/*
Set a 'id' property for your codeMirror obj
NoteToSelf: mobwrite.shareCodeMirrorObj.prototype.captureCursor_ - implement hasFocus
import linech2n func
import this code after you import MobWrite.
*/
/**
* Constructor of shared object representing a CodeMirror obj
*/
mobwrite.shareCodeMirrorObj = function(cmObj) {
// Call our prototype's constructor.
if(!"id" in cmObj) cmObj.id="TEMP";
mobwrite.shareObj.apply(this, [cmObj.id]);
this.element = cmObj;
};
// The textarea shared object's parent is a shareObj.
mobwrite.shareCodeMirrorObj.prototype = new mobwrite.shareObj('');
/**
* Retrieve the user's text.
* @return {string} Plaintext content.
*/
mobwrite.shareCodeMirrorObj.prototype.getClientText = function() {
var text = mobwrite.shareCodeMirrorObj.normalizeLinebreaks_(this.element.getValue());
return text;
};
/**
* Set the user's text.
* @param {string} text New text
*/
mobwrite.shareCodeMirrorObj.prototype.setClientText = function(text) {
this.element.setValue(text);
this.fireChange(this.element.getInputField());
};
/**
* Modify the user's plaintext by applying a series of patches against it.
* @param {Array.<patch_obj>} patches Array of Patch objects.
*/
mobwrite.shareCodeMirrorObj.prototype.patchClientText = function(patches) {
// Set some constants which tweak the matching behaviour.
// Maximum distance to search from expected location.
this.dmp.Match_Distance = 1000;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose)
this.dmp.Match_Threshold = 0.6;
var oldClientText = this.getClientText();
var cursor = this.captureCursor_();
// Pack the cursor offsets into an array to be adjusted.
// See http://neil.fraser.name/writing/cursor/
var offsets = [];
if (cursor) {
offsets[0] = cursor.startOffset;
if ('endOffset' in cursor) {
offsets[1] = cursor.endOffset;
}
}
var newClientText = this.patch_apply_(patches, oldClientText, offsets);
// Set the new text only if there is a change to be made.
if (oldClientText != newClientText) {
this.setClientText(newClientText);
if (cursor) {
// Unpack the offset array.
cursor.startOffset = offsets[0];
if (offsets.length > 1) {
cursor.endOffset = offsets[1];
if (cursor.startOffset >= cursor.endOffset) {
cursor.collapsed = true;
}
}
this.restoreCursor_(cursor);
}
}
};
/**
* Merge a set of patches onto the text. Return a patched text.
* @param {Array.<patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @param {Array.<number>} offsets Offset indices to adjust.
* @return {string} New text.
*/
mobwrite.shareCodeMirrorObj.prototype.patch_apply_ =
function(patches, text, offsets) {
if (patches.length == 0) {
return text;
}
// Deep copy the patches so that no changes are made to originals.
patches = this.dmp.patch_deepCopy(patches);
var nullPadding = this.dmp.patch_addPadding(patches);
text = nullPadding + text + nullPadding;
this.dmp.patch_splitMax(patches);
// delta keeps track of the offset between the expected and actual location
// of the previous patch. If there are patches expected at positions 10 and
// 20, but the first patch was found at 12, delta is 2 and the second patch
// has an effective expected position of 22.
var delta = 0;
for (var x = 0; x < patches.length; x++) {
var expected_loc = patches[x].start2 + delta;
var text1 = this.dmp.diff_text1(patches[x].diffs);
var start_loc;
var end_loc = -1;
if (text1.length > this.dmp.Match_MaxBits) {
// patch_splitMax will only provide an oversized pattern in the case of
// a monster delete.
start_loc = this.dmp.match_main(text,
text1.substring(0, this.dmp.Match_MaxBits), expected_loc);
if (start_loc != -1) {
end_loc = this.dmp.match_main(text,
text1.substring(text1.length - this.dmp.Match_MaxBits),
expected_loc + text1.length - this.dmp.Match_MaxBits);
if (end_loc == -1 || start_loc >= end_loc) {
// Can't find valid trailing context. Drop this patch.
start_loc = -1;
}
}
} else {
start_loc = this.dmp.match_main(text, text1, expected_loc);
}
if (start_loc == -1) {
// No match found. :(
if (mobwrite.debug) {
window.console.warn('Patch failed: ' + patches[x]);
}
// Subtract the delta for this failed patch from subsequent patches.
delta -= patches[x].length2 - patches[x].length1;
} else {
// Found a match. :)
if (mobwrite.debug) {
window.console.info('Patch OK.');
}
delta = start_loc - expected_loc;
var text2;
if (end_loc == -1) {
text2 = text.substring(start_loc, start_loc + text1.length);
} else {
text2 = text.substring(start_loc, end_loc + this.dmp.Match_MaxBits);
}
// Run a diff to get a framework of equivalent indices.
var diffs = this.dmp.diff_main(text1, text2, false);
if (text1.length > this.dmp.Match_MaxBits &&
this.dmp.diff_levenshtein(diffs) / text1.length >
this.dmp.Patch_DeleteThreshold) {
// The end points match, but the content is unacceptably bad.
if (mobwrite.debug) {
window.console.warn('Patch contents mismatch: ' + patches[x]);
}
} else {
var index1 = 0;
var index2;
for (var y = 0; y < patches[x].diffs.length; y++) {
var mod = patches[x].diffs[y];
if (mod[0] !== DIFF_EQUAL) {
index2 = this.dmp.diff_xIndex(diffs, index1);
}
if (mod[0] === DIFF_INSERT) { // Insertion
text = text.substring(0, start_loc + index2) + mod[1] +
text.substring(start_loc + index2);
for (var i = 0; i < offsets.length; i++) {
if (offsets[i] + nullPadding.length > start_loc + index2) {
offsets[i] += mod[1].length;
}
}
} else if (mod[0] === DIFF_DELETE) { // Deletion
var del_start = start_loc + index2;
var del_end = start_loc + this.dmp.diff_xIndex(diffs,
index1 + mod[1].length);
text = text.substring(0, del_start) + text.substring(del_end);
for (var i = 0; i < offsets.length; i++) {
if (offsets[i] + nullPadding.length > del_start) {
if (offsets[i] + nullPadding.length < del_end) {
offsets[i] = del_start - nullPadding.length;
} else {
offsets[i] -= del_end - del_start;
}
}
}
}
if (mod[0] !== DIFF_DELETE) {
index1 += mod[1].length;
}
}
}
}
}
// Strip the padding off.
text = text.substring(nullPadding.length, text.length - nullPadding.length);
return text;
};
/**
* Record information regarding the current cursor.
* @return {Object?} Context information of the cursor.
* @private
*/
mobwrite.shareCodeMirrorObj.prototype.captureCursor_ = function() {
this.element.focus();//change to hasFocus()?Pass:return null;
var padLength = this.dmp.Match_MaxBits / 2; // Normally 16.
var text = this.element.getValue();
var cursor = {};
var selectionStart = linech2n(this.element, this.element.getCursor(true));
var selectionEnd = linech2n(this.element, this.element.getCursor(false));
cursor.startPrefix = text.substring(selectionStart - padLength, selectionStart);
cursor.startSuffix = text.substring(selectionStart, selectionStart + padLength);
cursor.startOffset = selectionStart;
cursor.collapsed = (selectionStart == selectionEnd);
if (!cursor.collapsed) {
cursor.endPrefix = text.substring(selectionEnd - padLength, selectionEnd);
cursor.endSuffix = text.substring(selectionEnd, selectionEnd + padLength);
cursor.endOffset = selectionEnd;
}
// Record scrollbar locations
if ('scrollTop' in this.element.getScrollerElement()) {
scroller = this.element.getScrollerElement();
cursor.scrollTop = scroller.scrollTop / scroller.scrollHeight;
cursor.scrollLeft = scroller.scrollLeft / scroller.scrollWidth;
}
// alert(cursor.startPrefix + '|' + cursor.startSuffix + ' ' +
// cursor.startOffset + '\n' + cursor.endPrefix + '|' +
// cursor.endSuffix + ' ' + cursor.endOffset + '\n' +
// cursor.scrollTop + ' x ' + cursor.scrollLeft);
return cursor;
};
/**
* Attempt to restore the cursor's location.
* @param {Object} cursor Context information of the cursor.
* @private
*/
mobwrite.shareCodeMirrorObj.prototype.restoreCursor_ = function(cursor) {
// Set some constants which tweak the matching behaviour.
// Maximum distance to search from expected location.
this.dmp.Match_Distance = 1000;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose)
this.dmp.Match_Threshold = 0.9;
var padLength = this.dmp.Match_MaxBits / 2; // Normally 16.
var newText = this.element.getValue();
// Find the start of the selection in the new text.
var pattern1 = cursor.startPrefix + cursor.startSuffix;
var pattern2, diff;
var cursorStartPoint = this.dmp.match_main(newText, pattern1,
cursor.startOffset - padLength);
if (cursorStartPoint !== null) {
pattern2 = newText.substring(cursorStartPoint,
cursorStartPoint + pattern1.length);
//alert(pattern1 + '\nvs\n' + pattern2);
// Run a diff to get a framework of equivalent indicies.
diff = this.dmp.diff_main(pattern1, pattern2, false);
cursorStartPoint += this.dmp.diff_xIndex(diff, cursor.startPrefix.length);
}
var cursorEndPoint = null;
if (!cursor.collapsed) {
// Find the end of the selection in the new text.
pattern1 = cursor.endPrefix + cursor.endSuffix;
cursorEndPoint = this.dmp.match_main(newText, pattern1,
cursor.endOffset - padLength);
if (cursorEndPoint !== null) {
pattern2 = newText.substring(cursorEndPoint,
cursorEndPoint + pattern1.length);
//alert(pattern1 + '\nvs\n' + pattern2);
// Run a diff to get a framework of equivalent indicies.
diff = this.dmp.diff_main(pattern1, pattern2, false);
cursorEndPoint += this.dmp.diff_xIndex(diff, cursor.endPrefix.length);
}
}
// Deal with loose ends
if (cursorStartPoint === null && cursorEndPoint !== null) {
// Lost the start point of the selection, but we have the end point.
// Collapse to end point.
cursorStartPoint = cursorEndPoint;
} else if (cursorStartPoint === null && cursorEndPoint === null) {
// Lost both start and end points.
// Jump to the offset of start.
cursorStartPoint = cursor.startOffset;
}
if (cursorEndPoint === null) {
// End not known, collapse to start.
cursorEndPoint = cursorStartPoint;
}
// Restore selection.
this.element.setSelection(n2linech(this.element, cursorStartPoint), n2linech(this.element, cursorEndPoint));
// Restore scrollbar locations
if ('scrollTop' in cursor) {
this.element.getScrollerElement().scrollTop = cursor.scrollTop * this.element.getScrollerElement().scrollHeight;
this.element.getScrollerElement().scrollLeft = cursor.scrollLeft * this.element.getScrollerElement().scrollWidth;
}
};
/**
* Ensure that all linebreaks are LF
* @param {string} text Text with unknown line breaks
* @return {string} Text with normalized linebreaks
* @private
*/
mobwrite.shareCodeMirrorObj.normalizeLinebreaks_ = function(text) {
return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
};
/**
* Handler to accept CodeMirror Objs
* @param {*} cmObj CodeMirror Object.
* @return {Object?} A sharing object or null.
*/
mobwrite.shareCodeMirrorObj.shareHandler = function(cmObj) {
if ('lineCount' in cmObj) {
return new mobwrite.shareCodeMirrorObj(cmObj);
}
return null;
};
// Register this shareHandler with MobWrite.
mobwrite.shareHandlers.push(mobwrite.shareCodeMirrorObj.shareHandler);
//functions for converting b/n index on the data string & the {line, ch} obj of codeMirror
function linech2n(ed, linech) {
var line = linech.line;
var ch = linech.ch;
var n = line + ch; //for the \n s & chars in the line
for(i=0;i<line;i++) {
n += (ed.getLine(i)).length;//for the chars in all preceeding lines
}
return n;
}
function n2linech(ed, n) {
var line=0, ch=0, index=0;
for(i=0;i<ed.lineCount();i++) {
len = (ed.getLine(i)).length;
if(n < index+len) {
//alert(len+","+index+","+(n-index));
line = i;
ch = n-index;
return {line:line, ch:ch};
}
len++;//for \n char
index += len;
}
return {line:line, ch:ch};
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Azure SDK 1.5 installation error I had Azure SDK 1.4 installed on my machine (win7-64) that was used in VS2010-SP1.
now I started working on a project that is using Azure SDK 1.5, while trying to upgrade, the SDK, via with WPI3.0.
The installation failed, with the error: "Windows Azure SDK this product did not install sueccessfully".
So, I have decided to try to install it manually from the folder ...\50F77816F4EAEA75902EAE4F5C980656052EAB88\WindowsAzureSDK-x64.exe. before that, I have removed the Azure SDK 1.4 + restart) which resulted an error: "The installer has encountered an unexpected error installing this package. This may indicate a problem with the package. The error code is 2738." ("regsvr32.exe vbscript.dll" didn't help as well...)
Any ideas?
WPI error log:
DownloadManager Information: 0 : Loading product xml from: https://go.microsoft.com/?linkid=9767054
DownloadManager Information: 0 : https://go.microsoft.com/?linkid=9767054 responded with 302
DownloadManager Information: 0 : Response headers:
HTTP/1.1 302 Found
Cache-Control: private
Content-Length: 175
Content-Type: text/html; charset=utf-8
Expires: Wed, 21 Sep 2011 11:41:25 GMT
Location: https://www.microsoft.com/web/webpi/3.0/webproductlist.xml
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
Set-Cookie: MC1=GUID=b28ba68909cb9f4fb2743cebb287bbb8&HASH=89a6&LV=20119&V=3; domain=microsoft.com; expires=Sun, 03-Oct-2010 07:00:00 GMT; path=/
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:24 GMT
DownloadManager Information: 0 : https://www.microsoft.com/web/webpi/3.0/webproductlist.xml responded with 304
DownloadManager Information: 0 : Response headers:
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Last-Modified: Tue, 20 Sep 2011 00:14:47 GMT
Accept-Ranges: bytes
ETag: "fb334c4e2a77cc1:0"
Server: Microsoft-IIS/7.5
VTag: 438616531000000000
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:26 GMT
DownloadManager Information: 0 : Remote file has not changed, using local cached file: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\542864071.xml.temp
DownloadManager Information: 0 : Filtering by majorOS: 6, minorOS: 1, majorSP: 1, minorSP: 0, productType: 6, architecture: x64
DownloadManager Information: 0 : Loading product xml from: https://www.microsoft.com/web/webpi/3.0/webapplicationlist.xml
DownloadManager Information: 0 : https://www.microsoft.com/web/webpi/3.0/webapplicationlist.xml responded with 304
DownloadManager Information: 0 : Response headers:
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Last-Modified: Mon, 19 Sep 2011 18:48:23 GMT
Accept-Ranges: bytes
ETag: "dc09db5fc76cc1:0"
Server: Microsoft-IIS/7.5
VTag: 279981030800000000
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:26 GMT
DownloadManager Information: 0 : Remote file has not changed, using local cached file: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\-1338951197.xml.temp
DownloadManager Information: 0 : Filtering by majorOS: 6, minorOS: 1, majorSP: 1, minorSP: 0, productType: 6, architecture: x64
DownloadManager Information: 0 : Loading product xml from: https://www.microsoft.com/web/webpi/3.0/mediaproductlist.xml
DownloadManager Information: 0 : https://www.microsoft.com/web/webpi/3.0/mediaproductlist.xml responded with 304
DownloadManager Information: 0 : Response headers:
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Last-Modified: Thu, 08 Sep 2011 00:24:00 GMT
Accept-Ranges: bytes
ETag: "256f3f9bbd6dcc1:0"
Server: Microsoft-IIS/7.5
VTag: 279183230500000000
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:27 GMT
DownloadManager Information: 0 : Remote file has not changed, using local cached file: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\664384761.xml.temp
DownloadManager Information: 0 : Filtering by majorOS: 6, minorOS: 1, majorSP: 1, minorSP: 0, productType: 6, architecture: x64
DownloadManager Information: 0 : Loading product xml from: https://www.microsoft.com/web/webpi/3.0/toolsproductlist.xml
DownloadManager Information: 0 : https://www.microsoft.com/web/webpi/3.0/toolsproductlist.xml responded with 304
DownloadManager Information: 0 : Response headers:
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Last-Modified: Wed, 14 Sep 2011 06:06:39 GMT
Accept-Ranges: bytes
ETag: "2b55cd77a472cc1:0"
Server: Microsoft-IIS/7.5
VTag: 79171731300000000
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:27 GMT
DownloadManager Information: 0 : Remote file has not changed, using local cached file: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\1956869252.xml.temp
DownloadManager Information: 0 : Filtering by majorOS: 6, minorOS: 1, majorSP: 1, minorSP: 0, productType: 6, architecture: x64
DownloadManager Information: 0 : Loading product xml from: https://www.microsoft.com/web/webpi/3.0/enterpriseproductlist.xml
DownloadManager Information: 0 : https://www.microsoft.com/web/webpi/3.0/enterpriseproductlist.xml responded with 304
DownloadManager Information: 0 : Response headers:
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Last-Modified: Wed, 06 Apr 2011 17:49:12 GMT
Accept-Ranges: bytes
ETag: "2c1614f082f4cb1:0"
Server: Microsoft-IIS/7.5
VTag: 791755030500000000
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:27 GMT
DownloadManager Information: 0 : Remote file has not changed, using local cached file: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\903079739.xml.temp
DownloadManager Information: 0 : Filtering by majorOS: 6, minorOS: 1, majorSP: 1, minorSP: 0, productType: 6, architecture: x64
DownloadManager Information: 0 : Getting ratings file from http://go.microsoft.com/?linkid=9752395
DownloadManager Information: 0 : http://go.microsoft.com/?linkid=9752395 responded with 302
DownloadManager Information: 0 : Response headers:
HTTP/1.1 302 Found
Cache-Control: private
Content-Length: 203
Content-Type: text/html; charset=utf-8
Expires: Wed, 21 Sep 2011 11:41:29 GMT
Location: http://www.microsoft.com/web/handlers/WebPI.ashx?command=getatomfeedwithavgratingquery
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
Set-Cookie: MC1=GUID=f8eb0e8292bad14cbadbe1be35bf82be&HASH=820e&LV=20119&V=3; domain=microsoft.com; expires=Sun, 03-Oct-2010 07:00:00 GMT; path=/
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2011 11:42:29 GMT
DownloadManager Information: 0 : Ratings file loaded successfully
DownloadManager Information: 0 : Adding product Windows Azure Tools for Microsoft Visual Studio 2010 - September 2011 (WindowsAzureToolsVS2010) to cart
DownloadManager Information: 0 : Adding product Windows Azure AppFabric SDK V1.5 (AzureAppFabricSDKV1PROD) to cart
DownloadManager Information: 0 : Removing product Windows Azure AppFabric SDK V1.5 (AzureAppFabricSDKV1PROD) from cart
DownloadManager Information: 0 : Adding product Windows Azure AppFabric SDK V1.5 (AzureAppFabricSDKV1PROD) to cart
DownloadManager Information: 0 : Removing product Windows Azure Tools for Microsoft Visual Studio 2010 - September 2011 (WindowsAzureToolsVS2010) from cart
DownloadManager Information: 0 : Removing product Windows Azure AppFabric SDK V1.5 (AzureAppFabricSDKV1PROD) from cart
DownloadManager Information: 0 : Adding product Windows Azure AppFabric SDK V1.5 (AzureAppFabricSDKV1PROD) to cart
DownloadManager Information: 0 : Adding product Windows Azure Tools for Microsoft Visual Studio 2010 - September 2011 (WindowsAzureToolsVS2010) to cart
DownloadManager Information: 0 : Adding product 'AzureAppFabricSDKV1PROD'
DownloadManager Information: 0 : Product 'NETFramework4' is installed. Not adding
DownloadManager Information: 0 : Product 'WindowsImagingComponent' is installed. Not adding
DownloadManager Information: 0 : Adding product 'WindowsAzureToolsVS2010'
DownloadManager Information: 0 : Adding dependency product 'WindowsAzureSDK' for product 'WindowsAzureToolsVS2010'
DownloadManager Information: 0 : Product 'ASPNET' is installed. Not adding
DownloadManager Information: 0 : Product 'StaticContent' is installed. Not adding
DownloadManager Information: 0 : Product 'WASProcessModel' is installed. Not adding
DownloadManager Information: 0 : Product 'NETExtensibility' is installed. Not adding
DownloadManager Information: 0 : Product 'RequestFiltering' is installed. Not adding
DownloadManager Information: 0 : Product 'WASNetFxEnvironment' is installed. Not adding
DownloadManager Information: 0 : Product 'ISAPIExtensions' is installed. Not adding
DownloadManager Information: 0 : Product 'ISAPIFilters' is installed. Not adding
DownloadManager Information: 0 : Product 'DefaultDocument' is installed. Not adding
DownloadManager Information: 0 : Product 'CGI' is installed. Not adding
DownloadManager Information: 0 : Product 'UrlRewrite2' is installed. Not adding
DownloadManager Information: 0 : Product 'FastCGIUpdate' is installed. Not adding
DownloadManager Information: 0 : Product 'NETFramework35' is installed. Not adding
DownloadManager Information: 0 : Product 'PowerShell' is installed. Not adding
DownloadManager Information: 0 : Dependent product PowerShellMsu does not apply for current OS / configuration. Not adding
DownloadManager Information: 0 : Product 'IISManagementConsole' is installed. Not adding
DownloadManager Information: 0 : Product 'WASConfigurationAPI' is installed. Not adding
DownloadManager Information: 0 : Product 'DirectoryBrowse' is installed. Not adding
DownloadManager Information: 0 : Product 'HTTPErrors' is installed. Not adding
DownloadManager Information: 0 : Product 'HTTPRedirection' is installed. Not adding
DownloadManager Information: 0 : Product 'HTTPLogging' is installed. Not adding
DownloadManager Information: 0 : Product 'LoggingTools' is installed. Not adding
DownloadManager Information: 0 : Product 'Tracing' is installed. Not adding
DownloadManager Information: 0 : Product 'RequestMonitor' is installed. Not adding
DownloadManager Information: 0 : Adding dependency product 'WindowsAzureToolsVS2010ToolsOnly' for product 'WindowsAzureToolsVS2010'
DownloadManager Information: 0 : Product 'VS2010SP1Core' is installed. Not adding
DownloadManager Information: 0 : Product 'VS2010SP1Prerequisite' is installed. Not adding
DownloadManager Information: 0 : Product 'MVC3' is installed. Not adding
DownloadManager Information: 0 : Adding dependency product 'MVC3Installer' for product 'MVC3'
DownloadManager Information: 0 : No SQL to configure
DownloadManager Information: 0 : No MySQL to configure
DownloadManager Information: 0 : Setting current install to 1
DownloadManager Information: 0 : Starting install sequence
DownloadManager Information: 0 : Downloading file 'http://download.microsoft.com/download/F/9/5/F95A2093-134F-4182-8C0E-8678699202F4/WindowsAzureAppFabricSDK-x64.msi' to: C:\Users\XXXUser\AppData\Local\Temp\tmp9EF0.tmp
DownloadManager Information: 0 : Content-disposition header: attachment
DownloadManager Information: 0 : Moving downloaded file 'C:\Users\XXXUser\AppData\Local\Temp\tmp9EF0.tmp' to: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\AzureAppFabricSDKV1PROD\30D476EC3B25D7A180805C3DD4F2986BAD882879\WindowsAzureAppFabricSDK-x641.msi
DownloadManager Information: 0 : Using cached file at C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\WindowsAzureSDK\50f77816f4eaea75902eae4f5c980656052eab88\WindowsAzureSDK-x64.exe instead of downloading from http://download.microsoft.com/download/8/4/C/84C12C90-0831-485B-A181-A11A56389826/WindowsAzureSDK-x64.exe
DownloadManager Information: 0 : Starting MSI install for msi 'C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\AzureAppFabricSDKV1PROD\30D476EC3B25D7A180805C3DD4F2986BAD882879\WindowsAzureAppFabricSDK-x641.msi', commandline: 'ACTION=INSTALL REBOOT=ReallySuppress'
DownloadManager Information: 0 : Using cached file at C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\WindowsAzureToolsVS2010ToolsOnly\08958b0b72b3b9c71836a8ac6e14ea4cf484d9db\VSCloudService.VS100.en-us.msi instead of downloading from http://download.microsoft.com/download/8/4/C/84C12C90-0831-485B-A181-A11A56389826/VSCloudService.VS100.en-us.msi
DownloadManager Information: 0 : Using cached file at C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\MVC3Installer\7a15ca7a49ac8a9edfe71ac0873a8aa38338c029\AspNetMVC3ToolsUpdateSetup.exe instead of downloading from http://download.microsoft.com/download/F/3/1/F31EF055-3C46-4E35-AB7B-3261A303A3B6/AspNetMVC3ToolsUpdateSetup.exe
DownloadManager Information: 0 : MSI install return value for product 'Windows Azure AppFabric SDK V1.5' is 0
DownloadManager Information: 0 : Install return code for product 'Windows Azure AppFabric SDK V1.5' is Success
DownloadManager Information: 0 : Product Windows Azure AppFabric SDK V1.5 done install completed
DownloadManager Information: 0 : Increasing current install to 2
DownloadManager Information: 0 : Windows Azure AppFabric SDK V1.5 installation log: C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\logs\install\2011-09-21T14.43.00\WindowsAzureAppFabricSDK-x641.txt
DownloadManager Information: 0 : Starting EXE command for product 'Windows Azure SDK'. Commandline is: 'C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\WindowsAzureSDK\50f77816f4eaea75902eae4f5c980656052eab88\WindowsAzureSDK-x64.exe /quiet /norestart'. Process Id: 3112
DownloadManager Information: 0 : Install exit code for product 'Windows Azure SDK' is 1603
DownloadManager Error: 0 : Install return code for product 'Windows Azure SDK' is Failure
DownloadManager Information: 0 : Product Windows Azure SDK done install completed
DownloadManager Information: 0 : Increasing current install to 3
DownloadManager Warning: 0 : Dependency failed for product 'Windows Azure Tools for Microsoft Visual Studio 2010 v1.5'. Skipping install
DownloadManager Information: 0 : Product Windows Azure Tools for Microsoft Visual Studio 2010 v1.5 had a dependency fail. Increasing install product to 4
DownloadManager Warning: 0 : Dependency failed for product 'Windows Azure Tools for Microsoft Visual Studio 2010 - September 2011'. Skipping install
DownloadManager Information: 0 : Product Windows Azure Tools for Microsoft Visual Studio 2010 - September 2011 had a dependency fail. Increasing install product to 5
DownloadManager Information: 0 : Starting EXE command for product 'ASP.NET MVC 3 Tools Update Installer'. Commandline is: 'C:\Users\XXXUser\AppData\Local\Microsoft\Web Platform Installer\installers\MVC3Installer\7a15ca7a49ac8a9edfe71ac0873a8aa38338c029\AspNetMVC3ToolsUpdateSetup.exe /q /log C:\Users\XXXUser\AppData\Local\Temp\mvc3_install.htm'. Process Id: 3596
DownloadManager Information: 0 : Install exit code for product 'ASP.NET MVC 3 Tools Update Installer' is 0
DownloadManager Information: 0 : Install return code for product 'ASP.NET MVC 3 Tools Update Installer' is Success
DownloadManager Information: 0 : Product ASP.NET MVC 3 Tools Update Installer done install completed
DownloadManager Information: 0 : Increasing current install to 6
A: Found an answer here: http://social.msdn.microsoft.com/Forums/en/windowsazuredevelopment/thread/95579e93-0a46-4627-857b-f1c354526885
this helped: http://blogs.technet.com/b/fixit4me/archive/2009/03/31/error-code-2738-when-running-a-microsoft-fix-it-solution.aspx
Thank you all
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to copy several rows between two equal tables with JPA/Hibernate? Is there a way to do something like
INSERT INTO ... SELECT ...
with JPQL? Both tables are structurally equal, so that I defined two entity classes which inherit all field mappings from a superclass. The two @Entity subclasses differ only in their names and @Table annotations.
We use JPA 2.0 and Hibernate 3.5.
A: String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ...";
int createdEntities = s.createQuery(hqlInsert).executeUpdate();
See here for more information
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is the body background in my website not showing up? The website is http://www.sarahjanetrading.com/.
Here is the link for the image of the design so you could see the difference.
http://i52.tinypic.com/de6yja.png
In the body, you can see a little portion of gray(which is actually part of the header image), but the rest of the body is white. Please help.
Also I have used a lot of CSS3 properties in the website, and have used the IE7-js to make IE-6 to IE-8 render it like IE9, but it doesnt seem to be working. Is there some other script or a newer method to do it?
Thanks alot.
A: Your div #header (http://www.sarahjanetrading.com/style.css) should be larger. Change 570px to 670px
#header (line 46)
{
**height: 570px;**
background-color: #540451;
background-image: url("images/header.jpg");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: center top;
background-clip: border-box;
background-origin: padding-box;
background-size: auto auto;
overflow-x: auto;
overflow-y: auto;
}
Cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Generating the correct content for a page without JS when using Hash tag. My page is currently loaded using a GET variable. when you arrive at the page, the GET vairable loads in a set of images, starting off with the GET variable one. You then browse these images and if you have JS enabled the Hash tag is updated to reflect the current image. If you dont have JS enabled then the page is regenerated with a new GET variable.
the problem is if someone has JS enabled and moves to an image which they then want to send the URL link to a friend who doesn't have JS enabled, the friend will receive the incorrect link, as the GET variable will be used (which hasn't changed) and the # will be ignored because PHP can't read it.
an example of this is on my site using this link
www.martynazoltaszek.com/artpages?nid=27#Safe Place
with JS enabled you arrive correctly (at Safe Place(based on #value)), without JS you arrive incorrectly (at #Dream (based on GET Variable))
Safe Place
Dream
One obvious solution is to use the GET Variable instead of the # but this generates a Page refresh, which I'm trying to avoid.
Any ideas of a solution here?
And thanks for looking.
A: There's no standard solution to this problem, that's why many sites place permalinks boxes next to the resources as a way to expose a hash-less link which will work on all browser.
You current url scheme is not very consistent and might be confusing because it is possible to pass contradictory information about the image in the query string and the hash.
There are ways to solve your problems but they are not standard. For instance some browsers support modifications of the URL without page reload. Another non-standard option is to allow your web server to expose the hash tag among its request variables. It is not conventional but it would allow your PHP code to read the hash.
A: If I understand correctly, (sorry if this is not your case) you want a link such that when clicked to tell you if the user that clicked it has js enabled.
I think this is trivial, all you have to do is to let php know if the link was clicked from a browser with js enabled or not and then php will take the analogous action. I would do this like this:
Share this kind of link:
<a href="http://localhost/js_enabled/serverSide.php"
onclick="href='http://localhost/js_enabled/serverSide.php?js=1'">link</a>
To see how it works, this is a small php:
<?PHP
if(!isset($_GET['js']))
echo 'Oops! You js is not enabled!';
else
echo 'Okay your js is enabled.';
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: recurse through list of strings - how to tell the difference? I have the following code
def printmylist( mylist ):
"""
print tree
"""
try:
for f in mylist:
printmylist( f )
except:
print( " " + mylist )
hoping to get output like:
root
branch
leaf
leaf
but since a string is enumerable, I get
r
o
o
t
.
.
Checking for type seems to be unpythonic, so how would a Pythonian go about this?
A: The cleanest way that I know of is to use types.StringTypes (not to be confused with types.StringType):
isinstance(var, types.StringTypes)
Alternatively:
isinstance(var, basestring)
Documentation for the types module indicates that the latter is the preferred way in recent versions of Python 2.x.
A: I use the following pythonic approach to this problem. No isinstance() calls required. Therefore it even works with various custom C++ string classes I have wrapped in python. I don't think those isinstance() based methods would work in those cases. Plus the OP explicitly asked for a solution that does not involve type checking. Pythonistas check behavior, not type.
The trick here involves the observation that strings have an unusual property: the first element of a one-character string is the same one-character string.
"f"[0] == "f"
This works in python 2.x:
def is_string(s):
try:
if (s[0] == s[0][0]):
return True
except:
pass
return False
A: The simplest one is if type(f) == str
Sometimes it's better to use if's than exceptions.
EDIT:
Due to larsmans comment, I don't recommend this option. It is useful in simple usage, but in professional coding it is better to use isinstance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fetch JSON from a URL using JavaScript? I am using following code in one of my HTML files
var queryURL = encodeURI(yahooUrl + loc + appId);
alert(queryURL);
$.getJSON(queryURL, function(data){
alert('inside getJSON')
alert(data);
var items = [];
$.each(data, function(key, value){
items.push('<li id="' + key + '">' + value + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});`
where queryURL is one big query which if I load from the browser's address bar I get a file containing a JSON object. But the following code is not working, the whole JSON object is being displayed at the error console of Firefox, with the error 'Invalid Label'. I have added &callback=? at the end of the query string as mentioned in few of the answers here at SO.
Can any one suggest what I am doing wrong ?
Edit: for
queryURL = "http://where.yahooapis.com/geocode?location=107,South%20Market,San%20Jose,San%20Fransico,Leusina,USA,&flags=J&appid=dj0yJmk9SUk0NkdORm9qM2FyJmQ9WVdrOU1tVnFUVzlVTm5NbWNHbzlORFl4TnpZME5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PWE1&callback=?"
I get the following error:
Error: invalid label
Source File: http://where.yahooapis.com/geocode?location=107,South%20Market,San%20Jose,San%20Fransico,Leusina,USA,&flags=J&appid=dj0yJmk9SUk0NkdORm9qM2FyJmQ9WVdrOU1tVnFUVzlVTm5NbWNHbzlORFl4TnpZME5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PWE1&callback=jQuery16404719878257064011_1316606312366&_=1316608283354
Line: 1, Column: 1
Source Code:
{"ResultSet":{"version":"1.0","Error":0,"ErrorMessage":"No error","Locale":"us_US","Quality":87,"Found":1,"Results":[{"quality":39,"latitude":"37.336849","longitude":"-121.847710","offsetlat":"37.338470","offsetlon":"-121.885788","radius":34800,"name":"","line1":"","line2":"San Jose, CA","line3":"","line4":"United States","house":"","street":"","xstreet":"","unittype":"","unit":"","postal":"","neighborhood":"","city":"San Jose","county":"Santa Clara County","state":"California","country":"United States","countrycode":"US","statecode":"CA","countycode":"","uzip":"","hash":"","woeid":2488042,"woetype":7}]}}
A: This may be caused because jQuery automatically switches to using JSONP (because it's a cross-domain-request) and Yahoo apparently doesn't use JSONP but regular JSON. Have you tried good old $.ajax() with dataType:"JSON"?
Using $.ajax:
$.ajax({
url: queryURL,
dataType: "JSON",
success: function(data){
alert('inside getJSON')
alert(data);
var items = [];
$.each(data, function(key, value){
items.push('<li id="' + key + '">' + value + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
Let me be exceptionally nice here since I'm having a horrible day: Working example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: WCF Rest With Jquery Ajax and .Net Application consultation I need your help and consultation in a problem that i have faced based on some wrong architecture application design.
The case: im working in web application built on asp.NET 4.0 to a client and im almost have done 85% out of this project, the project architecture as the following:
*
*Front End Server: Web Application, Ajax JQuery Calling WCF Rest Service.
*Application Server: Host the WCF Rest Service and the DAL components.
*SQL Server: host the database it self
My problem i think is with the CROSS-DOMAIN issue, and my client ensure that the solution should be deployed on the 3 servers, as u know i have already stucked with solution and i need to find an exit to my problem. all the 3 servers are hosted at the same DOMAIN but with different ip address, i tried to go with JSONP approach but it seems have some limitations and drawbacks such as no error handling which is one my client requirement (is it possible to make POST, PUT operations using JSONP ?), also i tried to maintain the server response headers but i think its not going to work with all browsers such as IE 9, Chrome ..
This problem really puts me in a very embarrassing situation and i need your professional and consultation help, some people suggested that i create another WCF rest hosted in the frontend and it calls the other service but i think it will make the performance very slow.
Cheers.
A: I have been battling this issue too, and have not found a perfect answer yet. Here are some things that will at least get you further down the road.
One option is to configure your webHttp behavior so that it doesn't include the faultExceptionEnabled="true" attribute. This way, jQuery won't hit the error handler, but the success handler. The WebFaultException should still populate the data parameter in the success handler with JSON. The drawback to this approach is that I haven't found a way to wrap the fault exception so I can easily check if an error actually occurred in that success handler. All I get in the JSON are the properties of the fault.
The next option is just to drop the web front end into a different virtual directory on the same web site as the WCF service. There shouldn't be any cross-domain issues with this approach. Not always an ideal solution, but it works.
I had issues locally as well if I use the Cassini web server or IIS Express. I think the browser interprets requests to web sites on different ports as a cross-domain request. The only way I could work locally with any success is if I installed IIS on my dev box and hosted both the service and the front end on the default web site.
If anybody has figured out a better way, please share. It's enough to drive a guy bonkers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Save Dragable sitemap with jquery to database I have a question, I found a great script that I want to use for my website but I don't know how to save it to my database, the link here, could someone point me to the right direction?
Thanks
Take a look at the demo. I want to be able to sort the list and then save it to my database.
There is a function history but I just can't figure it out
`var sitemapHistory = {
stack: new Array(),
temp: null,
//takes an element and saves it's position in the sitemap.
//note: doesn't commit the save until commit() is called!
//this is because we might decide to cancel the move
saveState: function(item) {
sitemapHistory.temp = { item: $(item), itemParent: $(item).parent(), itemAfter:
$(item).prev() };
},
commit: function() {
if (sitemapHistory.temp != null) sitemapHistory.stack.push(sitemapHistory.temp);
},
//restores the state of the last moved item.
restoreState: function() {
var h = sitemapHistory.stack.pop();
if (h == null) return;
if (h.itemAfter.length > 0) {
h.itemAfter.after(h.item);
}
else {
h.itemParent.prepend(h.item);
}
//checks the classes on the lists
$('#sitemap li.sm2_liOpen').not(':has(li)').removeClass('sm2_liOpen');
$('#sitemap li:has(ul li):not(.sm2_liClosed)').addClass('sm2_liOpen');
}
}
`
A: First you need to create a sitemap in HTML yourself. It has to look like the example on the page: <ul id=”sitemap”> <li> <dl> <dt><a href=”#”>expand/collapse</a> ...
Then you include the script from the page and run it.
Not sure what all this has to do with your database.
A: A possible solution would be to add a linkID and a parentID to each line element. Then when you save the changes, make the updates to your table on the back end. That would cover the parent / child relationships. As for the sorting order, I'm still thinking about that.
A valuable resource is the jQuery Sortable document : http://jqueryui.com/demos/sortable/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange margin/padding in Firefox that doesn't occur in other browsers We've been working on a new website and there is some mystery padding/margin occurring just in Firefox 6 that doesn't appear in any other browser (including IE).
What it should look like:
What Firefox displays:
The additional margin/padding is appearing just above the Blackboard + Portal buttons.
Playing with Firebug it's something to do with the float:left on ul.springboard li.
Can anyone point me in the right direction?
Thank you
A: I tried removing the clearfix class and adding the following rules to ul.springboard:
display: inline-block;
width: 100%;
That removed the space in Firefox, but I'm not sure how it will impact other ul elements that use .springboard class.
A: I think your problem is that you don't actually have styles set up for .clearfix yet. The following CSS additions should sort you out.
/* Micro-clearfix, via goo.gl/QjJD9 */
.clearfix:before, .clearfix:after { content:""; display:table; }
.clearfix:after { clear:both; }
/* For IE 6/7 (trigger hasLayout) */
.clearfix { zoom:1; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TabItem headers: Content doesn't stretch if the actual tab header does I have a TabControl and am attempting to get the headers to look nice. I have the following XAML:
(In Resources.xaml:)
<DataTemplate x:Key="ClosableTabItemTemplate">
<DockPanel LastChildFill="True" MinWidth="200" Height="20" HorizontalAlignment="Stretch" behaviors:MouseClickBehavior.ClickCommand="{Binding Path=CloseCommand}">
<Image Source="{Binding Path=Image}" Height="16" VerticalAlignment="Center" />
<Button Background="Transparent"
BorderBrush="Transparent"
Command="{Binding Path=CloseCommand}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontSize="9"
FontWeight="Bold"
Margin="3,0,0,0"
Padding="0"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Width="16" Height="16" />
<TextBlock Text="{Binding Path=Header}" DockPanel.Dock="Left" VerticalAlignment="Center" />
</DockPanel>
</DataTemplate>
(In MainWindow.xaml:)
<TabControl Grid.Column="1"
ItemsSource="{Binding Path=Tabs}"
ItemTemplate="{DynamicResource ClosableTabItemTemplate}" />
Here is a visual example of my problem:
I like the actual width of the tabs for now, but the fact that my dockpanel for the header isn't filling up all the space is bothersome. Same thing happens if I use a Grid, too (presumably any container control).
A: ContentPresenter.HorizontalAlignment in the default style for TabItem is bound to ItemsControl.HorizontalContentAlignment. Here it is, taken from Aero.NormalColor.xaml:
<ContentPresenter Name="Content"
ContentSource="Header"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
HorizontalAlignment="{Binding Path=HorizontalContentAlignment,RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
VerticalAlignment="{Binding Path=VerticalContentAlignment,RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
RecognizesAccessKey="True"/>
Setting TabControl.HorizontalContentAlignment to Stretch fixes the issue for me.
<TabControl HorizontalContentAlignment="Stretch" />
A: I ran into the same visual issue with closable tabs and resolved it by extending both the TabControl (to be used later in XAML) and TabItem classes. I overrode GetContainerForItemOverride() in the former, and OnApplyTemplate() in the latter. I created a DependencyObject extension method to find the ContentPresenter element of the TabItem and set its HorizontalAlignment property to HorizontalAlignment.Stretch:
public class MyTabControl : TabControl
{
protected override DependencyObject GetContainerForItemOverride()
{
return new MyTabItem();
}
}
public class MyTabItem : TabItem
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var content = this.GetFirstDescendantOfType<ContentPresenter>();
if (content != null)
{
content.HorizontalAlignment = HorizontalAlignment.Stretch;
}
}
}
public static class DependencyObjectExtensions
{
public static T GetFirstDescendantOfType<T>(this DependencyObject parent) where T : DependencyObject
{
if (parent == null)
{
return null;
}
else
{
var children = parent.GetChildren();
T descendant = children.FirstOrDefault(child => child is T) as T;
if (descendant == null)
{
foreach (var child in children)
{
if ((descendant = child.GetFirstDescendantOfType<T>()) != null) break;
}
}
return descendant;
}
}
public static IEnumerable<DependencyObject> GetChildren(this DependencyObject parent)
{
var children = new List<DependencyObject>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
children.Add(VisualTreeHelper.GetChild(parent, i));
}
return children;
}
}
My XAML appears as the following:
(In MainWindowResources.xaml):
<DataTemplate x:Key="ClosableTabItemTemplate">
<DockPanel>
<Button Command="{Binding Path=CloseCommand}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontFamily="Courier"
FontSize="9"
FontWeight="Bold"
Margin="8,1,0,0"
Padding="0"
VerticalContentAlignment="Bottom"
Width="16"
Height="16"
ToolTip="Close" />
<TextBlock Text="{Binding Path=DisplayName}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</DockPanel>
</DataTemplate>
(In MainWindow.xaml): Note the use of the custom MyTabControl control
<MyTabControl IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=ClosableViewModels}"
ItemTemplate="{StaticResource ClosableTabItemTemplate}"
Margin="4" />
A: Try overwritting the ItemContainerStyle.Template instead of the ContentTemplate
I did something like this in the past, although I overwrote the entire TabControl template so it's a bit hard to see what I was doing. My code looked like this:
<ControlTemplate x:Key="CurvedTabItemTemplate" TargetType="{x:Type TabItem}">
<DockPanel Width="200">
<ContentPresenter x:Name="ContentSite" ContentSource="Header" RecognizesAccessKey="True" />
</DockPanel>
</ControlTemplate>
<Style x:Key="CurvedTabItemStyle" TargetType="{x:Type TabItem}">
<Setter Property="Template" Value="{StaticResource CurvedTabItemTemplate}" />
</Style>
<TabControl Grid.Column="1" ItemsSource="{Binding Path=Tabs}"
ContentTemplate="{DynamicResource ClosableTabItemTemplate}"
ItemContainerStyle="{DynamicResource CurvedTabItemStyle}" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Other Android Developer Tools The Android SDK comes with many tools to help you develop application, I am wonder what else is out there.
One tool that I have found is coloredlogcat - http://jsharkey.org/blog/2009/04/22/modifying-the-android-logcat-stream-for-full-color-debugging/
A: The Android Asset Studio is great for building icon images. Very handy.
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
A: You have a couple of more webbased tools I know of like:
DroidDraw which helps you creating layouts
RadDroid which helps you with the initial set-up of your project.
This website also features some of the best Android developer tools:
http://www.web3mantra.com/2011/05/05/best-android-developer-tools-and-resources/
A: The Android Icon Maker can also be very useful, him create a set of the icons for Android Applications from a specific icon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Objective-C - Converting NSString to a C string
Possible Duplicate:
objc warning: “discard qualifiers from pointer target type”
I'm having a bit of trouble converting an NSString to a C string.
const char *input_image = [[[NSBundle mainBundle] pathForResource:@"iphone" ofType:@"png"] UTF8String];
const char *output_image = [[[NSBundle mainBundle] pathForResource:@"iphone_resized" ofType:@"png"] UTF8String];
const char *argv[] = { "convert", input_image, "-resize", "100x100", output_image, NULL };
// ConvertImageCommand(ImageInfo *, int, char **, char **, MagickExceptionInfo *);
// I get a warning: Passing argument 3 'ConvertImageCommand' from incompatible pointer type.
ConvertImageCommand(AcquireImageInfo(), 2, argv, NULL, AcquireExceptionInfo());
Also when I debug argv it doesn't seem right. I see values like:
argv[0] contains 99 'c' // Shouldn't this be "convert"?
argv[1] contains 0 '\100' // and shouldn't this be the "input_image" string?
A: Richard is correct, here is an example using strdup to suppress the warnings.
char *input_image = strdup([@"input" UTF8String]);
char *output_image = strdup([@"output" UTF8String]);
char *argv[] = { "convert", input_image, "-resize", "100x100", output_image, NULL };
ConvertImageCommand(AcquireImageInfo(), 2, argv, NULL, AcquireExceptionInfo());
free(input_image);
free(output_image);
A: The warning is because you are passing a char const ** (pointer-to-pointer-to-const-char) where the API expects a char ** (pointer-to-pointer-to-char, in particular a NULL-terminated list of non-const C strings).
My point being the const makes the pointer types incompatible. The safe way to get around that is to copy the UTF8 strings into non-const C-string buffers; the unsafe way is to cast.
A: Use cStringUsingEncoding or getCString:maxLength:encoding:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Start Three20 Photo Viewer in Thumbnail view? I followed How To Use the Three20 Photo Viewer by Ray Wenderlich tutorial it was very clear and working perfectly, my question as the title, How to Start Three20 Photo Viewer in Thumbnail view?
I am greatly appreciative of any guidance or help.
A: You should use TTThumbsViewController instead of TTPhotoViewController. There's a good example of it in three20 TTCategory sample app.
TTThumbsViewController also uses a photo source, so you won't have to change that much code. Your Photo viewer should extend TTThumbsViewController and implement the TTThumbsViewControllerDelegate delegate functions.
You can load the photo source in your viewDidLoad function:
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
NSMutableArray* photos = [NSMutableArray array];
for (int i=kImagesCount;i>=1;i--) {
Photo* photo = [[[Photo alloc] initWithURL:[NSString stringWithFormat:@"bundle://%d.png", i]
smallURL:[NSString stringWithFormat:@"bundle://%dt.png", i]
size:CGSizeMake(400, 400)] autorelease];
[photos addObject:photo];
}
self.photoSource = [[PhotoSource alloc]
initWithType:PhotoSourceNormal
title:@"Select Picture"
photos:photos
photos2:nil];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to play the audio files directly from res/raw folder? I have multiple audio files in res/raw folder. I showing ListView that contains audio files name. I want to play the corresponding audio file when user select into the ListView. I have used setDataSource(path), but it showing error while playing. How play the audio files directly from that folder? Or Is there any other way?
A: mVideoView = (VideoView) findViewById(R.id.Video_FrontPage);
uri = Uri.parse("android.resource://com.urPackageName/" + R.raw.welcom_video);
mVideoView.setVideoURI(uri);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
mVideoView.start();
A: add this code in onItemClickListener.
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
TextView txtView=(TextView)view.findViewById(R.id.txt_view);
String fname=txtView.getText().toString().toLowerCase();
int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();
}
});
A: lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
int [] resID= {R.raw.sound1,R.raw.sound2,R.raw.sound3};
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID[position]);
mediaPlayer.start();
// sending data to new activity
}
});
}
A: try this for playing from raw ::
MediaPlayer mPlayer2;
mPlayer2= MediaPlayer.create(this, R.raw.bg_music_wav);
mPlayer2.start();
permission in manifest file ::
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Update::
public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
MediaPlayer mPlayer2;
if(position==1)
{
mPlayer2= MediaPlayer.create(this, R.raw.song1);
mPlayer2.start();
}else it() .....
}
A: var mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1)
mediaPlayer.start() // no need to call prepare(); create() does that for you
A: Place your audio file in the res/raw folder and call it from the create method of MediaPlayer.
MediaPlayer.create(this, R.raw.audio_file_name).start();
Eg:
MediaPlayer.create(this, R.raw.sample).start();
A: To play audio from the raw folder call this method. In my case my file name was notificaion.mp3:
AudioPlayer().playAudio(mContext, "notificaion")
Here is the AudioPlayer class:
class AudioPlayer {
private var mMediaPlayer: MediaPlayer = MediaPlayer()
private fun stopAudio() {
try {
mMediaPlayer.release()
}catch (ex: Exception){
ex.printStackTrace()
}
}
fun playAudio(mContext: Context, fileName: String) {
try {
stopAudio()
mMediaPlayer = MediaPlayer.create(mContext, mContext.resources.getIdentifier(fileName, "raw", mContext.packageName))
mMediaPlayer.setOnCompletionListener { stopAudio() }
mMediaPlayer.start()
}catch (ex: Exception){
ex.printStackTrace()
}
}
}
A: listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
TextView txtView=(TextView)view.findViewById(R.id.txt_view);
String fname=txtView.getText().toString().toLowerCase();
int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();
}
});
add this code in onItemClickListener and one more information is you can't play any file other than mp3 and the mp3 file must be the original extension as file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: how 'Accept-Language' header is passed in http in iphone? How 'Accept-Language' header is passed in http request in iphone?
In my http request, the header is empty. Is this appended at the framework level ?
If so, Is there a way to intercept it and make modifications?
A: +(NSMutableURLRequest*)assembleHTTPRequestHead:(NSMutableURLRequest *) requester
{
// These are the headers we need, we get ride of everything else
NSArray *headers = [NSArray arrayWithObjects:@"User-Agent", nil];
NSString* appName = [self getAppName];
NSArray *values = [NSArray arrayWithObjects: appName, nil];
// Add our headers
for (NSString *header in headers) {
// We use setValue to overwrite any value in an existing
// header, addValue appends to the values.
id theValue =[values objectAtIndex:[headers indexOfObject:header]];
[requester setValue:theValue forHTTPHeaderField:header ];
AppTrace3(self, @"Added Header", header, theValue);
}
AppTrace2(self, @"assembleHTTPRequestHead done", requester);
return requester;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: @Transactional annotation causing incompatible return types error on entity I have a Restful web service developed in Spring MVC which currently returns farmer information and allows for the deletion and addition of new farmers to the database. When extending the web service to include farmer advisors I am recieving the following error as soon as I add the transactional annotation to the advisor DAO implementation:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'advisorDAO' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: methods with same signature getAdvisors() but incompatible return types: [interface java.util.List, class [Lorg.springframework.aop.Advisor;]
The odd part about this error is that the system compiles fine and as intended prior to the annotation being added to the class, however as I need to be able to persist the entity to the database the transactions are a requirement. I know what the error means but I am at a loss as to why this is only an issue when using the annotation which isn't even applied to the method the compiler is complaining about.
The Advisors DAO interface:
public interface AdvisorDAO {
public List<Advisor> getAdvisors();
public Advisor getAdvisorByPk(int id);
public Advisor getAdvisorByFarmerID(int id);
public Advisor getAdvisorByAdvisorID(int id);
public void saveAdvisor(Advisor advisor);
public void deleteAdvisor(Advisor advisor);
public void updateAdvisor (Advisor advisor);
}
The interface implementation:
public class JpaAdvisorDAO implements AdvisorDAO {
@PersistenceContext
private EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public List<Advisor> getAdvisors() {
return entityManager.createNamedQuery("Advisor.findAll").getResultList();
}
@Override
public Advisor getAdvisorByPk(int id) {
Query query = entityManager.createNamedQuery("Advisor.findByPK");
query.setParameter("advisorPk", id);
return (Advisor) query.getSingleResult();
}
@Override
public Advisor getAdvisorByFarmerID(int id) {
Query query = entityManager.createNamedQuery("Advisor.findByFarmerId");
query.setParameter("farmerId", id);
return (Advisor) query.getSingleResult();
}
@Override
public Advisor getAdvisorByAdvisorID(int id) {
Query query = entityManager.createNamedQuery("Advisor.findByAdvisorId");
query.setParameter("advisorId", id);
return (Advisor) query.getSingleResult();
}
@Override
@Transactional
public void saveAdvisor(Advisor advisor) {
entityManager.persist(advisor);
}
@Override
@Transactional
public void deleteAdvisor(Advisor advisor) {
entityManager.remove(entityManager.getReference(Advisor.class, advisor.getAdvisorPk()));
}
@Override
@Transactional
public void updateAdvisor (Advisor advisor) {
entityManager.merge(advisor);
}
The context file used:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc">
<bean id="farmerDAO" class="com.test.cmsservice.persistance.JpaFarmerDAO" />
<bean id="advisorDAO" class="com.test.cmsservice.persistance.JpaAdvisorDAO" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringRestService"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/>
</bean>
</property>
</bean>
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/SpringDBTest"/>
<property name="username" value="APP"/>
<property name="password" value="app"/>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
A: Adding the annotation can't change the return type.
First, you have probably imported the wrong type - Advisor is a spring class as well, so fix your imports.
Then I suspect that you have an older version of your interface or its implementation that is loaded by the classloader. The exception message says that one of the methods returns a List<Advisor> and the other - Advisor[]. Make sure everything is cleaned and up-to-date.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Upgrade My database in app up gradation process? I am developing an app where i have to update my data base when user selects app upgrade process. Simply i want to do a database changes when my app is migrated to new version.
How to do this job please suggest.
AND
I am developing an app to which already have some versions in market now i want to release an update to my app but i haven't got any info how to do it. Is it like a normal apk file creation?? if it is then do i need to use any adb commands to test this apk file?? Please Suggest..!!!
Thanks,
Ram.
A: Please see this doc for information on SQLiteOpenHelper. It provides the functionality for you to do updates, and onCreates (when db is created).
The way the onUpgrade method should work is that you pass it the db, the old version number, and the new version number, so you can do comparisons of that. You would do something like this:
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer)
{
if (oldVer == 1 && newVer == 2)
{
db.exec("ALTER TABLE tbl_names RENAME TO names");
//.....
}
}
The version number is generally stored as a class level variable somewhere either in your SQLiteOpenHelper or your main database helper.
This will require a restart of your application. If you are referring to the ability of a user to do an in-app upgrade then this might not work for you.
A: If you are using SQLiteOpenHelper (which you should), just override the onUpgrade method. Then, every time your database structure changes, you up the version number of the database. Read this topic on data storage form the dev guide. Also, look at the NotePad sample which implements this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: while parse the xml, not full data is getting after some word line end with read more I'm trying to parse this:
I get the following, when I parse.
title = Workshop Metropolis
description = Workshop Metropolis groot succes Vlak voor de...Read more
Read more is not any text on Description, which tag of xml you may see on above ?
I don't understand why it is coming.
Here's the code:
///********************** XMLParsingExample.java **********************//
public class XMLParsingExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
// /** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://192.168.0.30/ibis.rss");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
for (int i = 0; i < sitesList.getLat().size(); i++) {
System.out.println("title = "+ sitesList.getLat().get(i).toString());
System.out.println("description = "+ sitesList.getLong().get(i).toString());
}
}
}
////MyXMLHandler
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("channel"))
{
/** Start */
sitesList = new SitesList();
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("title"))
sitesList.setLat(currentValue);
else if (localName.equalsIgnoreCase("description"))
sitesList.setLong(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
//currentValue = StringEscapeUtils.unescapeHtml4(new String(ch, start, length).trim()); //new String(ch, start, length).trim()
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
public class SitesList {
/** Variables */
private ArrayList<String> mlat = new ArrayList<String>();
private ArrayList<String> mlong = new ArrayList<String>();
private ArrayList<String> mradiuslat = new ArrayList<String>();
private ArrayList<String> mradiuslong = new ArrayList<String>();
private ArrayList<String> minfo = new ArrayList<String>();
private ArrayList<String> msound = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getLat() {
return mlat;
}
public void setLat(String lat) {
this.mlat.add(lat);
}
public ArrayList<String> getLong() {
return mlong;
}
public void setLong(String longs) {
this.mlong.add(longs);
}
}
A: first make pojo class(getter setter method for your all tag)
for parsing [CData] take a sax parser. put your link.
public class XMlStorePrasing extends DefaultHandler{
public ArrayList<StoreLocator> Locator = new ArrayList<StoreLocator>();
private StoreLocator wrapper ;
private String record = "";
private Context context;
public static Map<String, String> QAns = new LinkedHashMap<String, String>();
public ArrayList<StoreLocator> parseData(Context context)
{
try {
try
{
this.context = context;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
URL url = new URL("your link");
sp.parse(url.openStream(), this);
}
catch (UnknownHostException e) {
e.printStackTrace();
}
} catch (Exception e ) {
e.printStackTrace();
}
return Locator;
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
record = "";
if(localName.equalsIgnoreCase("Record"))
{
wrapper = new StoreLocator();
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(localName.equalsIgnoreCase("store"))
{
wrapper.setStore(record);
}
else if(localName.equalsIgnoreCase("latitude"))
{
wrapper.setLatitude(record);
}
else if(localName.equalsIgnoreCase("longitude"))
{
wrapper.setLongitude(record);
}
else if(localName.equalsIgnoreCase("distance"))
{
// wrapper.setAnswerOptions(record);
wrapper.setDistance(record);
}
else if(localName.equalsIgnoreCase("address"))
{
wrapper.setAddress(record);
}
else if(localName.equalsIgnoreCase("city"))
{
// wrapper.setAnswerOptions(record);
wrapper.setCity(record);
}
else if(localName.equalsIgnoreCase("state"))
{
wrapper.setState(record);
}
else if(localName.equalsIgnoreCase("zip"))
{
wrapper.setZip(record);
}
else if(localName.equalsIgnoreCase("Record"))
{
Locator.add(wrapper);
}
}
@Override
public void characters(char[] ch, int start, int length)throws SAXException {
record += String.valueOf(ch,start,length);
}
from calling this:
ArrayList<StoreLocator> ss = new ArrayList<StoreLocator>();
XMlStorePrasing prasing = new XMlStorePrasing();
ss = prasing.parseData(getApplicationContext());
I think this will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ObjectiveC: NSScanner scanDouble problem In my iPhone app I am trying to understand if a string is a valid number or not, the code below works most of the time but when I have a value starting with number and ends with text it wrongly returns "true" e.g "34rty"
if([[NSScanner scannerWithString:value] scanDouble:NULL] ){
val=[NSNumber numberWithDouble:[value doubleValue]];
}
what is wrong here?
A: scanDouble return via a reference.
NSString *string = @"34rty";
NSScanner *scanner = [NSScanner scannerWithString:string];
double doubleValue;
[scanner scanDouble:&doubleValue];
NSNumber *doubleNumber = [NSNumber numberWithDouble:doubleValue];
NSLog(@"doubleValue: %f", doubleValue);
NSLog(@"doubleNumber: %@", doubleNumber);
NSLog output:
doubleValue: 34.000000
doubleNumber: 34
You will have to scan up to the number if there is preceding text.
As @Benjamin says, a RegEx may be a better option for just checking.
A: NSScanner stops at the first matching character. So it finds '3', returns positive as it did scan a double, and then stops running. It doesn't check every character.
A REGEX check is a better choice for this purpose.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I run XPATH queries in Immediate window? Is it possible to run XPATH queries on an active window which is an XML from the Immediate window?
(In my case, I would like to do it to see if I am selecting the correct nodes; but anyway, is it possible and how? Example?)
A: I would do it in Firefox. Install XPath addon and open the xml on firefox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a reusable Dialog for getting a class name in Pharo? I need something better than writing the entire class name in a text field. Maybe a reduced view of the System Browser.
I've searched class names with 'Dialog' and 'Window' but i couldn't find it.
A: A while ago I've implemented a pluggable completion dialog for OmniBrowser. This is the blog post describing it for end-users:
OmniBrowser Completion Dialog
The model is implemented in OBCompletionRequest and the morphic view in OBCompletionDialog. While the code currently depends on the OmniBrowser infrastructure, it should be relatively easy to extract. There are no difficult dependencies.
The model is fully pluggable, so the dialog works with any collection of entities. Furthermore, the dialog scales well to huge lists: displaying and filtering all system classes or all system selectors is no big deal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Use C2DM in Android-x86 I use Android-x86 installed in virtual box and communicating with adb to debug my android application.
I know that since it is an open source project, it is not possible to use google API libraries.
But I know that using Maps is possible (somepeople did it), do you know any way to instal cd2m libraries to be able to test push in my emulator ?
Thxs
A: Correct me if I'm wrong, but I believe the C2DM framework is dependent in the android market. If your device doesn't contain the android market, it will be difficult to receive the C2DM stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: mysql searching, condition from another table I have two tables. products and productgroups.
I use
"SELECT * FROM `product` `t`
WHERE (name LIKE '%test%' OR ean LIKE '%test%')
AND closed=0 "
To search in products. Now I have another table called productgroups. Every product has its own productgroup_id. I need to show only those products that have their productgroup_id.closed=0.
If productgroup.closed = 1 it shouldn't display it.
How do I do this?
A: SELECT p.* FROM product p
INNER JOIN productgroup pg ON (pg.id = p.productgroup_id)
WHERE (p.name LIKE '%test%' OR p.ean LIKE '%test%')
AND p.closed=0
AND pg.closed=0
A: Maybe I've missed the complexity in the problem, but...
SELECT * FROM
products INNER JOIN
productgroups ON product.productGroup_id = productgroups.Id
WHERE
(products.name LIKE '%test%' OR products.ean LIKE '%test%') AND products.closed=0 and productgroups.closed = 0
should do the trick
A: just use an inner join:
SELECT
*
FROM
product t
INNER JOIN
productgroups g ON t.productgroup_id = g.id
WHERE
(t.name LIKE '%test%' OR t.ean LIKE '%test%')
AND
g.closed = 0
A: SELECT * FROM product t
INNER JOIN productgroup pg ON t.productgroup_id = pg.id
WHERE (t.name LIKE '%test%' OR t.ean LIKE '%test%') AND t.closed=0 AND pg.Closed = 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add click event for many buttons JQuery? I have buttons that has ids like that:
id='button0'
id='button1'
id='button2'
id='button3'
id='button4'
...
I want to add click event for all of them. How can I do it with most performance?
A: simple
you should use class instead !!!
<span class="MySpan"> ...
<span class="MySpan"> ...
<span class="MySpan"> ...
$(".MySpan").click (....
A: Starts with (^=)
Something like $("button[id^='button']")
Performance wise - not sure what the impact of ^= would be though.
ref: http://api.jquery.com/attribute-starts-with-selector/
A: $("*[id^='button']").click(
function() {
}
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set div height in steps to fit tiled background I need to control a div's height to always appear in steps of 20. I have a repeating div background that is 20 pixels high and I want the div to always end in a correct way. I found what I think is the solution here:
Set height of an element on multiples of a number?
But when I try it doesn't work. I'm a newbie at jquery and probably made a simple mistake.
In the following test html code I'm expecting the div's height to always appear in steps of 100px, but it doesn't work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://`enter code here`www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test jquery</title>
<script type="text/javascript" src="jquery.js"></script>
<script language=”javascript”>
$(document).ready(function(){
$('#testCol').height(function(i, h) { return Math.ceil(h / 100) * 100; });
});
</script>
<style type="text/css">
#testCol {
width: 150px;
background-color:#FFCC00;
}
</style>
</head>
<body>
<div id="testCol">df ds d sfdhs fdsf ds fhsdu ds iuhsdi fsdf dhsf sdiuh isdf iusd fiushd fiuds i uhsdiu isudf iusd fiusdh fiusd fih wtwpr wer rew</div>
</body>
</html>
A: Remove the language=”javascript” from the script tag. That's prevening the browser running the script. You don't need this directive but if you want to use it, it should be:
<script type="text/javascript">
A: Some neat maths for this is as follows, just set the roundTo variable to the number you wish to round to.
var height = parseInt($jQueryObj.height(), 10),
roundTo = 20;
if (height && (height % roundTo !== 0))
{
height = roundTo * Math.round(height / roundTo);
}
I have setup a demo fiddleof this in action here: http://jsfiddle.net/i_like_robots/uBcHh/
You may face issues with padding too so remember to add or subtract as necessary. You should probably set minHeight rather than height for safety. I would genuinely ask yourself or whoever asked for this feature if it is really necessary.
A: To set the div's height in steps of 20px, I changed the values to the following:
<script type="text/javascript">
$(document).ready(function(){
$('#testCol').height(function(i, h) { return Math.ceil(h / 20) * 20; });
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem in R with xml parse output on the Window XP – breaking national symbol I am interesting use R for data mining in the media research.
When I am pars xml (scraping Google RSS) national symbol (Cyrillic) is breaking:
>xml <- xmlTreeParse(url, useInternalNodes = T)
>xml
<? xml version="1.0" encoding="UTF‑8"?>
<rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>югра OR ханты OR хмао – Новости Google</title>
…
My system is:
sessionInfo()
R version 2.13.1 (2011-07-08)
Platform: i386-pc‑mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=Russian_Russia.1251 LC_CTYPE=Russian_Russia.1251
[3] LC_MONETARY=Russian_Russia.1251 LC_NUMERIC=C
[5] LC_TIME=Russian_Russia.1251
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] XML_3.4-2.2 RCurl_1.6-10.1 bitops_1.0-4.1
loaded via a namespace (and not attached):
[1] tools_2.13.1
I am try used any custom options (localeToCharset(locale="ru_RU.UTF-8")) – without effect.
I've been running the parsing on the Linux (Lubuntu 11.04) – no problem, national symbol output correct.
Sorry for my English.
Any idea?
Thanks.
A: Ok, the following worked for me, not sure if that is the case:
url.tmp <- "http://news.google.ru/news?hl=ru&gl=ru&q="
symbol <- "быть OR жить"
number <- 10
url <- paste(url.tmp, symbol, "&output=rss", "&start=", 1, "&num=", number, sep = "")
url <- URLencode(url)
Basically, I've removed the enc2utf8 from your example.
> xml <- xmlTreeParse(url, useInternalNodes = T, isURL=T)
> xml
Output:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>быть OR жить – Новости Google</title>
<link>http://news.google.ru/news?gl=ru&pz=1&ned=ru_ru&hl=ru&num=10&q=%D0%B1%D1%8B%D1%82%D1%8C+OR+%D0%B6%D0%B8%D1%82%D1%8C</link>
<language>ru</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>&copy;2011 Google</copyright>
<pubDate>Wed, 21 Sep 2011 13:49:52 GMT+00:00</pubDate>
<lastBuildDate>Wed, 21 Sep 2011 13:49:52 GMT+00:00</lastBuildDate>
<image>
<title>быть OR жить – Новости Google</title>
<url>http://www.gstatic.com/news/img/logo/ru_ru/news.gif</url>
<link>http://news.google.ru/news?gl=ru&pz=1&ned=ru_ru&hl=ru&num=10&q=%D0%B1%D1%8B%D1%82%D1%8C+OR+%D0%B6%D0%B8%D1%82%D1%8C</link>
</image>
<item>
<title>Взяточникам будут давать до 50 лет тюрьмы - Дни.Ру</title>
<link>http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGE1RZXvfqoSBuDU3EqSPeqJDRqDw&url=http://www.dni.ru/redir/?source%3Ddni_picture_day%26id%3D219166%26dniurl%3Dpolit/2011/9/21/219166.html</link>
<guid isPermaLink="false">tag:news.google.com,2005:cluster=http://www.dni.ru/redir/?source=dni_picture_day&id=219166&dniurl=polit/2011/9/21/219166.html</guid>
<pubDate>Wed, 21 Sep 2011 12:54:00 GMT+00:00</pubDate>
I'm running R via the StatET plugin for Eclipse.
> sessionInfo()
R version 2.13.1 (2011-07-08)
Platform: x86_64-pc-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=Russian_Russia.1251 LC_CTYPE=Russian_Russia.1251 LC_MONETARY=Russian_Russia.1251 LC_NUMERIC=C LC_TIME=Russian_Russia.1251
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] XML_3.4-2.2 quantmod_0.3-15 TTR_0.20-2 Defaults_1.1-1 xts_0.8-0 zoo_1.7-2 rj_0.5.5-4
loaded via a namespace (and not attached):
[1] grid_2.13.1 lattice_0.19-30 tools_2.13.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fatal Error AFTER text change listener executed SOLVED
I have an app that searches through an arraylist whenever the search string is updated in an EditText.
I have a text change listener added to the EditText. It usually works but randomly I've been getting a Fatal error with no reference to a line number in my app (I'm Using Eclipse Logcat)
I've put log outputs in my code to find the last line that is executed. Unexpectedly this turned out to be AFTER the text change listener had executed all it's code, and presumably after the thread had been handed back to the UI?
I'd be grateful of any help.
Here's the full code in my text Listener. I'm getting the log output saying it Finished this function though. So where does the thread go after this?
public void afterTextChanged(Editable s) {
if (("" + inputField.getText()).length() > 0) {
fullSearchString += ("" + inputField.getText()).trim();
inputField.setText("");
searchArray(fullSearchString);
out("FINISHED Text change Listener");
}
}
Here's the stack trace
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): FATAL EXCEPTION: main
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at java.util.ArrayList.get(ArrayList.java:311)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.widget.TextView.sendAfterTextChanged(TextView.java:6194)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:6377)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.sendTextHasChanged(SpannableStringBuilder.java:897)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:353)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.os.Handler.dispatchMessage(Handler.java:99)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.os.Looper.loop(Looper.java:123)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at java.lang.reflect.Method.invokeNative(Native Method)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at java.lang.reflect.Method.invoke(Method.java:521)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): at dalvik.system.NativeStart.main(Native Method)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regrading rank in Binomial queue I am reading about Binomial queue operations here.
At bottom of link it is mentioned as
Implementation of a Binomial Queue
*
*deletemin operation requires ability to find all subtrees of the root. Thus children of each node should be available (say a linked list)
*deletemin requires that the children be ordered by the size of their subtrees.
*we need to make sure it is easy to merge tress. Two binomial trees can be merged only if they have the same size, hence the size of the tree must be stored in the root. While merging, one of the trees becomes the last child of the other, so we should keep track of the last child of each node. A good data structure to use is a circular doubly
linked list what each node is of the following form:
data | first |left | right |rank No. of |
--------------------------------------------
child |sibling |sibling| children
In above what does author mean "rank No. Of? can any one please explain with example.
A: As far as I understand, he tries to say: We store the rank, which is incidently the same as the no. of childen (that's how ranks for such trees are usually defined). Thus, you just store in each node the following:
*
*data represents the element in the tree
*first represents a pointer to the linked list of children (i.e. a pointer to the first child)
*left is a pointer to the left neighbour
*right is a pointer to the right neighbour
*rank is simply the rank of the binomial tree
A: Note the requirement "Two binomial trees can be merged only if they have the same size, hence the size of the tree must be stored in the root."
It seems that instead of a "size of subtree" field, the author put a "number of children" field. This is confusing, but for an implementation it is fine, because the size of the subtree is 2^{# of children}. So you can compare # of children instead of comparing size of subtree.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vector of type/class for typecasting null pointer I have program that currently use typecast for a null-pointer vector according to the following:
(Note the code is "principal", I have stripped most unecessary content.
for (i=0;i<NObjects;i++)
{
switch (ObjectTypes[i])
{
case 1:
((File_GUI*) (NullVector[i]))->function();
break;
case 2:
((Point_GUI*) (NullVector[i]))->function();
break;
case 3....etc
}
}
Is there any way to replace to large amount of case 1, case 2 etc with a simple array that is used for the typecasting? Hence the code would look something like this (Where of course the TypeCastVector must be created earlier and containt the datatypes for each index i:
for (i=0;i<NObjects;i++)
{
((typeCastVector[i]*) (NullVector[i]))->function();
}
If possible, this would save me tons of lines of codes.
A: I agree with Kerrek SB, a redesign is probably wanted so as to use a virtual function call and a base class for this purpose. If for some reason you really don't want to give File_GUI, Point_GUI, etc a base class you could do this...
struct BaseStorer
{
virtual void CallFunction() = 0;
};
template<typename T>
struct TypeStorer : public BaseStorer
{
TypeStorer(T* _obj) : obj(_obj) {}
virtual void CallFunction() { obj->function(); }
T* obj;
};
Store an array of BaseStorer* which are new TypeStorer<File_GUI>(new File_GUI(...)). Your loop would look like...
for (i=0;i<NObjects;i++)
{
baseStorerVector[i]->CallFunction();
}
A: I am having the same opinion as mentioned in comments. Presently your ObjectTypes[] seems to be an array (or vector of ints). You may want to change it to an array of pointers (handles) of a common base class. For example,
GUI *ObjectTypes[NObjects];
Where class hierarchy is like,
class GUI { // abstract base class
public:
virtual void function () = 0; // make it an abstract method
};
class File_GUI : public GUI {
void function () { ... }
};
...
Now you can replace your call in a single line as,
for (i=0;i<NObjects;i++)
{
ObjectTypes[i]->function();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Standard way to add headers to ListView in ListActivity Is there a simple way to add Section headers to a list view. I've done a custom one, but it makes it much more difficult to detect which row that is getting selected.
A: It doesn't seem be be a default way to approach this. The easiest way is to create a custom adapter. UITableViews in iOS really is a better implementation :s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: windows form GUI gets freezed when calling the thread from the while loop. How to make Gui responsive? class ...
{
onClick()
{
while(true)
{
//call the thread from here
threadpool(request)//send request to thread using thread pool
}
}
//the function for thread
threadfunction()//function that thread calls
{
// I am not able to change the textbox/datagridview in windowsform from here the main ui gets stuck //
}
}
I dont want to change the above logic is it possible to update datagrid simaltaneously from function for thread because my program just get stuck.
A: The while (true) should be inside the threadfunction, not in the onClick. Otherwise the GUI gets stuck because it's executing endlessly the while(true).
A: According to the given code while(true) runs for ever. If you have got a time consuming process you will have to use a separate thread to handle that. If you execute that time consuming process in the main thread(UI thread) it will be busy and won't take your UI change requests into account until it finish that task. That's why you experience UI freezing.
If you use a backgroundWorker for your time consuming task you will be able to achieve what you want. You have to implement the logic in the while(true) clause in the BackgroundWorkder.DoWork method.
Some points about BackgroundWorker...
DoWork in a different thread, report progress to the main thread and cancel the asynchronous process are the most important functionalities in BackgroundWorker. Below example demonstrates those three functionalities quite clearly. There are heaps of examples available on the web.
using System;
using System.Threading;
using System.ComponentModel;
class Program
{
static BackgroundWorker _bw;
static void Main()
{
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_bw.DoWork += bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
_bw.RunWorkerAsync ("Hello to worker");
Console.WriteLine ("Press Enter in the next 5 seconds to cancel");
Console.ReadLine();
if (_bw.IsBusy) _bw.CancelAsync();
Console.ReadLine();
}
static void bw_DoWork (object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i += 20)
{
if (_bw.CancellationPending) { e.Cancel = true; return; }
_bw.ReportProgress (i);
Thread.Sleep (1000); // Just for the demo... don't go sleeping
} // for real in pooled threads!
e.Result = 123; // This gets passed to RunWorkerCompleted
}
static void bw_RunWorkerCompleted (object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
Console.WriteLine ("You canceled!");
else if (e.Error != null)
Console.WriteLine ("Worker exception: " + e.Error.ToString());
else
Console.WriteLine ("Complete: " + e.Result); // from DoWork
}
static void bw_ProgressChanged (object sender,
ProgressChangedEventArgs e)
{
Console.WriteLine ("Reached " + e.ProgressPercentage + "%");
}
}
Look at here for more details.
A: First, don't make an infinite loop in the callback as the UI thread will then be running that loop for ever. Then, if threadfunction() requires UI updates, you must re-synchronize your code to the UI thread :
threadfunction()
{
myControl.Update(result);
}
class TheControl
{
public void Update(object result)
{
if (this.InvokeRequired)
this.Invoke(new Action<object>(Update), result);
else
{
// actual implementation
}
}
}
A: I would assume the main (gui) thread freeze because of the loop (it isn't clear if you handle events somehow in there). Also to change gui from inside another thread you have to call Invoke with the delegate changing desired values.
A: Windows forms controls cannot be accessed from the separate thread directly. You might want to use Control.Invoke to change textbox/datagridview properties
Check out MSDN article. about accessing controls from a separate thread.
A: Consider using async-await to process input and update the result while your UI thread does other things.
event handler:
private async void OnButton1_clicked(object sender, ...)
{
var result = await ProcessInputAsync(...)
displayResult(result);
}
Assuming that ProcessInputAsync is the time consuming function. DisplayResult is called by the UI thread, and can be processed normally.
Note: all async functions should return Task instead of void or Task<Tresult> instead of TResult. There is one exception: async event handlers should return void instead of Task.
private async Task<TResult> ProcessInputAsync(...)
{
return await Task.Run( () => LengthyProcess(...)
}
private TResult LengthyProcess(...)
{
// this is the time consuming process.
// it is called by a non-ui thread
// the ui keeps responsive
TResult x = ...
return x;
}
If you really don't want to await for the lengthy process to finish, but you want that a different thread updates the UI you get an run time error that a thread that didn't create the UI element tries to update it. For this we have the invoke pattern:
private void UpdateMyTextBox(string myTxt)
{
if (this.InvokeRequired)
{ // any other thread than the UI thread calls this function
// invoke the UI thread to update my text box
this.Invoke(new MethodInvoker(() => this.UpdateMyTextBox(myTxt));
}
else
{
// if here: this is the UI thread, we can access the my text box
this.TextBox1.Text = myTxt;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Autoloading all models in CodeIgniter Are there any disadvantages to just putting all models in $autoload['model'] instead of loading them only as necessary?
A: You might want to take a look at the CodeIgniter Profiler Class to see how your application performs auto-loading all models versus loading them only when needed. I'd recommend looking at execution time and memory usage.
Here is a similar question with some more suggestions for profiling your application. Codeigniter. Autoload models, will things get slower?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Turning off data caching asp.net I make generous use of data caching in my asp.net application. However, my pathetic little laptop does not have the RAM to handle this making development testing hard...
Does any one know how I can temporarily turn off data caching without going through my code and adding conditionals?
Thanks!
P.S. I just want to clarify that I am not talking about client side caching or output caching.
A: I would abstract the caching to an interface which you can implement in 2 different ways using dependency injection or using a factory approach. This way you can work with a generic cache and leave your code as is (not worrying about whether or not caching should be used).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: View socket data header? After accepting data from a socket, can I view the header for the data? I want to know what IP address the packet was sent to as I am listening on multiple interfaces.
A: You can use getsockname to fetch the local IP address of the socket.
int getsockname(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);
Here is an example:
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(s, &addr, &len);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript regular expression I am trying to create a regular expression where the user should enter atleast 200 words in the textarea.. I got it working partially with the below code
/(\w+\s){200,}/
Now as per the above code, it will show error if the no of words is less than 200. But it accepts only alphabets. So what i want is that it should accept all characters including . , numbers etc.. How is it possible. Please help.
A: If it were me, I would do it entirely differently as just say
var notLongEnough = "This is a test".split(/\s+/,200).length != 200
A: Here is a tested function which uses a modified version of your regex.
// Check if string contains at least 200 words.
function validate200WordCount(text) {
var re = /^\W*(?:\b\w+\b\W*){200}/;
if (re.test(text)) {
return "VALID. Text has at least 200 words.";
}
return "INVALID. Text does not have 200 words.";
}
The problem with the original regex is that it requires a space to follow each and every word. But in text, lots of words are NOT followed by spaces, e.g. punctuation. The regex needs to allow for any non-word characters that may occur between words. The improved regex above defines a word as: \b\w+\b "One or more word characters between word boundaries" and then allows any number of non-word characters between each word. A ^ beginning of string anchor was added to improve the regex efficiency.
A: If you REALLY wanted to use a match instead of a split, then I would use
" this is a string that has a bunch of stuff ".match(/^\s*(\S+\s+){199}\S+/)
That should find 199 blocks of non-space characters that are separated by whitespace characters, ending with one or more non-space characters (totaling 200 words). This will short circuit after it finds the 200th word, rather than matching into infinity.
A: Well, you could do non-space characters followed by a space character:
/(\S+\s){200,}/
In general, if a character group shorthand matches a certain set of characters, the capitalized version will match the inverse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Can the stackable trait pattern be used with singleton objects? I'd like to use the stackable trait pattern with singleton objects, but i can't seem to find how to make the compiler happy:
abstract class Pr {
def pr()
}
trait PrePostPr extends Pr {
abstract override def pr() {
println("prepr")
super.pr()
println("postpr")
}
}
object Foo extends Pr with PrePostPr {
def pr() = println("Foo")
}
Trying to evaluate this in the repl produces the following error:
<console>:10: error: overriding method pr in trait PrePostPr of type ()Unit;
method pr needs `override' modifier
def pr() = println("Foo")
A: It can, but like this:
abstract class Pr {
def pr()
}
trait PrePostPr extends Pr {
abstract override def pr() {
println("prepr")
super.pr()
println("postpr")
}
}
class ImplPr extends Pr {
def pr() = println("Foo")
}
object Foo extends ImplPr with PrePostPr
The implementation has to be present in one of the superclasses/supertraits. The abstract modification trait has to come after the class/trait with the implementation in the inheritance list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to prevent resource leaks while using Open/Save file dialog in c# we are using save/opn file dialog in our desktop application(C#).
When we open the dialog for the first time, handles are increased by 100. After closing the dialog the handles are not getting reduced. From the next time onwards handles are increasing by 10 or so and getting reduced by 2 to 4.
We tried decreasing the handles by calling dispose and making it null.
And also tried with using block.
But none of them solved the issue.
Could you please tell me any work around for this? Or can we use any custom control or so
Please advice on this
Thanks in advance
code:
The code is
SaveFileDialog objSaveDialog = new SaveFileDialog();
try
{
objSaveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveDialog.Title = "Save to Text File";
//objSaveDialog.ShowDialog();
DialogResult dlgResult = objSaveDialog.ShowDialog();
objSaveDialog.Dispose();
if (dlgResult == DialogResult.OK)
{
string strSaveFilePath = objSaveDialog.FileName;
if (!string.IsNullOrEmpty(strSaveFilePath))
{
TextWriter myTxtWriter = new StreamWriter(strSaveFilePath, false);
for (int index = 0; index < 10000; index++)
{
myTxtWriter.WriteLine("sample text.....................................");
}
myTxtWriter.Flush();
myTxtWriter.Close();
myTxtWriter.Dispose();
}
}
}
finally
{
if (objSaveDialog != null)
{
objSaveDialog = null;
//((IDisposable)objSaveDialog).Dispose();
}
}
A: A lot of code gets loaded into your process when you open a shell dialog. All of the shell extension handlers installed on your machine. Code you didn't write. You can see them getting loaded in the Output window when you tick the "Enable unmanaged code debugging" option in the Project + Properties, Debug tab.
Having these shell extension handlers misbehave and leak resources is certainly not uncommon. You can use SysInternals' AutoRuns utility to disable them. Start with the ones not written by Microsoft.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to put a message on a Websphere MQ Queue from SQL Server sp? Is there an API to connect to a Websphere MQ queue from an SQL Server stored procedure and put a message onto a queue?
If not, what would be the best way to achieve this?
A: The solution I am going to use for this is to write a CLR stored procedure and deploy this onto SQL Server.
Inside the CLR stored proc I will use the MQ .NET api.
Update: I created a stored proc using the following code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using IBM.WMQ;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static int MQStoredProc(String queueManager, String queueName, String messageText)
{
//MQEnvironment.Hostname = "localhost";
//MQEnvironment.Port = 1414;
//MQEnvironment.Channel = "SYSTEM.DEF.SVRCONN";
MQQueueManager mqQMgr = null; // MQQueueManager instance
MQQueue mqQueue = null; // MQQueue instance
try
{
mqQMgr = new MQQueueManager(queueManager);
mqQueue = mqQMgr.AccessQueue(queueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); // open queue for output but not if MQM stopping
if (messageText.Length > 0)
{
// put the next message to the queue
MQMessage mqMsg = new MQMessage();
mqMsg.WriteString(messageText);
mqMsg.Format = MQC.MQFMT_STRING;
MQPutMessageOptions mqPutMsgOpts = new MQPutMessageOptions();
mqQueue.Put(mqMsg, mqPutMsgOpts);
}
return 0;
}
catch (MQException mqe)
{
return ((int)mqe.Reason);
}
finally
{
if (mqQueue != null)
mqQueue.Close();
if (mqQMgr != null)
mqQMgr.Disconnect();
}
}
};
This is not production ready but is inserting messages successfully on a queue manager running on the same server as the SQL server in bindings mode.
A: There is a much simpler solution than that..Check this out.
http://publib.boulder.ibm.com/infocenter/wmbhelp/v7r0m0/index.jsp?topic=%2Fcom.ibm.etools.mft.doc%2Fbc34040_.htm
A: The simplest way I can think of is to, write the information on to a file and then use rfhutil to export the message onto queue. This would require manual intervention. The other option would be to write a simple java application using JMS and JDBC.
A: The .NET CLR approach would have been my suggestion, too. I'd be curious to see an example of the code, I've never tried that before! Should work I guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: activescaffold belongs_to relationship giving routing error I am using the following:
Rails 3.0.3
Vhochstein's Fork for Activescaffold
rake 0.9.0
ruby 1.9.2
I have a model called component which has a belongs_to relationship with category. This was modelled using activescaffold and was working quite well. I took a break for a couple of months and now that I got back to it activescafold gives a
"ActionController::RoutingError (undefined method `class_name' for nil:NilClass):" error whenever I try to access the component model.
I figured this is due to the relationship (belongs_to). If i remove the relationship from the model, it works. If I add it back it fails!
Any Ideas?
Here is the Code:
Routes
namespace :admin do
resources :users,:roles,:vendors,:shipping_modes,:order_types,:sizes,
:suppliers,:categories,:sub_categories, :material_types,:colours,
:materials,:styles,:surcharges, :budget_templates, :budget_components do
as_routes
end
end
Controller
class Admin::BudgetComponentsController < ApplicationController
layout 'site_admin'
active_scaffold :budget_component do |config|
config.actions.exclude :delete,:update
config.columns[:category].form_ui = :select
config.create.columns = [:name,:category]
config.list.columns = [:name,:category]
config.show.columns = [:name,:category]
config.show.columns.add_subgroup "Time Details" do |name_group|
name_group.add :created_at,:updated_at
end
config.list.sorting = {:name => 'ASC'}
end
end
Model
class BudgetComponent < ActiveRecord::Base
belongs_to :category
validates_presence_of :name, :category_id
validates_uniqueness_of :name
end
A: I had a similar problem. The solution is to add your nil:NilClass again, then it will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to perform system restore (c#) Is there is some way to perform system restore from c# code? Any links\sample?
The program can be run form local or remote, whatever is better.
EDIT:
I have a machine that can be used by many users. I want to write a program that after the user check in the computer will run system restore in order to recover the OS and make sure the next user will have a working stable OS.
Thanks!
A: This guide talks you through it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where can I find a good GVIM cheatsheet? Can anyone recommend a GVim cheatsheet specifically for GVIM?
Am pretty much a new user and wondering where to look for a cheatsheet?
A: http://www.viemu.com/vi-vim-cheat-sheet.gif is my favourite.
A: Here: https://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/gvim/gvim.html
Is a tutorial and a few sheets.
A: http://tnerual.eriogerg.free.fr/vim.html
A: vimtutor is a great tutorial for beginers
A: My favorite is zapper's tipset. It's really excellent. And visit all Vim Tips Wiki site -- there are gems there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to switch a getElementById to getElementsByClassName Im trying to switch a getElementById to getElementsByClassName
for a project like this: http://jsfiddle.net/2waZ2/21/
My simple efforts just dont work: http://jsfiddle.net/2waZ2/27/
A: Change
document.getElementsByClassName('mytable').appendChild( row ) ;
to
document.getElementsByClassName('mytable')[0].appendChild( row ) ;
http://jsfiddle.net/2waZ2/30
and also remove dot in your class name.
Or easily use jQuery
row = displayArrayAsTable(QR4, 24, 25);
$(".mytable").append(row);
http://jsfiddle.net/2waZ2/32/
A: Almost there, you just need to remove the dot in getElementsByClassName and only get the first result from that, like this:
document.getElementsByClassName('mytable')[0]
http://jsfiddle.net/2waZ2/33/
A: getElementsByClassName returns array of elements, not single element, as getElementById. So you should iterate over your collection (unless you want to append only to first found element) with:
var elements = document.getElementsByClassName('mytable');
for(var i = 0; i < elements.length; i++) { elements[i].appendChild( row ) };
Also remove dot from class name, as it's not part of class name (the same as # is not part of id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Google maps glitch showing blank squares with x in the middle android Like i say in title my app is behaving strangely. It all worked fine until this morning... I changed some image in my app before uploading it onto market, and then i wanted to see once again whether everything is OK...Now i dont know what to do...see the image:
And here is xml:
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:enabled="false"
android:layout_alignParentTop="true"
android:layout_above="@+id/seekBar1"
android:layout_weight="5"
android:apiKey="******-********************************" >
</com.google.android.maps.MapView>
Can anybody give some advice???
A: In my case I don't use mapView.setStreetView(true or false), but just use mapView.setSatelite (true) when i want to use Satelite view on the map, and set mapView.setSatelite.(false) when i want to use Street view...
I hope that this will help somebody else...
Once again thanks people for your time and help... :D
A: I found this bug (setSatteliteView + setStreatView) as a specific for concrete android versions.
It exists on 2.2.1, but not on 2.3.5 (I have checked 2 different devices though)
A: This is a possible bug in Google Maps that has popped up as recently as the past few weeks.
Someone else had a similar problem here.
In that case, the error was that both
mapView.setSatellite(true);
mapView.setStreetView(true);
appeared in the code. The documentation says that this is allowed, but in practice, it seems to be causing problems. Look through your code to see if it contains both of those lines, and try commenting out one of them to see if it fixes things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: parent-child relation to flat view Is there an easy way to migrate a table with a parent child relation to a column one ?
INPUT_TABLE
PARENT_ID,ID,NAME
null,1, USA
1 ,2, Las Vegas
2 ,3, City in las Vegas
2 ,4, Another City in las Vegas
.. a lot more
OUTPUT
ID, COUNTRY, CITY, PLACE
1, USA, null,null
2, USA, Las Vegas,null
3, USA, Las Vegas,City in las Vegas
4, USA, Las Vegas,Another City in las Vegas
Thanks in advance
A: Provided you have a hierarchie of 3 items as per your comments and there's no need to retain rows that have no City or Place, joining the table twice with itself would suffice.
SQL Statement
SELECT ID = Country.ID
, Country = Country.NAME
, City = City.NAME
, Place = Place.Name
FROM q Country
INNER JOIN q City ON City.PARENT_ID = Country.ID
INNER JOIN q Place ON Place.PARENT_ID = City.ID
(SQL Server) Test script
;WITH q (PARENT_ID, ID, NAME) AS (
SELECT null, 1, 'USA'
UNION ALL SELECT 1, 2, 'Las Vegas'
UNION ALL SELECT 2, 3, 'City in las Vegas'
UNION ALL SELECT 2, 4, 'Another City in las Vegas'
)
SELECT ID = Country.ID
, Country = Country.NAME
, City = City.NAME
, Place = Place.Name
FROM q Country
INNER JOIN q City ON City.PARENT_ID = Country.ID
INNER JOIN q Place ON Place.PARENT_ID = City.ID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SUM on a Column Group i have three tables with structure something like
tasktime - starttime,endtime,packagedetailid,packageid
packagedetailid - packageid,productid, etc
productime - productid and searchesperday
and the query i am using on these is as follows
SELECT CONVERT(varchar, t.StartTime, 111) AS 'Date'
, SUM(DATEDIFF(second, t.StartTime, t.EndTime)) / 60 AS DailyMinutes
, COUNT(DISTINCT p.PackageDetailID) AS OrderCount
, LEFT(CAST(SUM(DATEDIFF(minute, t.StartTime, t.EndTime))
/ (COUNT(DISTINCT p.PackageDetailID) + 0.0000001) AS varchar), 4) AS PerOrder
, LEFT(CAST((COUNT(DISTINCT p.PackageDetailID) * 100)
/ (e.SearchesPerDay + 0.00000001) AS varchar), 4) AS WeightedOrderCount
FROM ProductTime AS e INNER JOIN dbo.PackageDetails AS p
WITH (NOLOCK) ON e.ProductID = p.ProductID INNER JOIN
TaskTime AS t WITH (NOLOCK) ON p.PackageDetailID = t.PackageDetailId
WHERE(t.EndTime IS NOT NULL)
AND (DATEDIFF(hour, t.StartTime, t.EndTime) < 1)
AND (DATEDIFF(second, t.StartTime, t.EndTime) > 0)
AND (t.UserId = '12345')
AND (t.StartTime BETWEEN '1/1/2010'
AND '9/13/2010')
GROUP BY CONVERT(varchar, t.StartTime, 111), e.SearchesPerDay
ORDER BY CONVERT(varchar, t.StartTime, 111)
The OUTPUT is:
**date dailyminutes ordercount perorder weightordercount**
2010/01/04 104 26 4.03 43.30
2010/01/04 10 1 9.99 1.24
2010/01/04 19 8 2.37 8.88
2010/01/04 22 11 1.99 10.90
2010/01/04 18 5 3.59 2.77
2010/01/05 49 17 2.99 28.30
2010/01/05 31 5 6.39 5.55
2010/01/05 26 6 4.33 5.99
2010/01/05 8 4 1.99 3.33
But i want to SUM up the "Weightordercount" against the date so that the output is
**date dailyminutes ordercount perorder weightordercount**
2010/01/04 173 51 21.97 67.09
2010/01/05 114 32 15.70 43.17
i am not a sql expert and need your help if this can be achieved by a Single SQL command or through a Strored Procedure
Thanks in advance
A: Your code is horribly formatted in your post, so I'm going to give you a general answer:
You need to use a GROUP BY clause and then SUM each of your aggregates.
So something like this:
select date, sum(dailyminutes), sum(ordercount), sum(perorder), sum(weightordercount)
from (yourentirequery) a
group by date
order by date asc
A: (1) Don't use varchar without length - but why are you converting to a varchar anyway?
(2) Why are you grouping by searches per day? I'm guessing this needs to be a SUM to be meaningful, here is how I would do it:
;WITH x AS
(
SELECT
[Date] = DATEDIFF(DAY, '19000101', t.StartTime),
DailyMinutes = SUM(DATEDIFF(SECOND, t.StartTime, t.EndTime)),
OrderCount = COUNT(DISTINCT p.PackageDetailID),
SearchesPerDay = SUM(e.SearchesPerDay)
FROM
dbo.ProductTime AS e
INNER JOIN
dbo.PackageDetails AS p
ON e.ProductID = p.ProductID
INNER JOIN
dbo.TaskTime AS t
ON p.PackageDetailID = t.PackageDetailID
WHERE
t.EndTime IS NOT NULL
AND (DATEDIFF(SECOND, t.StartTime, t.EndTime) BETWEEN 1 AND 3599)
AND (t.UserId = '12345')
AND (t.StartTime >= '20100101' AND t.StartTime <= '20100913')
GROUP BY
DATEDIFF(DAY, '19000101', t.StartTime)
)
SELECT
[Date] = DATEADD(DAY, [Date], '19000101'),
DailyMinutes,
OrderCount,
PerOrder = CONVERT(DECIMAL(10,2), (DailyMinutes * 1.0 / OrderCount)),
WeightedOrderCount = CONVERT(DECIMAL(10,2), (100.0 * OrderCount / SearchesPerDay))
FROM
x
ORDER BY
[Date];
A couple of other enhancements:
(a) don't use BETWEEN for date/time, use >= and < (I left the end as <= but it's likely you either meant < 9/14 or < 9/13).
(b) don't use regional formats for dates - '09/13/2010' is not a valid date depending on language, dateformat or regional settings. 'YYYYMMDD' is the safest format to use in SQL Server for date only.
(c) try to perform calculations as few times as possible - I moved repeated calculations into a CTE so that reference in other calculations can be much simpler. You don't need a CTE, you can also use a subquery. This is also the reason I combined the two checks against the delta between StartTime and EndTime.
(d) your method for getting decimals was rather crude - adding decimal places, converting to a string, taking the left...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can double quotes be used to delimit a string? I was surprised to encounter a SQL 2008 T-SQL proc that used a double quote as a string delimiter. For example:
DECLARE @SqlStmt AS VarChar(5000)
SET @SqlStmt = "ok"
PRINT @SqlStmt
I didn't think it was allowed. I thought only apostrophes could be used.
Thinking that T-SQL is flexible like Javascript to allow either as delimiters in case you wanted to mix the two in a single statement, I tried to do the same in one of my stored procs because I wanted to construct dynamic SQL that included ticks. I was surprised that the script wouldn't compile, I was getting an "INVALID COLUMN [X]" error where X was the contents of my quoted string.
So, I stripped it down to it simplest components until I got the exact SQL you see above, which compiles, runs, and prints "OK".
Now the real surprising part:
I placed the T-SQL script above on my clipboard, executed Control + N to open a new query window using the same connection and pasted the above script into the new query window and was shocked to see that I was getting the following error in the new window:
Msg 207, Level 16, State 1, Line 3
Invalid column name 'ok'.
Explanation Update:
Apparently I had removed the SET QUOTED_IDENTIFIER from the original script, but I had already executed it in the original query window, but the option was still in effect. When I created a new query Window, the option was reset to off by default.
Thanks for the answers.
A: If QUOTED_IDENTIFIER is OFF then they can be used to delimit a string. Otherwise items in double quotes will be interpreted as object names.
Always use single quotes to delimit strings and square brackets for those object names that require delimiting so your code doesn't break when run under the "wrong" setting.
A: Like already Martin Said, you could use like this.
SET QUOTED_IDENTIFIER OFF
BEGIN
DECLARE @SqlStmt AS VarChar(5000)
SET @SqlStmt = "ok"
PRINT @SqlStmt
END
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dev express Grid View column header size Is there a property of a grid view control that can set the text size of a column header?
A: For that controll you have a HeaderStyle Porperty
For example:
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
Well explained at MSDN:
Formatting the GridView
A: Sorry, I forgot to mention that it needs to be server side. figured it out.
Me.Grid.Columns(columName).HeaderStyle.Font.Size = 50
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is "Configuration Type"? I don't have much experience on interactiong with config files and I was reading the GetSection() method in MSDN which notes that:
**Notes to Implementers**:
You must cast the return value to the expected configuration type.
To avoid possible casting exceptions, you should use a conditional
casting operation such as...
What does "configuration type" mean in this note? Are not the sections selected represents an xml node always?
A: There's some great samples on MSDN here: http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
Here, the "configuration type" is the custom type that's been created to extend ConfigurationSection. Yes, this is implemented as an XML node, but the intent of the System.Configuration namespace is to abstract this away.
A: Configuration Type is basically just the type of the custom class you define to represent the configuration values you want to store in the App.Config or Web.Config
Your custom config section needs to inherit from System.Configuration.ConfigurationSection and when you use the GetSection method, you need to cast the return value as the type of your Custom class that you inherited off of System.Configuration.ConfigurationSection
see more here
An example would be if I had a special class to represent a property I wanted to store in either the App.Config or Web.Config such as:
public class MyConfig : ConfigurationSection
{
[ConfigurationProperty("myConfigProp", DefaultValue = "false", IsRequired = false)]
public Boolean MyConfigProp
{
get
{
return (Boolean)this["myConfigProp"];
}
set
{
this["myConfigProp"] = value;
}
}
}
Any time I would want to access that property I would do the following in my code:
//create a MyConfig object from the XML in my App.Config file
MyConfig config = (MyConfig)System.Configuration.ConfigurationManager.GetSection("myConfig");
//access the MyConfigProp property
bool test = config.MyConfigProp;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS difference between ".cssClass object" and "object.cssClass" I was doing some css today and was forced to change some syntax from:
input.cssClass
to
.cssClass input
How do these definitions differ, and when should we use either of them?
A: Wow, that is an odd change. The first will collect all the inputs with class cssClass, while the second will take all inputs inside any element with cssClass.
<body>
<input class="cssClass" type="text" />
<div class="cssClass">
<input type="text" />
</div>
</body>
So here, the first input will be grabbed by your first selector, while the second input will be grabbed by your second selector. Neither selector will grab both.
A: input.cssClass will apply that style to input type objects that have that class specified.
.cssClass input will apply that style to input type objects that are contained within any other object type that has the cssClass class.
A: The first works with any input element that has the class cssClass:
<input class="cssClass" type="text" />
Whereas the second works with any input element inside an element with class cssClass, eg.:
<div class="cssClass">
<input type="text" />
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# Thread Pool - how to return value (to make it fully synchronized with request) I have a webservice that ask for data from my server.
The request needs to be run inside a thread pool, how do I return the value to the client?
A: You can't pass a response back to your client on the initial request. You would have to return a token that the client would subsequently poll another method on your class with to check to see if the operation was complete; if the operation is complete, the method returns the result, otherwise, it returns a result to indicate that it should continue to poll.
If you are using .NET 4.0, I'd recommend using the Task<T> class, and passing that back to your client; your client can poll for the result, wait on it, get notification when it's done, etc.
If you are not working with .NET 4.0, then I recommend using a custom Delegate, assigning an anonymous method/method group to it, and then calling BeginInvoke on the delegate; this will return an IAsyncResult implementation which you can use to perform the operations mentioned above (polling, waiting, etc).
A: Multithreading is by its definition asynchronous. In order to get value back, you need to implement some form of callback (a method that the thread can call when it has finished its operation) so that it can pass the value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to structure data in order to use item preference recommendation in mahout first of all new to mahout, apache, maven etc - so apologies if some if this is obvious.
I have a typical market basket data set ie
user1, item1
user1, item2
user2, item1
user2, item3
user3, item2
my query - what are recommendations for user3 ? (Yes I know the answer is item1!).
How do I structure this for use in Mahout ? I have looked at the page - https://cwiki.apache.org/MAHOUT/recommender-documentation.html - which is very useful - but just when I want the interesting bit - ie how to build the correlation data - it says :
// Construct the list of pre-computed correlations
Collection<GenericItemSimilarity.ItemItemSimilarity> correlations =
...;
ItemSimilarity itemSimilarity =
new GenericItemSimilarity(correlations);
and the bit I want to calculate is the missing ... !!!
Although this is completely the wrong way of doing it, I massaged my dataset to look identical to the movielens structure (giving a 5 as a rating, but really it should be a binary true), but all recommendations for all users are always the same list of products.
Any advice please ?
A: (This data is so sparse that I don't know that a recommender would actually recommend item 1, by the way.)
The code snippet you reference would be what you use if you already had precomputed item-item similarities. You don't have that here; you have user-item associations. Surely you mean to compute those similarities from this data, and use that for recommendations?
While you can do this programmatically, I suggest it's faster to craft a simple text file with your data...
1,1
1,2
2,1
2,3
3,2
Then to make your item-based recommender with a log-likelihood similarity:
DataModel model = new FileDataModel(new File("yourdata.txt"));
ItemSimilarity similarity = new LogLikelihoodSimilarity(model);
Recommender recommender =
new GenericBooleanPrefItemBasedRecommender(similarity, model);
and to recommend 1 item for user 3:
recommender.recommend(3, 1);
(This is covered in fair detail in Mahout in Action.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to call a view from another view in iPhone I want to call a view in the same view on a button click, is there any way to do it other then PushViewContrller and PresentModalView.
Thanx in advance......
A: i think its working ......
-(void)btn_clicked{
[self addSubView:new_View];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jaxb - how to create XML from polymorphic classes I've just started using JAXB to make XML output from java objects. A polymorphism exists in my java classes, which seems to not working in JAXB.
Below is the way how I tried to deal with it, but in the output I haven't expected field: fieldA or fieldB.
@XmlRootElement(name = "root")
public class Root {
@XmlElement(name = "fieldInRoot")
private String fieldInRoot;
@XmlElement(name = "child")
private BodyResponse child;
// + getters and setters
}
public abstract class BodyResponse {
}
@XmlRootElement(name = "ResponseA")
public class ResponseA extends BodyResponse {
@XmlElement(name = "fieldA")
String fieldB;
// + getters and setters
}
@XmlRootElement(name = "ResponseB")
public class ResponseB extends BodyResponse {
@XmlElement(name = "fieldB")
String fieldB;
// + getters and setters
}
Before I start invent some intricate inheritances, is there any good approach to do this?
A: For your use case you will probably want to leverage @XmlElementRefs, this corresponds to the concept of substitution groups in XML Schema:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement
private String fieldInRoot;
@XmlElementRef
private BodyResponse child;
// + getters and setters
}
*
*http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
You can also leverage the xsi:type attribute as the inheritance indicator:
*
*http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html
EclipseLink JAXB (MOXy) also has the @XmlDescriminatorNode/@XmlDescriminatorValue extension:
*
*http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-moxy-extension.html
A: @XmlRootElement(name = "root")
public class Root {
....
@XmlElements({
@XmlElement(type = ResponseA.class, name = "ResponseA"),
@XmlElement(type = ResponseB.class, name = "ResponseB")})
private BodyResponse child;
}
Maybe you need an @XmlType(name = "ResponseX") on your Response classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Linq to SQL loop performance OK, I have a bunch of complex logic I need to iterate through. I am calling a web service and getting back results. I take the results and loop through them and make different database calls based on various rules.
The initial code I used was the following:
foreach(var obj in MyObjects)
{
using(var connection = new LinqToSqlDBContext())
{
connection.StoredProc1(obj.Name);
connection.StoredProc2(obj.Name);
connection.SubmitChanges();
}
}
I figure this would be more efficient:
using(var connection = new LinqToSqlDBContext())
{
foreach(var obj in MyObjects)
{
connection.StoredProc1(obj.Name);
connection.StoredProc2(obj.Name);
}
connection.SubmitChanges();
}
Is there a better way I can do this to increase performance? I am using Linq to SQL classes and C# 4.0.
Thanks!
A: Since you are invoking stored-procs, but not performing object changes, the SubmitChanges() is redundant. In normal usage, I would expect this SubmitChanges to be a significant factor, so balancing the number of calls vs the size of individual transactions is important. However, that doesn't apply here, so I would just use:
using(var connection = new LinqToSqlDBContext())
{
foreach(var obj in MyObjects)
{
connection.StoredProc1(obj.Name);
connection.StoredProc2(obj.Name);
}
}
A: yes, I think 2 one is better one because you are updating data just establishing connection where as in 1 one you are dropping and than again connecting so that it add cost of dropping and gaining connection with database.
A: Consider batching the operations performed inside the stored procedures by making the procedures accept a list of names instead of one name. This can be achieved using Table-Valued parameters.
A: As ever - it depends.
In your examples, the first block of code runs the stored procedures and submits changes for each object in separate transactions.
The second block of code, however, executes the stored procedures... and then commits all the changes in one go, in one single transaction.
This may be more efficient, depending on your application.
Best of all, if you can, is to reduce the number of database calls. So if you can rework the stored procedure to take a list of names rather than one single name, and then perform the loop on the database server, you'll most likely see a significant improvement in performance.
Note that there's in practice usually little overhead associated with opening and closing connections as they are typically cached in a connection pool. So, the performance of
using(var connection = new LinqToSqlDBContext())
{
foreach(var obj in MyObjects)
{
connection.StoredProc1(obj.Name);
connection.StoredProc2(obj.Name);
}
}
and
foreach(var obj in MyObjects)
{
using(var connection = new LinqToSqlDBContext())
{
connection.StoredProc1(obj.Name);
connection.StoredProc2(obj.Name);
}
}
will most likely be very similar.
A: Well, actually your question has nothing to do with Linq2Sql since you are using stored procedures. You may try to invoke the stored procedures not with the datacontext but using ado.net. Perhaps that has some performance advantages but I am not sure.
First of all, since your two stored procedures have the same arguments, you can combine that into one stored procedure so it might again take a bit of your overhead.
Also do as Jonas H says: provide a list of names and call the SP once.
And perhaps you can do some parrallel processing by invoking the SP's all in a different thread but this is where Marc Gravell might shine some light?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to create json structure in java? var abc = {"action":"Remove",
"datatable":[
{"userid":"userid0","username":"name0"},
{"userid":"userid1","username":"name1"},
{"userid":"userid2","username":"name2"},
{"userid":"userid3","username":"name3"}
]
, "msgType":"success"};
How could I create above JSON structure in java and send it as response & at client side how could I parse it?
A: Use Google's gson library. It converts java objects to and from json.
I've used it and it's really good.
A: consider groovy: http://groovy.codehaus.org/gapi/groovy/json/JsonBuilder.html (won't help you on the client side though)
A: Simple as using springframework and mark your @Controller method with @ResponseBody to json-encode your pojos.
Also use @RequestBody to decode json back and if needed use jackson annotations to customize d/encoding
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Seam swallowing JDBC exceptions I'm working with Seam 2.1 but when I get a JDBC Exception throw proxy call, the framework swallows the exception without logging it. There is any way to show the exception?
Thanks
A: Have you seen this?
JSF is surprisingly limited when it comes to exception handling. As a
partial workaround for this problem, Seam lets you define how a
particular class of exception is to be treated by annotating the
exception class, or declaring the exception class in an XML file. This
facility is meant to be combined with the EJB 3.0-standard
@ApplicationException annotation which specifies whether the exception
should cause a transaction rollback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JasperReports fonts I need to export the Japanese report in PDF. Report font must be Tahoma. So I set the report font as "Tahoma". Initially it thrown like "tahoma" not available to JVM, I have placed the tahoma.ttf as jar in classpath. After that, When I execute, For Tahoma, it doesn't support, pdf encode= "UniJIS-UCS2-HW-H" option.
Error is like:
Usupported encoding: "UniJIS-UCS2-HW-H"
PDF font used is "HeiseiKakuGo-W5"
Can anyone suggest a solution please?
A: Do not use pdfEncoding or isPdfEmbedded. These attributes were deprecated years ago. Use Font Extensions. They were introduced to solve exactly this problem. They'll let you generate the PDF as you are attempting to do. If you Google "jasperreports font extensions" you should find the information that you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Spring: how to initialise Bean A after load of Bean B is complete? I have a BeanA which whose constructor requires BeanB.
Once BeanB has been instantiated (and its properties set), I'd like to invoke BeanB.init()
Is there a way of doing this?
An alternative would be to have BeanB.init() invoked after all beans in the context have been created.
Cheers!
A: You can use init-method in your applicationContext.xml in order to specify an init method. If you want a bean to instantiate after another, you can use depends-on, even though any ref element (in this example inside constructor-args) will implicitly place a dependency.
This would initialize firstly Bean B with an init method and, when finished, use it in as constructor argument to A.
<!-- Bean B -->
<bean id="beanB"
class="classB"
init-method="init"
/>
<!-- Bean A -->
<bean id="beanA"
class="classA"
init-method="anotherInit">
<constructor-arg ref="beanB"/>
</bean>
A: You can make BeanB implement InitializingBean. The drawback of this is that you're creating a dependency between BeanB and Spring, which is not great.
I think a better approach would be to inject all the dependencies in the constructor and call init form it. In this way, you don't need to tie your class to Spring.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Data bindings in Data Template not working I have UserControl to do filtering for several presentations, which in turn has a ContentControl. The content are the individual filtering controls that vary among the presentations.
The scheme works as intended visually, but the data bindings do not. There are no data binding errors in output. The DataContext is from a view model call PimMasterVm, which otherwise seems correctly wired (ie, the status of 5 avalable people, etc)
Can someone help me trouble shoot this?
Cheers,
Berryl
Filtering Control
<Grid>
<Border Style="{StaticResource FilterPanelBorderStyle}">
<StackPanel Orientation="Horizontal" x:Name="myFilterPanel" >
<ContentControl x:Name="ctrlFilters"
ContentTemplate="{Binding Path=FilterContentKey, Converter={StaticResource filterTemplateContentConv}}" />
<Button x:Name="btnClearFilter" Style="{StaticResource FilterPanelClearButtonStyle}" />
<Label x:Name="lblStatus" Style="{StaticResource FilterPanelLabelStyle}" Content="{Binding Status}" />
</StackPanel>
</Border>
</Grid>
Data Template (resource)
<DataTemplate x:Key="pimFilterContent">
<StackPanel Orientation="Horizontal" >
<cc:SearchTextBox x:Name="stbLastNameFilter"
Style="{StaticResource FilterPanelSearchTextBoxStyle}"
Text="{Binding Path=LastNameFilter, UpdateSourceTrigger=PropertyChanged}"
/>
<cc:SearchTextBox x:Name="stbFirstNameFilter"
Style="{StaticResource FilterPanelSearchTextBoxStyle}"
Text="{Binding Path=FirstNameFilter, UpdateSourceTrigger=PropertyChanged}"
/>
</StackPanel>
</DataTemplate>
A: There is current view model in DataContext of the "ctrlFilters" ContentControl, bind it to Content property:
...
<ContentControl x:Name="ctrlFilters"
Content="{Binding}"
ContentTemplate="{Binding Path=FilterContentKey, Converter={StaticResource filterTemplateContentConv}}" />
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Select from a certain row and onwards with mysql How can I select from a certain row and onwards?
For instance, the table I want to query,
pg_id pg_title pg_backdate
1 a 2012-09-18 13:32:49
2 b 2011-09-18 13:32:49
3 c 2011-06-18 13:32:49
4 d 2010-05-18 13:32:49
5 e 2009-04-18 13:32:49
6 f 2011-10-18 13:32:49
7 g 2012-04-18 13:32:49
8 h 2012-09-18 13:32:49
9 i 2012-10-18 13:32:49
I want to select the top 5 rows only, starting from current month and year and onwards, I have worked on the query below - it only selects the top 5 of current month and current year but not the rows onwards,
SELECT *
FROM root_pages AS p
WHERE DATE_FORMAT(p.pg_backdate, '%Y') = '2011'
AND DATE_FORMAT(p.pg_backdate, '%m') = '09'
ORDER BY p.pg_backdate DESC
LIMIT 5
Ideally, it should return these rows only,
pg_id pg_title pg_backdate
1 a 2012-09-18 13:32:49
2 b 2011-09-18 13:32:49
6 f 2011-10-18 13:32:49
7 g 2012-04-18 13:32:49
8 h 2012-09-18 13:32:49
A: SELECT *
FROM root_pages AS p
WHERE p.pg_backdate >= '2011-09-01'
ORDER BY p.pg_backdate DESC
LIMIT 5
Using functions like you do will kill any chance MySQL has of using an index.
If you want to select the top 5 from the month do:
SELECT *
FROM root_pages AS p
WHERE p.pg_backdate BETWEEN '2011-09-01' AND '2011-09-30'
ORDER BY p.pg_backdate DESC
LIMIT 5
If you want the top 5 in the month and the rows beyond, then do
SELECT *
FROM root_pages AS p
WHERE p.pg_backdate BETWEEN '2011-09-01' AND '2011-09-30'
ORDER BY p.pg_backdate DESC
LIMIT 5
UNION ALL
SELECT *
FROM root_pages AS p
WHERE p.pg_backdate > '2011-09-30'
ORDER BY p.pg_backdate DESC
A: SELECT *
FROM root_pages
WHERE pg_backdate >= '2011-09-01'
ORDER BY pg_backdate
LIMIT 0, 5
The above query will return 5 rows starting from 1st day of September 2011 and onwards. An ORDER BY clause will return the dates closest to that date. You can generate the date (1st of current month) via PHP - or - you can have MySQL do that for you:
SELECT *
FROM root_pages
WHERE pg_backdate >= CAST(CONCAT_WS('-', YEAR(CURRENT_TIMESTAMP), MONTH(CURRENT_TIMESTAMP), 1) AS DATE)
ORDER BY pg_backdate
LIMIT 0, 5
A: He wants to order by id it seems...
SELECT *
FROM (
SELECT *
FROM root_pages AS p
WHERE p.pg_backdate >= '2011-09-01'
ORDER BY p.pg_backdate DESC
LIMIT 5
) AS sub
ORDER BY sub.pg_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ajax + back & forward buttons I'm starting to write new application and want to make it full ajax style :)
I'm using Jquery to make ajax requests.
Main JS file gets some variable from pressed link and according to that link goes to some php files grabs some data comes back and puts everything in pre prepared html tags.
This is the way I see this app.
Now I've found some solutions to make back&forward buttons start working but in those solutions their script goes to predefined pages and reads some data according to some constant ID So I don't like it.
What I want is...
*
*I need some code which will prevent browser from page reloading if user is pressing back,forward button
*Remember browser position, so If we are on state 'C' and back was pressed it brings to JS some variable with value 'B', then JS goes to php and says 'B' so php will understand which content to prepare. gives content back to JS , JS updates the page, everybody happy.
Is there solution which will work this way ?
A: I've used jQuery BBQ: Back Button & Query Library in the past for just this purpose.
Specifically, the basic AJAX example looks to be what you're after. The rest of the examples are most excellent as well.
A: I think you should take a look at backbone.js http://documentcloud.github.com/backbone/. It has a router based application structure, where each route is actually a different /#'ed url.
Like this when you have an item list, you could display it in route /#itemsList, and each item details page could be on /#items/id. The entire navigation is handled for you, all you have to do is to call some functions or paste the code that you want to be ran when you get to that url. (example adapted http://documentcloud.github.com/backbone/#Router)
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"item/:id": "item", // #item/myItemId
"itemList": "list" // #itemList
},
help: function() {
... show help
},
item: function(id) {
... show single item with jQuery, Ajax, jQuery UI etc
},
itemList: function(){
... show item list with jQuery, jQuery UI etc.
}
});
www.myapp.com/#help -> help code
www.myapp.com/#item/32 -> item with ID 32, which is captured in the item(id) function and a request is made to fetch the data via Ajax
www.myapp.com/#itemList -> the list of all items, where you can generate links with #item/id for each item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7499757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.