text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Gmail does not list sent items if mail sent from custom smtp server We have our own company's smtp server.
When we send mails using the above smtp server, the mails do not list in the gmail's sent items.
The mail is sent using asp.net
What can be done?
A: Instead of using your own SMTP server, use the SMTP server from GMail. How else can Gmail know that you have send an email.
You have to supply credentials to use Google's SMTP server, so you must store the user's username and password (from Gmail).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DataGridView ICustomTypeDescriptor I´m want build a DataGridView with Databinding to a Class where I can add Properties at Runtime.
I want to add Columns at runtime and have the values stored in the class.
I found a nice example here (Dictionary to store Properties with ICustomTypeDescriptor)
It works fine til i want read information from the DataGridView. I get NullReferenzException or IndexOutOfBoundException.
I think something is missing in my BindingClass with the ICustomTypeDescriptor.
The .NET designer don´t create Columns in Visual Studio but therea are created at programmstart.
I will be realy glad, if someone could help me with this one.
A: I don't know the answer, but I suggest checking the column management.
Maybe you have forgotten for example assigning the Name or DataPropertyName properties of the column...
Please give more description of your problem + some code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Window is not releasing when switching to another window I am creating a Mac application in which I have mainwindow with some buttons.
When I click button it will open a DetailWindow with NSTableview. Every buttonclickevent change the data in NSTableView.
Here is my code:
In my mainWindow.m FIle
- (IBAction)btn1Event:(id)sender {
if (!detailwindow) {
detailwindow = [[DetailWindow alloc] initWithWindowNibName:@"DetailWindow"];
detailwindow.mainwindow = self;
}
detailwindow.title = @"First";
[detailwindow showWindow:self];
}
- (IBAction)btn2Event:(id)sender{
if (!detailwindow) {
detailwindow = [[DetailWindow alloc] initWithWindowNibName:@"DetailWindow"];
detailwindow.mainwindow = self;
}
detailwindow.title = @"Second";
[detailwindow showWindow:self];
}
In DetailWindow
- (void)windowDidLoad
{
[super windowDidLoad];
[tableView setBackgroundColor:[NSColor clearColor]];
[tableView setHeaderView:nil];
if([title isEqualToString:@"First"]){
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"MS.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"CVS.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"NS.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"EM.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RES.png"],@"image",@"first image",@"text", nil]];
}
if ([title isEqualToString:@"Second"]) {
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RS.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"FB.png"],@"image",@"first image",@"text", nil]] ;
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"GT.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"SKIN.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"GP.png"],@"image",@"second image",@"text", nil]];
}
[tableView reloadData];
}
- (IBAction)GoToMainWindow:(id)sender {
[mainwindow showWindow:self];
}
If i click first button this if([title isEqualToString:@"First"]) event call and I can see first five image in my tableview.
After that if I click second button I can't see the next five image in table. Data is not changing because if ([title isEqualToString:@"Second"]) this event is not being call.
If I first click second button then same thing happen with first event.
Any idea why? I think window is not releasing when I click any of button at secondly.
A: No, that's because your insert image method is in the -(void)windowDidLoad method, which gets called on when the window is loaded, not when you call the showWindow: method so it only gets called once. Instead of calling the showWindow: method in mainWindow.m, create a new method in DetailWindow instead and call that when you click the button.
- (IBAction)btn1Event:(id)sender {
if (!detailwindow) {
detailwindow = [[DetailWindow alloc] initWithWindowNibName:@"DetailWindow"];
detailwindow.mainwindow = self;
}
detailwindow.title = @"First";
[detailwindow addImageToTableView]; //It doesn't have to be named like that. Your choice
}
- (IBAction)btn2Event:(id)sender{
if (!detailwindow) {
detailwindow = [[DetailWindow alloc] initWithWindowNibName:@"DetailWindow"];
detailwindow.mainwindow = self;
}
detailwindow.title = @"Second";
[detailwindow addImageToTableView];
//DetailWindow
- (void)addImageToTableView
{
[super windowDidLoad];
[tableView setBackgroundColor:[NSColor clearColor]];
[tableView setHeaderView:nil];
if([title isEqualToString:@"First"]){
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"MS.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"CVS.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"NS.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"EM.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RES.png"],@"image",@"first image",@"text", nil]];
}
if ([title isEqualToString:@"Second"]) {
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"RS.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"FB.png"],@"image",@"first image",@"text", nil]] ;
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"GT.png"],@"image",@"second image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"SKIN.png"],@"image",@"first image",@"text", nil]];
[arrayController addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSImage imageNamed:@"GP.png"],@"image",@"second image",@"text", nil]];
}
[tableView reloadData];
}
- (IBAction)GoToMainWindow:(id)sender {
[mainwindow showWindow:self];
}
It's definitely not the best code you should have. Just make some changes to the code above and it should be sufficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: directory write access for admin area I have a site, with a small admin area. The admin area needs to write to a directory, but dont want to give write access to that directory to the group or for anybody else (for security reasons). How can I change the owner of the directory (and subdirectories) to the runing user?
A: Your PHP program will run with a fixed user id as far as the operating system is concerned. The OS does not know who is accessing the website.
What you need to do is give permission to write files to the user that PHP is running under, and then trust the PHP code to only act on behalf of who it considers to be admin users.
The best you can (and should) do on the OS level is to lock down other parts of the filesystem, so that an error in the PHP cannot cause anyone to get to files outside of this admin area.
A: There's no such thing as impersonation in PHP, so you'll have to live with one OS user performing all actions, whoever is logged in to your site (guest / user / admin).
A: I'll explain how we manage that on our installations.
We've got two groups - "webmasters" and "uploads". Every web developer is member of both group. Apache is member of "uploads" group only. We have a mask set to 002 and +s flag set on directories.
Our directory permissions look like this:
drwxrwsr-x 3 romans webmaster 4096 Sep 19 16:56 locale
drwxrwsr-x 2 romans upload 4096 Sep 23 17:27 logs
-rw-rw-r-- 1 romans webmaster 136 Sep 19 16:56 main.php
This have worked for us amazingly. Permissions are tight and consistent. Any files PHP will create will belong to "upload" and thus be editable by all web-masters. Any other content by web-masters won't be editable by apache.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tracking auto-renewable subscriptions for magazins I'm trying to implement the auto-renewable subscriptions but something is not really clear for me.
If I have for example a magazine like app and want to track the subscriptions even if they are invalid now, do I have to save the receipts in my app (e.g. Core Data)? I have to track them all because I have to give the user access to old issues even if the subscription is invalid. So either it has the status code 0 oder 21006.
Another question is why Apple uses the 21006 status code for canceled subscriptions that were canceled by Apple because for example somebody mistakenly made a subscription. How can I determine if that happend when I only know that it's invalid now? It could also be invalidated because it is out of the subscription period. I have this Information from the WWDC 2011 Video on iTunes U.
Any help would be appreciated ;-)
A: Apple recommends you store and verify all receipts on your server, not necessarily on the app. To check on the status of someones subscription, just verify any receipt you have stored for that user. (it must be a receipt from the same subscription family) Then Apple will respond with the latest receipt in that subscription. You can use this information to provide the user with all issues of the magazine up until the expiration date of that receipt. You can do this all on the app if you want, but Apple discourages it since you'd have to store your iTunes verification secret in the app itself.
As for your second question, my assumption is that Apple sees refunds as outside-the-norm. So they don't want to make any concessions for it. They don't want to make it easier or automated. That's why you don't get a special code that means 'the user's subscription was cancelled due to refund.' I would hope that this is rare enough that simply providing the magazine articles for free to refunded users, won't make you broke. (and since your receipt verification will show that their account isn't renewing, you don't have to give them new issues).
A: Apple recommends you store and verify all receipts on your server.
(OR)
RMStore delegates transaction persistence and provides two optional reference implementations for storing transactions in the Keychain or in NSUserDefaults. You can implement your transaction, use the reference implementations provided by the library or, in the case of non-consumables and auto-renewable subscriptions, get the transactions directly from the receipt.
-(void) startProductPurchase{
[[RMStore defaultStore] requestProducts:[NSSet setWithArray:_products] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
_productsRequestFinished = YES;
NSLog(@"Product Request Finished");
[self buyApplication:products];
} failure:^(NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Products Request Failed", @"")
message:error.localizedDescription
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil];
[alertView show];
}];
Refresh receipt notifications (iOS 7+ only)
- (void)storeRefreshReceiptFailed:(NSNotification*)notification;
{
NSError *error = notification.rm_storeError;
}
- (void)storeRefreshReceiptFinished:(NSNotification*)notification { }
Receipt verification
RMStore doesn't perform receipt verification by default but provides reference implementations. You can implement your own custom verification or use the reference verificators provided by the library.
Both options are outlined below. For more info, check out the wiki.
Reference verificators
RMStore provides receipt verification via RMStoreAppReceiptVerificator (for iOS 7 or higher) andRMStoreTransactionReceiptVerificator (for iOS 6 or lower). To use any of them, add the corresponding files from RMStore/Optional into your project and set the verificator delegate (receiptVerificator) at startup. For example:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
const BOOL iOS7OrHigher = floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1;
_receiptVerificator = iOS7OrHigher ? [[RMStoreAppReceiptVerificator alloc] init] : [[RMStoreTransactionReceiptVerificator alloc] init];
[RMStore defaultStore].receiptVerificator = _receiptVerificator;
// Your code
return YES;
}
For more details follow the below links.
iOS In-App purchases made easy
A lightweight iOS library for In-App Purchases
Welcome.
Hope it will help you.............
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Controlling embedded windows media player with javascript I have embeded a few videos which I need to display if a link is clicked. so what I am trying to do is click a link and it will display a video, which the user can press play on. If they click another link, the previous video stops and a new video will be displayed. The current HTML structure I have is:
<div>
<ul>
<li><a onclick="ShowVideo(0);" href="javascript:void(0);" class="CalltrackLink">Missed Opportunities</a></li>
<li><a onclick="ShowVideo(1);" href="javascript:void(0);" class="CalltrackLink">Create User</a></li>
</ul>
</div>
<div>
<div id="Video1Div" style="display:none">
<OBJECT id="Video1" width="640" height="480"
STANDBY="Loading Windows Media Player components..."
CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"
type="application/x-oleobject">
<PARAM NAME="URL" VALUE="Video1.mp4" />
<PARAM NAME="SendPlayStateChangeEvents" VALUE="True" />
<PARAM NAME="AutoStart" VALUE="False" />
<PARAM NAME="ShowControls" value="True" />
</OBJECT>
</div>
<div id="Video2Div" style="display:none">
<OBJECT id="Video2" width="640" height="480"
STANDBY="Loading Windows Media Player components..."
CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"
type="application/x-oleobject">
<PARAM NAME="URL" VALUE="Video2.mp4" />
<PARAM NAME="SendPlayStateChangeEvents" VALUE="True" />
<PARAM NAME="AutoStart" VALUE="False" />
<PARAM NAME="ShowControls" value="True" />
</OBJECT>
</div>
</div>
I have the following javascript which I got from various sources on the internet:
function ShowCalltrack(i) {
$('#Video1Div').hide();
$('#Video2Div').hide();
document.getElementById("Video1Div").controls.stop();
document.getElementById("Video2Div").controls.stop();
if(i == 0)
{
$('#Video1Div').show();
}
else if(i == 1)
{
$('#Video2Div').show();
}
}
When I run this I get the error:
Unable to get value of the property 'stop': object is null or undefined
If I remove the offending code then, when the user clicks another link the previous video will still be playing, and you can hear the audio, if the user did not manually stop the video.
I was able to stop the previous video by using this code:
var Video1 = document.getElementById("Video1Div");
var Video1Text = Video1.innerHTML;
Video1.innerHTML = '';
Video1.innerHTML = Video1Text;
this does stop the video from playing, however, the problem with this is, if you go back to a link which you had previously opened the video will resume from where it left off with previously, and I need to to start again from the start.
Any ideas?
A: Your addressing the DIV element, not the control which has ID Video1;
var Wmp = document.getElementById("Video1");
if (Wmp.controls.isAvailable('Stop'))
Wmp.controls.stop();
A: I think it should be where 'S' in stop is capital
document.getElementById("Video1Div").Stop();
Instead of
document.getElementById("Video1Div").controls.stop();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Clicking highlighted Link in Unoredered list Here's a sample of the page I'm working with. The problem is that the user has to click on the link before they are directed to the target page. Is there a way of making the highlighted box for each of those links active and respond to click as well?
My users are complaining that unless they click on the link, clicking in the box does not work.
Any help will be appreciated.
<html>
<head>
</head>
<style type="text/css">
li {
background-color: #F5F2EE;
background-position: left top;
background-repeat: no-repeat;
border: 1px solid #E9E3DD;
height: auto;
width: 100px;
margin-bottom: 4px;
padding: 4px 5px 4px 20px;
}
li a, span {
color: #4B0F19;
text-decoration: none;
}
li:hover {
background-color: #DEB887;
cursor: pointer;
}
</style>
<body>
Hello world
<ul>
<li><a href="http://google.com">Please see this</a></li>
<li><a href="http://msn.com">Another link</a></li>
<li><a href="http://twitter.com">The main link</a></li>
<li><a href="http://bbc.co.uk">fourth link</a></li>
</ul>
</body>
</html>
A: Make the li have 0 padding and margin, the a display: block;, and move the styles to a.
This way the a will expand to fill all the li, and so there will be no area that is part of the menu item but it not filled by the a.
Does this make sense? Do you understand the different approach?
live example: http://jsfiddle.net/NB6Wx/
(You could also capture the click on the li with JavaScript, and trigger a click in the a... but that would be patching a problem that can actually be solved.)
(A bad solution.)
A: Well as far as i understood the problem is <a> is displaying as inline element. you can modify the CSS to make it block element and it will take the whole <li> element.
Like
li a {
display:block;
width:100%;
}
A: You Need to add li a {display:block;} to your CSS.
Here is a Working DEMO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selected content to upperCase? I am just wondering if there is a simple solution already to the problem of turning selected content in tinymce to upperCase letters.
Anyone got a solution?
PS: The upperCase-function is known, but won't solve the tinymce setting of selected content alone.
A: This is what i came up with after some fiddling
// check if a node intersects the given range
rangeIntersectsNode: function (range, node) {
var nodeRange;
if (range.intersectsNode) {
return range.intersectsNode(node);
}
else {
nodeRange = node.ownerDocument.createRange();
try {
nodeRange.selectNode(node);
} catch (e) {
nodeRange.selectNodeContents(node);
}
return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 &&
range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1;
}
},
// Tinymce-Shortcut: (cmd/ctrl + shift +a)
if ( ( (mac && evt.metaKey)|| (!mac && evt.ctrlKey)) && evt.shiftKey && evt.keyCode == 65 ){
if (!ed.selection.isCollapsed()) {
var selection = ed.getWin().getSelection(); // user selection
var range = selection.getRangeAt(0); // erste range
var start = range.startContainer;
var start_offset = range.startOffset;
var end = range.endContainer;
var end_offset = range.endOffset;
// Get all textnodes of the common ancestor
// Check foreach of those textnodes if they are inside the selection
// StartContainer and EndContainer may be partially inside the selection (if textnodes)
// concatenate those textnode parts and make toUppercase the selected part only
// all textnodes inbetween need to become upperCased (the nodeContents)
// Selection needs to be reset afterwards.
var textnodes = t.getTextNodes(range.commonAncestorContainer);
for (var i=0; i<textnodes.length; i++) {
if (t.rangeIntersectsNode(range, textnodes[i])){
if (textnodes[i] == start && textnodes[i] == end) {
var text_content = start.textContent;
text_content = start.textContent.substring(0, start_offset) + text_content.substring(start_offset, end_offset).toUpperCase() + end.textContent.substring(end_offset);
textnodes[i].nodeValue = text_content;
}
else if (textnodes[i] == start){
var text_content = start.textContent.substring(0, start_offset) + start.textContent.substring(start_offset).toUpperCase();
textnodes[i].nodeValue = text_content;
}
else if (textnodes[i] == end){
var text_content = end.textContent.substring(0, end_offset).toUpperCase() + end.textContent.substring(end_offset);
textnodes[i].nodeValue = text_content;
}
else {
// Textnodes between Start- and Endcontainer
textnodes[i].nodeValue = textnodes[i].nodeValue.toUpperCase();
}
}
}
// reset selection
var r = ed.selection.dom.createRng();
r.setStart(start, start_offset);
r.setEnd(end, end_offset);
ed.selection.setRng(r);
evt.preventDefault();
return false;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I take Android Screen shots at the right size for publishing? I'm sorry if this is a daft question but I appear to be missing something.
I am trying to publish my first app and I need at least 2 screen shots. I have taken these using DDMS in eclipse which produces an image 240 by 400. The market requires an image that is at least 320 by 480!
How do I generate a screenshot of this size?
A: Create an emulator from Eclipse with the required screen-size and run your app in the emulator and then use DDMS to take the screenshot.
From Eclipse: Window > Android SDK and AVD Manager. Create a New one. Specify a screen resolution of your desired size.
A: Create an AVD which has an HVGA skin/resolution. HVGA is by default 320x480.
Run your application once more using this AVD and use DDMS to take screen shots.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: problem with closing connection on db with servlet I am trying to run my app with tomcat an the first time that I am debugging/running the app its work fine. but when I am trying to run on second time I am getting error "XJ040".
"Failed to start database 'C:\Documents and Settings\vitaly87\.netbeans- derby\articals' with class loader WebappClassLoader
context: /WebApplication1
delegate: false
repositories:
I thinks the problem because something wrong with closing the connections.Because when I stop my server the problem goes away until the second run.
here the code:
private Connection connect = null;
//private Statement stmt = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public ArrayList<story> stories=new ArrayList<story>();
void getStories(String version) throws SQLException{
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
}catch(ClassNotFoundException e){
System.out.println(e);
}
connect = DriverManager.getConnection( "jdbc:derby:C:\\Documents and Settings\\vitaly87\\.netbeans-derby\\articals", "admin", "admin");
// statement = connect.createStatement();
int ArticlesId= Integer.parseInt(version);
preparedStatement = connect.prepareStatement("SELECT * FROM admin.articles where id>"+ArticlesId+"");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
stories.add(new story(resultSet.getString("title"),resultSet.getString("date"),resultSet.getString("text")));
}
close();
}
//close connection
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
thanks for helping
A: Best always close connections in a finally
connect = DriverManager.getConnection(...)
try
{
// use connection
}
finally
{
try
{
connect.close()
}
catch (SQLException e)
{
// log e
}
}
In your code the connection will not be closed if you have an exception for example in parseInt(version) or exequteQuery()
also in your case I don't think closing of result set is necessary because you are closing the connection anyway.
try {
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
is problematic because 1. if resultSet.close() throws an exception the connection is never closed and 2. you won't see any exceptions thrown in this method. I'd recommend to at least log the catched exceptions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Deploy Excel Workbook Project from VS2010 I have created my first Excel 2007 workbook project in C# using VS2010 that contains a few buttons and carries out a bunch of tasks that all seems to work quite well. I now need it to run on users' machines but I'm not quite sure how to get it to work as the workbook loads but the buttons are inactive and the code doesn't run. I would presume the machine will need the VSTO run-time 3.0 installed, but what else is required?
Thanks in advance for any assistance on this.
A: I figured it out. I published as a ClickOnce application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Polymorphic static const member variables in an ABC? I have a rather strange situation where I would like to be able to define certain constants that a subclass of an ABC can override.
struct A {
static const int a = 20;
virtual int func() = 0;
};
struct B : public A {
static const int a = 3;
int func() { return 5; }
};
struct C : public A {
static const int a = 4;
int func() { return 3; }
};
Unfortunately, if I use A *aPtr = new B, aPtr->a will return 20, instead of 3.
One workaround I see is one-liner functions (along the lines of func in the above example), but the syntax of constants is quite a bit more appropriate for this particularly situation conceptually. Is there a syntactically reasonable way of resolving which constants to use at runtime, where the calling code doesn't need to know anything after initial object creation?
A: Constants, especially static constants, cannot be overriden like you are asking for. You would have to use a virtual function instead:
struct A {
virtual int get_a() { return 20; }
int func() = 0;
};
struct B : public A {
virtual int get_a() { return 3; }
int func() { return 5; }
};
struct C : public A {
virtual int get_a() { return 4; }
int func() { return 3; }
};
Another option would be to use a template for the constant instead:
template< const int a_value = 20 >
struct A {
static const int a = a_value;
int func() = 0;
};
struct B : public A<3> {
int func() { return 5; }
};
struct C : public A<4> {
int func() { return 3; }
};
A: You can get answer from the example itself ! :) Just declare a method like get_a() which is virtual and override the same.
struct A {
static const int a = 20;
virtual int get_a() const { return a; } // <--- for A
};
struct B : public A {
static const int a = 3;
virtual int get_a() const { return a; } // <--- for B
};
struct C : public A {
static const int a = 4;
virtual int get_a() const { return a; } // <--- for C
};
Also note that, only method can be overridden in C++ and not the variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Execute terminal command top from a Cocoa app I want to execute top and get the result in order to know how much memory is used by a process.
First, I want to execute a terminal command. I use code from this question
Execute a terminal command from a Cocoa app
I tried with uptime and it worked flawlessly.
But, when I tried to use top instead of uptime, i get the following error:
Error opening terminal: unknown.
Or, top is in /usr/bin/top, I don't know why it refuses to use it.
Here is my code:
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/top"];
/*NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"foo", @"bar.txt", nil];
[task setArguments: arguments];*/
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
[label setStringValue: string];
[string release];
[task release];
Second question: the thing I am trying to do is to know how much memory is used by Google Chrome.
Because it uses a process for each tab, it's difficult to know how much memeroy in total it uses.
Problem 1: top changes its value every second, how can I get a value?
Problem 2: how can I search in the result of top in order to find only the processes I want (given that I know their names).
Thanks.
A: The problem is that commands like top needs a terminal (= window to interact with) to execute.
This means they need a real window context, because they display the results dynamically in the window (clearing the window, displaying the output of "top" in the whole terminal window, and more important, update the display every N seconds, redrawing the whole terminal window)
So as commands like top need a real "Terminal", this is why, when using top with NSTask, it throw "Error opening terminal".
You may instead check in the manual page of top (man top) if there is an option to avoid dynamic paging of the command and instead output a single shot (without using ncurse and the terminal dynamic display) directly on stdout (maybe try top -l 1 -- Don't have my Mac here to try myself and confirm).
Or a better solution is probably to dig around commands like ps (or others?) instead of top that will give you the same info but directly on stdout instead of as a dynamic display in a terminal.
A: For your first question, use the arguments for top. For example
top -l 1
This will give one set of output.
Hence in the code:
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-l 1", nil];
[task setArguments: arguments];
This will successfully execute the NSTask.
A: For non interactive operations with process information, I would use ps instead of top.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to solve : doesn't work toggle when using linkify class in Android? http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List6.html
Taking Referece of the above link, whenI test sample and I added linkify getView function, does not work toggle.
public View getView(int position, View convertView, ViewGroup parent) {
SpeechView sv;
if (convertView == null) {
sv = new SpeechView(mContext, myTitle[position], myContent[position], mExpanded[position]);
} else {
sv = (SpeechView)convertView;
sv.setTitle(myTitle[position]);
sv.setDialogue(myContent[position]);
sv.setExpanded(mExpanded[position]);
TextView body = (TextView)sv.getChildAt(1);
body.setTextColor(Color.GRAY);
body.setText(myContent[position]);
Linkify.addLinks(body, Linkify.PHONE_NUMBERS);
body.setMovementMethod(LinkMovementMethod.getInstance());
}
TextView title = (TextView)sv.getChildAt(0);
title.setTextColor(Color.LTGRAY);
return sv;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: BufferedReader prepends input I am trying to read from a Socket using BufferedReader as follows
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((line = in.readLine()) != null)
{
}
I input a string, say "AUTH", I am getting the value of line variable as ÿûÿû ÿûÿû'ÿýÿûÿýAUTH
Any solution to this problem?
A: That just means the extra data is in the socket for whatever reason. My guess is that you're using telnet to connect to the server, and that's the telnet protocol negotiation.
Java won't add extra data to what's genuinely there.
A: BufferedReader.readLine() is for input that consists of "lines" make sure that you are providing input correctly. Alternatively, you can define your own terminator and then read input character by character using BufferedReader.read() (use a while loop if you don't know the length of input like while (in.read()!=-1) or something like this).
A:
bufferedReader prepends input
No it doesn't. Something is writing extra input that you aren't expecting. In this case, Telnet. Telnet is a protocol that includes more than just lines of text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Yahoo Mail Api with Java - Can't authorize I try to authorize to yahoo api by example on http://developer.yahoo.com/mail/code/ for JAX-WS. I get an exception:
Exception in thread "main" ua.com.stormlabs.gap.yahoomail.BrowserBasedAuthManager$AuthException: Signature mismatch
at ua.com.stormlabs.gap.yahoomail.BrowserBasedAuthManager.authenticate(BrowserBasedAuthManager.java:59)
at ua.com.stormlabs.gap.yahoomail.JaxWsSample.main(JaxWsSample.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
My code fragment:
String token = "<very_big_token>";
BrowserBasedAuthManager authManager = new BrowserBasedAuthManager(appid, secret);
authManager.setToken(token);
authManager.authenticate();
And authenticate() method:
try {
long time = System.currentTimeMillis() / 1000;
String signatureUrl = "/WSLogin/V1/wspwtoken_login?appid=" +
URLEncoder.encode(this.appid, "UTF-8") + "&token=" + URLEncoder.encode(this.token, "UTF-8") +
"&ts=" + time;
MessageDigest digest = MessageDigest.getInstance("MD5");
String signature = new BigInteger(1, digest.digest((signatureUrl + this.secret).getBytes())).toString(16);
String requestUrl = "https://api.login.yahoo.com" + signatureUrl + "&sig=" + URLEncoder.encode(signature, "UTF-8");
Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new URL(requestUrl).openStream());
if (response.getElementsByTagName("Error").getLength() == 0) {
this.cookie = response.getElementsByTagName("Cookie").item(0).getTextContent();
this.wssid = response.getElementsByTagName("WSSID").item(0).getTextContent();
} else {
throw new AuthException(response.getElementsByTagName("ErrorDescription").item(0).getTextContent());
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new AuthException("Error parsing XML", e);
} catch (IOException e) {
throw new AuthException("Communication failure", e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
Where is a problem?
I also found this forum thread:
http://developer.yahoo.com/forum/Yahoo-Mail-Web-Services-API/-Authorization-failed-error-when-using-Yahoo/1304709008000-9792a6b7-5492-3863-a865-ab36576e399f
but it doesn't help me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Complementary filter (Gyro + accel) with Android Recently I have made some research to use both the accelerometer + Gyroscope to use those senser to track a smartphone without the help of the GPS (see this post)
Indoor Positioning System based on Gyroscope and Accelerometer
For that purpose I will need my orientation (angle (pitch, roll etc..)) so here what i have done so far:
public void onSensorChanged(SensorEvent arg0) {
if (arg0.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
accel[0] = arg0.values[0];
accel[1] = arg0.values[1];
accel[2] = arg0.values[2];
pitch = Math.toDegrees(Math.atan2(accel[1], Math.sqrt(Math.pow(accel[2], 2) + Math.pow(accel[0], 2))));
tv2.setText("Pitch: " + pitch + "\n" + "Roll: " + roll);
} else if (arg0.sensor.getType() == Sensor.TYPE_GYROSCOPE )
{
if (timestamp != 0) {
final float dT = (arg0.timestamp - timestamp) * NS2S;
angle[0] += arg0.values[0] * dT;
filtered_angle[0] = (0.98f) * (filtered_angle[0] + arg0.values[0] * dT) + (0.02f)* (pitch);
}
timestamp = arg0.timestamp;
}
}
Here I'm trying to angle (just for testing) from my accelerometer (pitch), from integration the gyroscope_X trough time filtering it with a complementary filter
filtered_angle[0] = (0.98f) * (filtered_angle[0] + gyro_x * dT) + (0.02f)* (pitch)
with dT begin more or less 0.009 secondes
But I don't know why but my angle are not really accurate...when the device is position flat on the table (Screen facing up)
Pitch (angle fromm accel) = 1.5 (average)
Integrate gyro = 0 to growing (normal it's drifting)
filtered gyro angle = 1.2
and when I lift the phone of 90° (see the screen is facing the wall in front of me)
Pitch (angle fromm accel) = 86 (MAXIMUM)
Integrate gyro = he is out ok its normal
filtered gyro angle = 83 (MAXIMUM)
So the angles never reach 90 ??? Even if I try to lift the phone a bit more...
Why doesn't it going until 90° ? Are my calculation wrong? or is the quality of the sensor crap?
AN other thing that I'm wondering it is that: with Android I don't "read out" the value of the sensor but I'm notified when they change. The problem is that as you see in the code the Accel and Gyro share the same method.... so when I compute the filtered angle I will take the pitch of the accel measure 0.009 seconds before, no ? Is that maybe the source of my problem?
Thank you !
A: I can only repeat myself.
You get position by integrating the linear acceleration twice but the error is horrible. It is useless in practice. In other words, you are trying to solve the impossible.
What you actually can do is to track just the orientation.
Roll, pitch and yaw are evil, do not use them. Check in the video I already recommended, at 38:25.
Here is an excellent tutorial on how to track orientation with gyros and accelerometers.
Similar questions that you might find helpful:
track small movements of iphone with no GPS
What is the real world accuracy of phone accelerometers when used for positioning?
how to calculate phone's movement in the vertical direction from rest?
iOS: Movement Precision in 3D Space
How to use Accelerometer to measure distance for Android Application Development
Distance moved by Accelerometer
How can I find distance traveled with a gyroscope and accelerometer?
A: I wrote a tutorial on the use of the Complementary Filter for oriëntation tracking with gyroscope and accelerometer: http://www.pieter-jan.com/node/11 maybe it can help you.
A: I test your code and found that probably the scale factor is not consistent.
Convert the pitch to 0-pi gives better result.
In my test, the filtered result is ~90 degrees.
pitch = (float) Math.toDegrees(Math.atan2(accel[1], Math.sqrt(Math.pow(accel[2], 2) + Math.pow(accel[0], 2))));
pitch = pitch*PI/180.f;
filtered_angle = weight * (filtered_angle + event.values[0] * dT) + (1.0f-weight)* (pitch);
A: i tried and this will give you angle 90...
filtered_angle = (filtered_angle / 83) * 90;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: problem with between predicate when using an nspredicate ( a between predicate) i had an exception.
there is the code i used:
NSMutableArray *returnedArray=[[[NSMutableArray alloc]init] autorelease];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *objEntity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:objEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"When" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:
@"self.Reunion==%@",reunion];
NSNumber *endOfEtape=[NSNumber numberWithInt:[etape.positionDepart intValue]+[etape.duree intValue]];
NSExpression *s1 = [ NSExpression expressionForConstantValue: etape.positionDepart ];
NSExpression *s2 = [ NSExpression expressionForConstantValue: endOfEtape ];
NSArray *limits = [ NSArray arrayWithObjects: s1, s2, nil ];
NSPredicate *predicate2=[NSPredicate predicateWithFormat: @"self.When BETWEEN %@",limits];
NSPredicate *predicate=[NSCompoundPredicate andPredicateWithSubpredicates:
[NSArray arrayWithObjects:predicate1,predicate2,nil]];
[fetchRequest setPredicate:predicate];
NSArray *notes;
notes=[context executeFetchRequest:fetchRequest error:nil];
[fetchRequest release];
and i had an 'objc_exception_throw' at the line on which i call "executeFetchRequest:" method.
I will be happy if you can help me.
Thanks.
A: Unfortunately, the BETWEEN operand is considered an aggregate function & these aren't supported by CoreData.
See Apple's Documentation
... consider the BETWEEN operator (NSBetweenPredicateOperatorType); its
right hand side is a collection containing two elements. Using just
the Mac OS X v10.4 API, these elements must be constants, as there is
no way to populate them using variable expressions. On Mac OS X v10.4,
it is not possible to create a predicate template to the effect of
date between {$YESTERDAY, $TOMORROW}; instead you must create a new
predicate each time.
Aggregate expressions are not supported by Core Data.
So you'll need to use a predicate like:
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:
@"self.When >= %@ AND self.When <= %@", etape.positionDepart, endOfEtape];
(assuming positionDepart and endOfEtape are of type NSString)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# PropertyGrid - Check if a value is currently beeing edited Is there a simple way to find out if a property grid is currently being edited by the user?
My usecase is the following:
I update the grid data every second. If the user is editing a value, all inputs get lost when my update is called. So what I want to do is only update if the user is not editing something.
A: I don't think there is any official way. However the following piece of code can detect when a grid entry is opened using the builtin text box editor, or the dropdown editor. It does not detect when an entry is opened using the small '...' edit button.
public static bool IsInEditMode(PropertyGrid grid)
{
if (grid == null)
throw new ArgumentNullException("grid");
Control gridView = (Control)grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(grid);
Control edit = (Control)gridView.GetType().GetField("edit", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(gridView);
Control dropDownHolder = (Control)gridView.GetType().GetField("dropDownHolder", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(gridView);
return ((edit != null) && (edit.Visible & edit.Focused)) || ((dropDownHolder != null) && (dropDownHolder.Visible));
}
Of course, since it's based on the grid internal structure, it may change in the future, so, use at your own risk.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asp.net: Multiple iFrame in page I have multiple iframe in my asp.net page. But all this iframe are loading through loop and having same page in all.
These all iframes are loading at last, after loop completes and because of these i am getting last loop data in all iframes.
What to do for this.
This is my main page code where Iframe created in loop:
for (int iCount = 0; iCount < rcChartSubject.Items.Count; iCount++)
{
SetChart();
if (iCount.Equals(1))
{
divRadarChart1.InnerHtml = "";
divRadarChart1.InnerHtml = "<iframe class='RadarSize' src='RadarChart.aspx' frameborder='0' width='680px' height='480px'></iframe>";
divRadar1.Visible = true;
}
else if (iCount.Equals(2))
{
divRadarChart2.InnerHtml = "";
divRadarChart2.InnerHtml = "<iframe class='RadarSize' src='RadarChart.aspx' frameborder='0' width='680px' height='480px'></iframe>";
divRadar2.Visible = true;
}
}
In SetChart() method i am setting global variable for generating chart. But if for loop is for 4 times then iframe page is loading at last 4 times instead of loading in for loop one by one and due to this i am getting last for loop global variables.
And On RadarChart.aspx page I am using those global variables value like below :
protected void Page_Load(object sender, EventArgs e)
{
ltRadar.Text += string.Format("<input type='hidden' name='chxl' value='0:|{0}|1:|{1} |' />", strRadarChartSubjectLabel, strRadarChartAxisValue);
}
A: All Iframe will loads pages at last when your loop completes its execution. So at that time you will have last data in all your variables if you are using global variables and set those variable's value in your iframe page. Better you try with query string where you can pass your all variable's values and set those values in page. So all pages will have seperate data to load.
Try this :
<iframe class='RadarSize' src='RadarChart.aspx?q1=val1&q2=val2' frameborder='0' width='680px' height='480px'></iframe>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript textarea undo redo I'm making a small javascript editor (for a chrome extension) somewhat like the one on SO.
There's a toolbar for manipulation of the text in the textarea. (e.g. surround the selected text with some template)
I was wondering if there is a easy way to achieve this, currently when using the system undo/redo, it messes the text up (I think the system is only keeping track of deltas between edits).
A: If the textarea has focus and its caret is at the correct position,
document.execCommand("insertText", false, "the text to insert");
will insert the text "the text to insert", preserving the browser's native undo stack. (See the work in progress HTML Editing API spec.) Chrome 18 supports this, but I'm unsure of the exact version it was introduced.
A: You can probably simulate textInput events to manipulate the contents of the textarea. The changes made that way are respected by undo/redo, I think (I know they are in Safari)
var element = document.getElementById('someTextarea');
var text = 'This text will be inserted in the textarea';
var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, null, text);
element.dispatchEvent(event); // fire the event on the the textarea
Basically, the text is inserted as though you pasted it yourself. So if something is selected, it'll be be replaced with the text. If there's no selection, the text will be inserted at the caret's position. And undo/redo should work normally (undoing/redoing the entire inserted string in one go), because the browser acts as if you typed/pasted it yourself.
As I said, I know this works like a charm with undo/redo in Safari, so I'd assume it works in Chrome as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: BitmapFactory decode function for Android I encounter problem with .decodeStream function.
File cacheMap = new File(context.getCacheDir(), "test.GIF");
if(cacheMap.exist()){
FileInputStream is = new FileInputStream(cacheMap);
Bitmap bitmap = BitmapFactory.decodeStream(is);
puzzle.add(test);
}else{
//retrieved from server and cache the image
}
The decode function always return null value. And from the internet, I found that in order to display the image, the Bitmap is always set to an ImageView. But what I am doing here is storing it into a ArrayList of Bitmap and display it later on in a Canvas. Can anyone tell me how to get back the image after decoding it?
From this page, it states the following,
public static Bitmap decodeStream (InputStream is)
Decode an input stream into a bitmap. If the input stream is null, or cannot be used to decode a bitmap, the function returns null. The stream's position will be where ever it was after the encoded data was read.
Parameters: The input stream that holds the raw data to be decoded into a bitmap.
Returns:The decoded bitmap, or null if the image data could not be decoded."
Does it means that the image that was cached previously cannot be use to decode it even though I had run the few line of code to cached the image?
cacheMap.createNewFile();
fos = new FileOutputStream(cacheMap);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Does anyone know what is wrong with my code? i have been tackling this issue for days and is driving me crazy!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to create navigation tabs or thumbnails as Firefox or Google chrome? I want to show the important links or services in my website as multiple thumbnails or tabs like what we see in Firefox or Google Chrome when we open it and they show us the latest opened websites.
I think there is a way to do that with CSS or JQuery. I googled about it but I could not be able to find it.
A: Though I'm not quite sure what you're referring to RE. a web browser interface, here's a really simple implementation of jQuery powered tabs: http://jsfiddle.net/i_like_robots/cc324/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I automatically login to youtube using UIWebView (iOS)? I have a question about authentication with UIWebView. I want to login in webview, but without webview interface. Is it possible?
For example I will be using UITextField for user login and password. After the user enters a user name and password, the program will automatically log in and save the user's session.
Is it possible to login without providing UIWebView interface?
I was able to parse the html page, but if the html changes, I can't correctly parse the new html.
A: Youtube has - like most google products - a pretty well documented API to access nearly everything on their site through API calls.
Check http://code.google.com/intl/en/apis/youtube/overview.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Asp.net GridView Headertext aligment problem with the Column text In my GridView the Headertext is aligned to left and itemstyle is aligned to left but the header is not exactly aligned to left. It leaves some space before.
Saml code: <asp:BoundField DataField="COMPANY_TYPE" SortExpression="Company_Type" HeaderText="Company Type" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%"/>
A: It's possible that your padding on the <th> elements in the header is larger than the <td> elements in the item rows. Use Firebug (or equivalent) to check if something in your css is affecting it. I would also look into the source of the page to verify that there is not any extra whitespace or anything before your column headers.
A: In the column section where you set the fields add this
ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left"
for example:
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left"/>
A: Try
.HeaderStyle {
text-align: Left
}
<asp:GridView runat="server" ID="TestAlign" ShowFooter="True"
DataSourceID="testDataSource" Width="600"
HeaderStyle-CssClass="HeaderStyle">
<Columns>
<asp:BoundField DataField="left" HeaderText="-left-"
HeaderStyle-CssClass="HeaderStyle" />
</Columns>
</asp:GridView>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery how to prevent mouseenter triggering when page loads with cursor hovering element I have an element on my page with a mouseenter event bound to it which changes the dimensions of a child image.
It works just as I want, however if you hit the page with your cursor hovering where the div will be, it triggers as soon as it loads - this is undesired, I want it to do nothing until a mouse cursor actualy enters the div rather than just being there to start with.
I've tried knocking up an example on jsfiddle but the page loads too quickly for me to get the cursor in the right place :(
One possibility is putting the bind method calls in a timeout so that it takes a second to bind the event, but the problem will still happen if the user leaves their cursor over my div.
Any ideas?
Using jQuery 1.6.2
A: Hm. Its only idea.
var mouse_already_there = false;
var event_set = false;
$(document).ready(function() {
$(item).hover(function(){
if(!event_set) { mouse_already_there = true; }
}, function(){
if(!event_set) { mouse_already_there = false; }
});
if(mouse_already_there) {
//do nothing
} else {
event_set = true;
//set event
}
});
A: My working solution is:
var mouseenterno = 0;
$('.selector').on('mouseenter', function() {
//your code here
mouseenterno = mouseenterno + 1;
});
$('.selector').on('mouseleave', function() {
if (mouseenterno >= 1){
//your code here
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Building wsp from post-build event command line What is the command for building WSP from post-build event command line?
I'm adding one more image so that you can understand my exact requirement.
A: You can build a WSP by using MSBuild. Each SharePoint project is build with the parameter
IsPackaging=True
By adding this parameter to the msbuild command you can ensure that all WSPs will be created.
A: You will have to depend on external tools like makecab.exe or WSPBuilder.
http://www.developerfusion.com/community/blog-entry/8390127/tfs-teambuild-and-sharepoint-wsp-deployment-and-any-post-build-events-for-that-matter/
http://www.fftf.org/news/Jul07feed/SharePoint_Solution_Deployment_Handy_PostBuild_Events.rss.html
A: I found the answer from here and it works for both SharePoint 2007 and 2010.
call "C:\Program Files\WSPTools\WSPBuilderExtensions\WSPBuilder.exe" -ProjectPath $(SolutionDir) -OutputPath $(SolutionDir) -SolutionPath $(SolutionDir)
A: This seems to be VS2010.
If you choose the project template to be a SharePoint 2010 project then you will find items in the context menu that are related to SharePoint. If you choose deploy, it will create the wsp package automatically and deploy it to the server.
A: To force Visual Studio to create a wsp on post build for SharePoint solutions, add these properties to the project xml. If you already have a post build event defined, just add the two inner tags to the existing property group. Visual Studio will create the wsp in the configured location; Release or Debug.
To edit the project xml unload the project in visual studio then right-click on the project and select edit.
<PropertyGroup>
<IsDebugging>False</IsDebugging>
<PostBuildEventDependsOn>$(PostBuildEventDependsOn);CreatePackage</PostBuildEventDependsOn>
</PropertyGroup>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to add method i.e get/post in a form using jquery I am using spring mvc in my project.
<form:form method="" action="" id="myform" commandName="users">
I have this form, want to add action a runtime using jquery. how can I do it
Using javascript I was doing as which worked fine
document.getElementById("myform").action = "changePWD"
document.getElementById("myform").method="POST";
A: Using jQuery:
$('#myform').attr('action','changePWD').attr('method','POST');
Why would you not do it with Javascript though if that is working fine as you say?
A: $('#myform').attr({
action: 'changePWD',
method: 'POST'
});
But I agree with Kokos, why fix what's not broken?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to open multiple instances of a program in Linux Say for example, to open multiple instances of gedit editor I wrote a shell script like this-
gedit&
gedit&
gedit&
gedit&
But after I ran my shell script ./example.sh, I can find only one instance of gedit! I've even used the & operator, so that the shell doesn't wait for one instance to finish. Still I cannot see four instances of gedit.
Also I tried directly from the command prompt. If I just enter gedit& on the command line, it showed 1906 ( this is the PID of the newly created gedit process ), started one new gedit instance and returned to prompt again. When I typed gedit& on the command line, it showed 1909 this time, but no new instance of gedit! And I couldn't find any process with PID 1909 in the System Monitor too. Where did this new process go away?
Is the happening specific to gedit? If so, what is the generic behavior when creating multiple instances of a program?
A: It is specific to gedit. You are likely looking for gedit --new-window &.
From man gedit:
--new-window
Create a new toplevel window in an existing instance of gedit.
A: I came here, trying to start multiple instances of audacious.
Allowing only one instance is actually harder to implement, because the program needs to find and communicate with the instance already running. This is done via D-Bus. In order to prevent communication with the already started instance you can run the program in another D-Bus session:
nohup dbus-run-session audacious &
nohup dbus-run-session audacious &
Note: nohup will keep the program running even if the terminal is to be closed.
This method should also work for other programs which do not let the user choose between multiple instance vs. one instance.
Beware that this might introduce bugs, if multiple instances are accessing the same configuration files.
Tested with xfce 4.14.1 and dbus 1.12.20
For Scite:
scite -check.if.already.open=false &
A word of caution:
If you, like me, have your system running for multiple months and have edited some of your shortcuts or aliases to open with this hack, then after a while some programs will not start anymore because there are already too many open D-Bus session. In this case you have to kill the started D-Bus sessions, which do not close when the started program closes. The other way around, killing the D-Bus session, will also kill the opened program, so use with care! For me personally, I have some long running autostarted programs which I want to keep open (firefox), so I kill all but the first 10 D-Bus sessions with this:
for pid in $( ps --sort start_time -aux | grep dbus-daemon | tail +10 | awk '{ print $2; }' ); do kill $pid; done
The cleanest solution would be to write a launcher script which waits for the program to finish and then closes the opened D-Bus sessions. But this is a bit more difficult than it seems because it is hard to find the PID of the corresponding D-Bus session.
P.S.: I also used this hack because there seems to be some program on my system which, after a while, slows down the system's default file open dialog to take multiple minutes if not longer to open! Programs then seem to hang when trying to save or open files. A new D-Bus sessions seems to fix this for some reason. While writing this, I found that pkill gvfsd-trash also works and that it may have been this bug. So until this gets shipped, I guess I'll add pkill gvfsd-trash to my crontab.
A: This seems specific to gedit, perhaps there's some option to turn off the check for a running instance.
A: Looks like gedit is first looking for a running instance and simply ignores further start-requests (just a wild guess). But the manual page says, that you can open another window:
--new-window
Create a new toplevel window in an existing instance of gedit.
That wouldn't exactly solve your problem, but maybe that's what you were looking for in the first place.
Good luck,
Alex.
A: Using this in a script. I've found that it does what I need it to:
#!/bin/bash
xterm -e "gedit; bash" &disown
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Local android service receive data from local web page I have offline web page on android tablet.
Is it possible to write android service which will get data from web page when user insert data and submit it, and when android service receive data than it has to save it in text file or db.
Everything is in offline local mode.
A: You should be carful when using the word Service besides android. People might get a worng idea of what you're taliking about because it has a special meaning for android.
Because a local webpage will submit a post request to a certain URL and your device is actually not the webserver you will fail with that. But you can accomplish your task with a javascript/JSON bridge to your local HTML. See this post to see how.
The idea is to use a click handler which collects the needed data and returns it to the webview by the javascript bridge instead submiting the data to a from submit URL. From java side to WebView you can respond with an JSON object.
To accomplish this you need to have fundamental knowledge about HTML and javascript and understand the use of a WebView.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how i can insert a javascript code inside visual web jsf page in netbeans? how i can insert a javascript code inside visual web jsf page in netbeans 6.5.1 ?
<webuijsf:head id="head1"> <script type="text/javascript" src="ddaccordion.js"></script> </weuijsf:head>
it doesn't work however it works fine inside dreamweaver or visual studio
so i tried to make an html file and write this code inside it and link it to jsf file also it doesn't work
<head> <script type="text/javascript" src="ddaccordion.js"> </script> </head>
so any help pls
A: Put <script...> in the <h:head> tag:
<h:head>
<script type="text/javascript" src="ddaccordion.js"> </script>
</h:head>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with Apple Push Notification service I tried to set the push notification on my app iPhone.
I created the certificate and then I used the apns php library on my web server to create the notify, but this is the error:
Warning: stream_socket_client() [function.stream-socket-client]: SSL operation failed with code 1. OpenSSL Error messages: error:14094414:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate revoked
A: It means that your apns certificate has been revoked. You can regenerate a new certificate and then try again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple select statements in a stored procedure sql server 2005 Is it possible to add multiple select statements in a single stored procedure . The select statements are getting data from same tables. If yes, could anybody provide an example in adding multiple select statements, which retrieve data from different tables in a stored procedure.
Actually I am having list like state,city, university,college,department in my maintenance (same) table. As per the query i want execute the query and populate the value in my drop down list .
A: This proc will return mutiple result sets to the client
CREATE PROC whatever
AS
SELECT col1, col2 FROM Table1
SELECT col3, col4, col5 FROM Table2
SELECT col1, col3 FROM Table3
GO
You can use DataAdaptor.Fill and then you can DataTable(0), DataTable(1) and DataTable(2)
Or iterate over them with DataReader.NextResult
If you have "all data in one table" then you have a bad design: sql performance of a lookup table
A: Not sure what you are trying to do exactly, but for example this would work:
select id,name from table1 where code<=500
union all
select id,name from table2 where code >=1000 and code <=2000
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: from Plain text generate encrypted text of same legnth I want to create a java program in which I will give plain text , a key then the output should be of same length as of plain text. Using the same key I will decrypt the encrypted text. So please suggest me how to proceed?
Thanks.
A: What sort of encryption scheme are you wanting? The Vigenère cipher will give you ciphertext of the same length as your plaintext, but if the key is not random the ciphertext will be vulnerable to various frequency attacks such as the Kasiski examination.
What are you trying to achieve?
A: Using a stream cipher like RC4 or a block cipher like AES in a counter mode can do what you want. However, these still require an a random IV for each message so you have to somehow manage that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Creating a aggregation function on Oracle 10g returning unhelpful error I've got some help and was led to this page and this explanation, which should contain a efficient way to aggregate things.
It suggest to use de COLLECT function and some other custom things. I'm trying get along with it, but the error messages (plus my newbness) aren't the most helpful.
The function:
CREATE OR REPLACE TYPE t_varchar2_tab AS TABLE OF VARCHAR2(4000);
CREATE OR REPLACE FUNCTION tab_to_string (
p_varchar2_tab IN t_varchar2_tab,
p_delimiter IN VARCHAR2 DEFAULT ',')
RETURN VARCHAR2 IS
l_string VARCHAR2(32767);
BEGIN
FOR i IN p_varchar2_tab.FIRST .. p_varchar2_tab.LAST LOOP
IF i != p_varchar2_tab.FIRST THEN
l_string := l_string || p_delimiter;
END IF;
l_string := l_string || p_varchar2_tab(i);
END LOOP;
RETURN l_string;
END tab_to_string;
And my tests:
with my_table as
(
select 'user1' as usrid, 'ab' as prodcode from dual union
select 'user1' as usrid, 'bb' as prodcode from dual union
select 'user1' as usrid, 'a' as prodcode from dual union
select 'user2' as usrid, 'db' as prodcode from dual union
select 'user2' as usrid, 'b' as prodcode from dual union
select 'user2' as usrid, 'bfdd' as prodcode from dual
)
select
usrid,
tab_to_string(CAST(COLLECT(prodcode) AS t_varchar2_tab)) AS codes
from
my_table
group by
usrid
Would give me an ORA-06553: PLS-306: wrong number or types of arguments in call to 'TAB_TO_STRING'
This is pretty much copy-and-past from the source I mention in the beginning, and the function makes sense for me.. what am I missing?
thanks!
[EDIT] Codo has figured that one of the problems was Oracle understanding the 'a' as a char, rather than varchar. This brought the question to the real issue. I updated it so it is focused.
A: For reasons I don't really understand, Oracle thinks that the PRODCODE column of your synthetic table isn't a VARCHAR2 column. If you slightly modify one of the PRODCODE values, it'll work:
with my_table as
(
select 'user1' as usrid, 'ab' as prodcode from dual union
select 'user1' as usrid, 'b' as prodcode from dual union
select 'user1' as usrid, 'c' as prodcode from dual union
select 'user2' as usrid, 'd' as prodcode from dual union
select 'user2' as usrid, 'e' as prodcode from dual union
select 'user2' as usrid, 'f' as prodcode from dual
)
select
usrid,
tab_to_string(CAST(COLLECT(prodcode) AS t_varchar2_tab)) AS codes
from
my_table
group by
usrid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Mix and playback multiple tracks Actionscript 3 I am creating a sound mixer in AS3. I have several sound samples that a user can choose from to create their own track. The mixer will "mixdown" a max of 4 tracks and playback the "mixed" track on demand. I'm having trouble getting the sounds to playback in sync. I'm new to working with sound in flash and wondering what I'm missing... Here is the "mix" function at present:
function mixIt(e:MouseEvent) {
if (isPlaying) {
channel1.stop();
}
var mChannel1:SoundChannel = new SoundChannel;
var mChannel2:SoundChannel = new SoundChannel;
var tUrl1:URLRequest = new URLRequest(trackChoice1);
var tUrl2:URLRequest = new URLRequest(trackChoice2);
var s1:Sound = new Sound();
var s2:Sound = new Sound();
var s1Done:Boolean = false;
var s2Done:Boolean = false;
s1.addEventListener(Event.COMPLETE, onSoundLoaded1);
s2.addEventListener(Event.COMPLETE, onSoundLoaded2);
s1.load(tUrl1);
s2.load(tUrl2);
function onSoundLoaded1(e:Event) {
s1Done = true;
if (s2Done) {
playMix()
}
}
function onSoundLoaded2(e:Event) {
s2Done = true;
if (s1Done) {
trace("s2 Done")
playMix()
}
}
function playMix(){
mChannel1 = s1.play(0, 2);
mChannel2 = s2.play(0, 2);
//trace("MIXING TRACKS :" + tUrl1 + " + " + tUrl2);
}
}
A: try mixing sounds as byte arrays using Sound.extract() and SampleDataEvent
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problem with deserialization xml to objects - unwanted split by special chars I try to deserialize xml to objects, and i met a problem with encoding of various items in xml tree.
XML example:
<?xml version="1.0" encoding="utf-8"?>
<results>
<FlightTravel>
<QuantityOfPassengers>6</QuantityOfPassengers>
<Id>N5GWXM</Id>
<InsuranceId>330992</InsuranceId>
<TotalTime>3h 00m</TotalTime>
<TransactionPrice>540.00</TransactionPrice>
<AdditionalPrice>0</AdditionalPrice>
<InsurancePrice>226.56</InsurancePrice>
<TotalPrice>9561.31</TotalPrice>
<CompanyName>XXXXX</CompanyName>
<TaxID>111-11-11-111</TaxID>
<InvoiceStreet>Jagiellońska</InvoiceStreet>
<InvoiceHouseNo>8</InvoiceHouseNo>
<InvoiceZipCode>Jagiellońska</InvoiceZipCode>
<InvoiceCityName>Warszawa</InvoiceCityName>
<PayerStreet>Jagiellońska</PayerStreet>
<PayerHouseNo>8</PayerHouseNo>
<PayerZipCode>11-111</PayerZipCode>
<PayerCityName>Warszawa</PayerCityName>
<PayerEmail>no-reply@xxxx.pl</PayerEmail>
<PayerPhone>123123123</PayerPhone>
<Segments>
<Segment0>
<DepartureAirport>WAW</DepartureAirport>
<DepartureDate>śr. 06 lip</DepartureDate>
<DepartureTime>07:50</DepartureTime>
<ArrivalAirport>VIE</ArrivalAirport>
<ArrivalDate>śr. 06 lip</ArrivalDate>
<ArrivalTime>09:15</ArrivalTime>
</Segment0>
<Segment1>
<DepartureAirport>VIE</DepartureAirport>
<DepartureDate>śr. 06 lip</DepartureDate>
<DepartureTime>10:00</DepartureTime>
<ArrivalAirport>SZG</ArrivalAirport>
<ArrivalDate>śr. 06 lip</ArrivalDate>
<ArrivalTime>10:50</ArrivalTime>
</Segment1>
</Segments>
</FlightTravel>
</results>
XML Deserialization function in python:
# -*- coding: utf-8 -*-
from lxml import etree
import codecs
class TitleTarget(object):
def __init__(self):
self.text = []
def start(self, tag, attrib):
self.is_title = True #if tag == 'Title' else False
def end(self, tag):
pass
def data(self, data):
if self.is_title:
self.text.append(data)
def close(self):
return self.text
parser = etree.XMLParser(target = TitleTarget())
infile = 'Flights.xml'
results = etree.parse(infile, parser)
out = open('wynik.txt', 'w')
out.write('\n'.join(results))
out.close()
Output:
['6', 'N5GWXM', '330992', '3h 00m', '540.00 ', '0', '226.56', '9561.31', 'XXXXX', '111-11-11-111', 'Jagiello', 'ń', 'ska', '8', 'Jagiello', 'ń', 'ska', 'Warszawa', 'Jagiello', 'ń', 'ska', '8', '11-111', 'Warszawa', 'no-reply@xxxx.pl', '123123123', 'WAW', 'ś', 'r. 06 lip', '07:50', 'VIE', 'ś', 'r. 06 lip', '09:15', 'VIE', 'ś', 'r. 06 lip', '10:00', 'SZG', 'ś', 'r. 06 lip', '10:50']
In item 'Jagiellońska' is special char 'ń'. When parser appending data to array then char 'ń' is some king of split character and my question is why this is happening? Rest of items are appending to array correctly. In item 'śr 06.lip' is exactly the same situation.
A: The problem is that the data method of your target class may be called more than once per element. This may happen if the feeder crosses a block boundary, for example. Looks like it can also happen when it hits a non-ASCII character. This is ancient legend. I can't find where this is documented. However if you change your target class to something like the following, it will work. I have tested it on your data.
class TitleTarget(object):
def __init__(self):
self.text = []
def start(self, tag, attrib):
self.is_title = True #if tag == 'Title' else False
if self.is_title:
self.text.append(u'')
def end(self, tag):
pass
def data(self, data):
if self.is_title:
self.text[-1] += data
def close(self):
return self.text
To get a better grasp of what your output is like, do print repr(results) after the parse call. You should now see such pieces of unsplit text as
u'Jagiello\u0144ska\n '
u'\u015br. 06 lip\n '
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why do my linked lists appear to point to same thing after clone? I noticed that when I first have
list2 = (LinkedList)list.clone();
I could operate on both lists independently eg. list2.remove(1)
But later when I do
list = (LinkedList)list2.clone();
when I do list.remove(1) list2 is affected too. Why is that?
UPDATE
My code http://pastie.org/2598096
Example input:
4 8
1 5 2 3
4
I 1 2
R 2
C 1 10
I 4 2
> javac Main.java && java Main < ./input/betterlist0.in
[ 1, 5, 2, 3, ] -- [ 2, 1, 5, 2, 3, ] // list2 can be modified from list1 independently
YES9 8
[ 2, 5, 2, 3, ] -- [ 2, 5, 2, 3, ] // now when list2 is modified, list1 gets modified too.
I think its because super.clone() makes a shallow copy. But why then did it work the 1st time?
A: In general you should write your own clone() function to achieve the deep copy you want. because java is not guaranteeing this.
Here is a quote from wikipedia:
The default implementation of Object.clone() performs a shallow copy. When a class desires a deep copy or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.
And I think this is also worth reading.
A: LinkedList l1 = new LinkedList();
l1.add("A");l1.add("B");
LinkedList l2 = (LinkedList)l1.clone();
out("l2 after clone: "+l2.size());
l2.remove(0);
out("l2 after remove: "+l2.size());
l1 = (LinkedList)l2.clone();
out("l1 cloned from l2: "+l1.size());
l1.remove(0);
out("l1 after remove :"+l1.size());
out("l2 after l1's remove:"+l2.size());
that makes:
l2 after clone: 2
l2 after remove: 1
l1 cloned from l2: 1
l1 after remove :0
l2 after l1's remove:1
that demonstrates
.clone
is working as expected.
A:
when I do list.remove(1) list2 is affected too
No it isn't. Your observations are at fault here.
A: Here's also what might be happening.
Basically, the list is probably not holding the actual object data, but references to them. In other words, it's keeping track of the pointers (a.k.a. memory addresses) to those objects.
In English, this is like saying "These houses are at these addresses", and you are storing the list of addresses in a phone book. The clone() might not be copying the house, but it might be copying the phone book
There's also the chance that someone might be storing "The phone book is stored on shelf B", writing it down, and handing someone else a paper saying that "The phone book is stored on shelf B"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android :Changing tabs on Fling Gesture Event- not working for ListActivity inside TabActivity I have a tabactivity with three tabs. One of the tab contains ListActivity and two others contains simple Activity. And i have implemented OnGestureListener to change the tab on fling event.
The onTouchEvent and 'onFling' events are not being called for the tab with ListActivity . But working fine for Simple Activity( without lists).
Here is my Code :
Main Activity class :
public class GestureTest extends TabActivity implements OnGestureListener {
private TabHost tabHost;
private GestureDetector gestureScanner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testmainlayoutforgesture);
gestureScanner = new GestureDetector(this);
addTabs();
}
private void addTabs() {
Intent i1 = new Intent().setClass(this, SimpleListActivity.class);
Intent i2 = new Intent().setClass(this, SimpleActivity.class);
Intent i3 = new Intent().setClass(this, SimpleActivity.class);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("First").setIndicator("First").setContent(i1));
tabHost.addTab(tabHost.newTabSpec("Second").setIndicator("Second").setContent(i2));
tabHost.addTab(tabHost.newTabSpec("Third").setIndicator("Third").setContent(i3));
tabHost.setCurrentTab(0);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureScanner.onTouchEvent(me);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float dispX = e2.getX() - e1.getX();
float dispY = e2.getY() - e1.getY();
if (Math.abs(dispX) >= 200 && Math.abs(dispY) <= 100) {
// swipe ok
if (dispX > 0) {
// L-R swipe
System.out.println("L-R swipe");
changeLtoR();
} else {
// R-L swipe
System.out.println("R-L swipe");
}
}
return true;
}
private void changeLtoR() {
int curTab = tabHost.getCurrentTab();
int nextTab = ((curTab + 1) % 3);
tabHost.setCurrentTab(nextTab);
}
//other interface methods
}
SimpleListActivity.java:
public class SimpleListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> list1Strings = new ArrayList<String>();
list1Strings.add("List 11");
list1Strings.add("List 12");
list1Strings.add("List 13");
list1Strings.add("List 14");
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, list1Strings));
}
}
SimpleActivity.java :
public class SimpleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simplelayouttest);
}
}
testmainlayoutforgesture.xml layout :
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
</LinearLayout>
</TabHost>
simplelayouttest.xml layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/helloTv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello Hello" />
</LinearLayout>
I could not figure out what is wrong here.
A: Try adding this to your TabActivity:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (gestureScanner != null) {
if (gestureScanner.onTouchEvent(ev))
return true;
}
return super.dispatchTouchEvent(ev);
}
Implementing this, will tell your device that the gestureScanner consumed the onFling event.
EDIT Again:
You will also need to change your onFling-method a bit to this:
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// Check movement along the Y-axis. If it exceeds SWIPE_MAX_OFF_PATH, then dismiss the swipe.
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// Swipe from right to left.
// The swipe needs to exceed a certain distance (SWIPE_MIN_DISTANCE) and a certain velocity (SWIPE_THRESHOLD_VELOCITY).
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
// do stuff
return true;
}
// Swipe from left to right.
// The swipe needs to exceed a certain distance (SWIPE_MIN_DISTANCE) and a certain velocity (SWIPE_THRESHOLD_VELOCITY).
if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
// do stuff
return true;
}
return false;
}
}
Another possibility could be if your ListView does not fill the screen and the 'empty' space is not clickable and you fling on this 'empty' space the touch event won't be registered and dispatched. Does it work if you fling on top of the ListView?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XMPP (Jabber) windows client with SSO features I'k looking for a xmpp windows client with SSO feature in a Windows Domain.
I've tried pandion but it doens't work.
A: You're likely looking for Kerberos 5 support. The GSSAPI SASL mechanism is how this works on the wire. I think Psi implements GSSAPI. Setting this up on the server side can be hard, so please don't assume that if it doesn't work the first time it is the client's fault.
A: Spark + Openfire (http://community.igniterealtime.org/docs/DOC-1362)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Date format of sql from regional settings I am reading date from the sql table. In sql table date time in the format how client set in regional format. Because of this reading date and splitting that and taking to a format what we want is becoming difficult. Is there any way to restrict sql date format from regional settings date format (means sql not suppose to take regional settings date format).
Now i got the answer:
string Date = Convert.ToDateTime(dateTimeString).ToString("yyyy-MM-dd");
string time = Convert.ToDateTime(dateTimeString).ToString("hh:mm:ss");
//dateTimeString--->my dateTime value from sql database
A: If you write datetime fields using ISO 8601 there should be no problem.
That way, dates get formatted like "2011-09-26T12:04:00", so there's no misunderstanding possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error $mainframe->set() in joomla 1.7 I have code in joomla 1.5
global $mainframe;
$html = "web solution";
$mainframe->set('JComponentTitle', $html);
Use in joomla 1.5 is OK
But when using joomla 1.7 is error Call to a member function set() on a non-object in ...
I want help for this idea
A: Try this:
global $app;
$html = "web solution";
$app->set('JComponentTitle', $html);
A: I think the using of global objects in joomla 1.6+ is deprecated. Instead of using $mainframe and global $app, I'd use something like :
$app = & JFactory::getApplication();
$html = 'web solution';
$app->set('JComponentTitle', $html);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problem with "count_all_results" and "where" with Active Record in CodeIgniter In CodeIngiter User guide ,they said the following code:
$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status);
// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
It means when I wanna select some thing from database by active record,I should use where method and it will do it by replace AND between fields.
now I wanna to make login page,I do this:public function True_login($username = '',$password = '')
{
$this->db->flush_cache();
$this->db->where('username',$username);
$this->db->where('password',$password);
$count = $this->db->count_all_results('PM_ADMIN_LIST');
if ($count === 1)
{
return TRUE;
}
else
{
return FALSE;
}
}
but it will return TRUE if username=$username OR password = $password .
if one of the username or password will be found in table(and $count === 1 it will return TRUE)
where is my prbolem and how should I solve it?
A: Simply use->
$this->db->count_all();
instead of
$this->db->count_all_results();
problem resolved.......
A: $this->db->count_all_results('PM_ADMIN_LIST');
is returning the number of rows in the table and ignorning the restrictors above it.
Try:-
$this->db->where('username',$username);
$this->db->where('password',$password);
$this->db->from('PM_ADMIN_LIST');
$count = $this->db->count_all_results();
Also, put some debug in - if you knew what the value of $count was then it may have helped you work out that the Active Record query was wrong rather than thinking it was doing an OR instead of an AND.
A: Add second parameter with value false in count_all_results() function.
$this->db->count_all_results('PM_ADMIN_LIST',FALSE);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Buffering videos leads to page loading slow I am using flowplayer to play videos. I need to show first frame of every videos on my page. so I put the settings as autoPlay as false, and autoBuffering as true. So what happens is every videos (more than 10 videos) are buffering simultaneously and it leads the page loading very slow.
How can I overcome this? Is there any way to stop the buffering after I got the first frame. I am using .net 3.5. Any inbuild feature in .net for this. videos will be only .flv and .mp4. The files will be from online also.
A: Check out this forum post and the responses there for some ideas of how to stop the buffering using javascript. You'll have to read through all the responses, because the common solution is mainly geared towards only ONE video on the page. But it may point you in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php - get full image path from server how can i get image path on server using "browse" button in a html form, select the file (double clicking the file returning its full path), and put the result image path into variable $img_path?
let's say the image dir in my server is /images, i'd like to get path of "foo.jpg", the full image path should be "/images/foo.jpg"
so, all i have to do is :
1. create form which contain "browse" button or something like that - that allow me to explore "images" directory at my server
2. exploring "images" dir, all files listed and clickable, locate "foo.jpg", select it, and voila, i get the image path "/images/foo.jpg"
any lil' help would be appreciated..
Thanks
@CodeCaster thanks for your respond.. but this is all i want (at least closer) :
<?php
$dir = '/images';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
echo $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
?>
A: You could use dir:
echo "<ul>";
$d = dir("images");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo "<li><a href=\"/images/" . $entry . "\">" . $entry . "</a></li>";
}
$d->close();
echo "</ul>";
A: using "dir" you can achieve your goal.
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Identifying a String within a file such that it starts and ends with a quote i am writing a scheme interpreter in Java.
Files contain many lines/words
This is one of the lines in the file:
"xx'x v \"yyyyy\"... eee dddd ffff\\\n"
I have to identify it such that the whole string is returned,
but in my program, it only reads "xx'x v \"
and then reads the other words from " to \"
Any help is highly appreciated
String text = "";
int nextString = t;
while(!isString(nextString)){
nextString = reader.read();
int next = peek();
if (nextString == '\\' && next =='"'){
nextString = reader.read();
if(Character.isSpaceChar(next)){
text+=" ";
}
}
text += (char) nextString;
}
return new StringToken(text, lineNumber);
}
A: if you don't want to use regular expression maybe you can use:
String text = "";
int nextString = t;
while(!isString(nextString)){
nextString = reader.read();
int next = peek();
if (nextString == '\\' && next =='"'){
nextString = reader.read();
text += (char) nextString;
nextString = reader.read();
}
if(Character.isSpaceChar(next)){
text+=" ";
}
text += (char) nextString;
}
return new StringToken(text, lineNumber);
}
A: Using regular expressions, for example:
[^\\]\"(.*[^\\])\"
This will only work if the first " is not the first character of the string. The string you want is the one enclosed between (). For example, if I pass \"garbage"Hello\"foo", it will get Hello\"foo (this is what you want if I understood right).
I actually don't know how regex's Java classes handle () in regexs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC3 Html.HiddenFor(Model => Model.Id) not passing back to Controller I have created a strongly typed MVC3 Razor view using the scaffolding code.
The model is a POCO with a base type of PersistentEntity which defines a property called Created, Updated and Id.
Id is an int, Created and Updated are DateTime.
I am using Html.HiddenFor to create the hidden field on the view.
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Created)
@Html.HiddenFor(model => model.Updated)
On the page, the hidden input is being rendered properly, with the Id being set in the value.
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="12">
However when the page is submitted to the controller [HttpPost]Edit(Model model) the Id property is always 0. Created and Updated are correctly populated with the values from the View.
This should be 12 in the case of the example in this post. What is going wrong?
I am aware that I can change the method signature to [HttpPost]Edit(int personID, Person model) as the personID is in the get string, however why does the model not get populated with the hidden field?
Update
The problem was that the setter on PersistentEntity was protected, ASP could not set the property, and swallowed it. Changing this to public has solved the problem.
public abstract class PersistentEntity
{
public virtual int Id { get; protected set; }
public virtual DateTime Created { get; set; }
public virtual DateTime Updated { get; set; }
}
A: public virtual int Id { get; protected set; }
protected set; <!-- That's your problem. You need a public setter if you want the default model binder to be able to assign the value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Does rails and other gems install documentation anywhere when you install them? And where can I find it? I'm running OSX.
In addition I have to do a lot of work offline while travelling so if anyone can offer any tips for downloadable documentation please let me know.
A: If you have installed your gems the "normal" way, they install rdoc documentation.
Just run gem server in your console and go to http://localhost:8808 in your browser. There you'll find all available Gems and the RDoc documentation
A: http://railsapi.com provides you to download offline documentation for:
*
*Rails 2.2.2, 2.3.8, 3.0.8
*Ruby 1.8, 1.9.2
*Authlogic
*AWS-S3
*EventMachine
*Haml
*Hpricot
*Nokogiri
*Rack
*Rspec
*Sinatra
The downloadable file has wonderful jQuery search functionality, so it's pretty useful
A: @klaustopher's answer didn't work for me directly, so here is how I got this to work for the rspec-expectations gem:
*
*Install gem documentation by either
*
*using the --rdoc flag: gem install --rdoc rspec-expectations
*or by installing rdocs for all gems: gem rdoc --all
*Run rdoc server.
gem server
*Go to http://localhost:8808 in my browser.
Caveat: at a first glance the rdoc for rspec-expectations is pretty useless. I bet there is a better way to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Json.Net - Serialize property name without quotes I'm trying to get Json.Net to serialise a property name without quote marks, and finding it difficult to locate documentation on Google. How can I do this?
It's in a very small part of a large Json render, so I'd prefer to either add a property attribute, or override the serialising method on the class.
Currently, the it renders like this:
"event_modal":
{
"href":"file.html",
"type":"full"
}
And I'm hoping to get it to render like: (href and type are without quotes)
"event_modal":
{
href:"file.html",
type:"full"
}
From the class:
public class ModalOptions
{
public object href { get; set; }
public object type { get; set; }
}
A: It's possible, but I advise against it as it would produce invalid JSON as Marcelo and Marc have pointed out in their comments.
Using the Json.NET library you can achieve this as follows:
[JsonObject(MemberSerialization.OptIn)]
public class ModalOptions
{
[JsonProperty]
public object href { get; set; }
[JsonProperty]
public object type { get; set; }
}
When serializing the object use the JsonSerializer type instead of the static JsonConvert type.
For example:
var options = new ModalOptions { href = "file.html", type = "full" };
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, options);
}
var json = stringWriter.ToString();
This will produce:
{href:"file.html",type:"full"}
If you set the QuoteName property of the JsonTextWriter instance to false the object names will no longer be quoted.
A: You can also try a regex replace, with a substitution, which could handle any serialized object, and replace the quotes for you.
For Example:
var options = new ModalOptions { href = "file.html", type = "full" };
string jsonText = JsonConvert.SerializeObject(options);
string regexPattern = "\"([^\"]+)\":"; // the "propertyName": pattern
Console.WriteLine(Regex.Replace(jsonText, regexPattern, "$1:"));
This would produce:
{href:"file.html",type:"full"}
I built a working web example here.
Explanation of regex substitutions are here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: Glassfish 2.1 Spring 3.0 - How-To Setup - No Web Application I have googled around and I have not found satisfying informations about how to start to setup spring in a glassfish container.
Starting point is:
*
*Glassfish 2.1 (no discussions about the version please cause we are forced to use this)
*Spring (preferrable version 3.0 but if not possible also lower version is allowed)
*EJB 3.0 (therefore I want to make use of the interceptor mechanism to inject a spring bean on the the stateless bean see: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ejb.html#ejb-implementation-ejb3 )
We don't have a web application in the ear file therefore I am lost at the moment how I could integrate spring into our ear file.
Therefore I have the following questions:
How do I have to configure glassfish/ear file to recognize the spring xml files?
Where should I place and how should I name the spring xml files so they are recognized correctly by the spring framework?
It would be great if anybody could help to find the approriate starting point.
Kind regards,
Walter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Need horizontal menu option on mouseover on a particular div My requirement is to make a horizontal menu in the end of a paragraph where on mouseover a menu should appear
On mouse over it should show an option to add an item like this
On clicking the add option the menu should appear like this
Please suggest any jQuery or javascript plugin for this functionality. My preference is a plugin for this other than writing custom script.
A: Here is what I have: http://jsfiddle.net/cbARJ/4/
I don't have such background for your Add here buttons, so you will need to add it.
A: Simple.
EDIT: On mouse over for paragraph?
CSS:
p #add_link { display:none }
p:hover #add_link { display: block }
#links { display:none }
JS:
$('p #add_link').click(function() {
$(this).parent().append($('#links').html()); // Or anything else
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Set maven property from plugin I've read some questions here about how to set a property (most of them talked about the version number for an application) from a maven plugin.
It seems there's no easy way of doing this and the best solution I found is to have a filter.properties file which is updated from the plugin and used by the main pom file to filter the desired resources.
I tried another solution after I read this from the Maven documentation (Maven filter plugin):
Variables can be included in your resources. These variables, denoted
by the ${...} delimiters, can come from the system properties, your
project properties, from your filter resources and from the command
line.
I found interesting that variabled can be read from system properties. So, I modified my plugin to set a system property like this:
System.setProperty("currentVersion", appCurrentVersion);
However, filtered resources don't seem to read this value.
Could anybody tell me what's wrong with this approach?
UPDATE: I'm running my plugin in the validate phase.
Thanks a lot.
A: Maven sets properties in initialize phase. I assume that in that phase maven loads system properties. And after that maven doesn't load system properties again. If you try to add a system property after this phase than it's not loaded.
Try to run your plugin in validate phase.
A: Don't set it as System Property, set it as Maven Project property
// inject the project
@Parameter(defaultValue = "${project}")
private org.apache.maven.project.MavenProject project;
// and in execute(), use it:
project.getProperties().setProperty("currentVersion", appCurrentVersion);
See:
*
*Mojo Developer Cookbook
*MavenProject javadoc
An edit suggested using Properties.put() instead of Properties.setProperty(). While technically, Properties implements Map, this usage is discouraged explicitly in the Properties javadoc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: get and initialValues method of ThreadLocal synchronized I came across a code where the get() and initialValue() methods of ThreadLocal is synchronized.
I couldn't find any use of having these methods synchronized. Correct me if I am wrong.
-Krishna.
A: I was investigating the same usage of synchronized on ThreadLocal initialValue(). Fakrudeen's answer includes a link to a Java 1.5 defect in which the synchronized keyword was the work around for multiple objects being created. It was fixed in Java 1.6
If you run this test (taken from the Fakrudeen's link) in Java 1.5 and compare your results to a later version, you will see that in versions 1.6 and later that synchronized is not necessary.
---------- BEGIN SOURCE ----------
import java.util.ArrayList;
public class ThreadLocalBug {
static int COUNT = 8;
static ThreadLocal tl = new ThreadLocal() {
protected Object initialValue() {
System.err.println("initialValue called");
ArrayList list = new ArrayList(COUNT);
for (int i = 0; i < COUNT; i++) {
MyThreadLocal mtl = new MyThreadLocal();
mtl.get();
list.add(mtl);
}
return list;
}
};
public static void main(String[] args) throws Throwable {
Object first = tl.get();
Object second = tl.get();
Object third = tl.get();
System.err.println("first=" + first);
System.err.println("second=" + second);
System.err.println("second=" + third);
}
static class MyThreadLocal extends ThreadLocal {
protected Object initialValue() {
return Boolean.TRUE;
}
}
}
---------- END SOURCE ----------
(I would have added this as a comment to Fakrudeen's answer, but I don't have enough points :-) )
A: It may be useful due to this bug:
https://bugs.openjdk.java.net/browse/JDK-6550283?page=com.atlassian.streams.streams-jira-plugin:activity-stream-issue-tab
A: No, that's completely pointless, and was likely written by someone who didn't know what they were doing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to delete 2 spaces or break line become one space? here is my coding is break line str_replace
$finalresult = "a<\n>b";
$strreplace = str_replace("\n", "", $finalresult);
echo $strreplace;
here is my coding is 2 spaces str_replace
$finalresult = "a b";
$strreplace = str_replace(" ", "", $finalresult);
echo $strreplace;
result1 :
a
b
result2 :
a b
my question is why my str_replace does not working at all ?
A: I'm not entirely sure why that is not working (it is for me), however if you want to replace all x amounts of spaces / linebreaks etc. with one space you could do this:
$result = preg_replace('/\s+/',' ',$input);
Your two examples on codepad (they work fine):
http://codepad.org/t3jR2azv
http://codepad.org/h3qiDzMD
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Append form values to hidden XML string on post I am posting a form to a remote server and have to send over an XML formatted string as a hidden field, containing the entered info. Im struggling to append the input values entered to the XML string, E.g.:
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
The XML is as such:
<input type="hidden" name="parameters" value="<request><first_name>Test User</first_name> <surname>XXXX</surname></request>"/>
How can I with PHP ideally, on POST, apply the values entered in the inputs to the XML string, so firstname and surname are posted as entered by the user?
I tried Jquery but it broke the XML string.
Many Thanks in advance!
A: I think you need to use java script to manipulate parameters value.
Sample example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://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>Untitled Document</title>
<script language="javascript">
function callme()
{
document.getElementById('parameters').value="<request><first_name>"+document.getElementById('fname').value+"</first_name> <surname>"+document.getElementById('sname').value+"</surname></request>";
document.getElementById('loginForm').submit();
}
</script>
</head>
<body>
<form id="loginForm">
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
<input type="hidden" id="parameters" name="parameters" value=""/>
<input type="button" onclick="javascript:callme()" />
</form>
</body>
</html>
A: I think you should do this server-side as malicious users could post anything. Having to escape your first and last name values is a lot easier than validating the correctness of your xml.
$first = htmlspecialchars($_GET['firstname']);
$last = htmlspecialchars($_GET['lastname']);
$xml = sprintf
( '<request>
<first_name>%s</first_name>
<last_name>%s</last_name>
</request>',
$first, $last
);
There is no reason to do this in javascript unless you need that xml to be sent of to a different url by ajax.
EDIT This solution also works for people having javascript turned off (e.g no-script users).
A: html -
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
<input type="hidden" id="parameters" />
<input type="button" name="click" id="button" value="button" />
Script - Use a parameter and set before submit e.g.
$(document).ready(function() {
var parameters = "<request><first_name>YYYY</first_name> <surname>XXXX</surname></request>";
$('#button').click(function(){
parameters = parameters.replace('YYYY',$('#fname').val());
parameters = parameters.replace('XXXX',$('#sname').val())
$('#parameters').val(parameters);
alert($('#parameters').val());
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error out of bounds exception when running recursive program in Java I'm learning about recursion as part of a Java tutorial and I am looking for a little help.
We need to make a recursive Java program which will work out how to get from one city to the other when there is no direct flight.
My latest issue is Im getting an error out of bounds exception after the code has 2 cities in the flightRoute array List. it gives the error "IndexOutOfBoundsException Index 2 Size 2"
The connection value is an arrayList which takes all the cities that the city connects with and the flightRoute is also an arrayList which keeps track of the cities we have had to travel to in order to reach our destination.
I just cannot work out why it will not proceed.
I would appreciate some help on this if you could.
I do not want to overflow you guys with code so i'll put up the method that you should need. If you need more I will happily add some more code.
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
//the Connections value takes all the connecting cities we can travel to from a departure point
Connections = from.getConnections();
City theCity = Connections.get(i);
//searches in the connecting cities from the current city as to if it contains the city we wish to travel to
if (flightRoute.contains(to)|| 7 >8)
{
System.out.println("Congrats you can go their cause one of its connecting cities is the to city that u wanna go to");
return true;
}
System.out.println("the City name "+theCity);
if(flightRoute.contains(theCity))
{
System.out.println("Sorry it cannot be added "+Connections.get(i));
}
else
{
//add connecting city to list for future reference
flightRoute.add(Connections.get(i));
//takes the lates connection and uses it for recursion (below)
from = Connections.get(i);
i++;
//recursive part which sends a new from city for analysis until the city we want to travel to arises
determineRoute(from, to, flightRoute);
}
return true;
}
A: Where do you set the i value? Anyway, the only get() you do use i as index, so it is clear that Connections does not have as much items as i.
BTW:
a) Next time mark at which line the exception is thrown (from what I see, probaly the first get()
b) use lowercase for variable names: connections instead of Connections
A: The problem is that i is non declared locally, so you're forever incrementing some instance variable. Declare it locally and set it to zero.
Before you can make any real progress fixing this code, I advise you clean it up:
*
*Name variables with a leading lowercase - ie connections not Connections
*Use local variables where it makes sense - like connections
*Remove nonsense code, such as the test if 7 > 8 is true - of course it's always true!
*Use proper indentation of blocks
*Iterate over collections using a "foreach" loop: for (City city : from.getConnections())
*Tend to name your variables the same as the class name, but with a lowercase letter, so city, not theCity
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to check condition on check box click? I am trying to check the condition of checkboxes.For making checkbox i use button.I changed there sizes and provide image as checked or unchecked on their click method.Now i have two checkboxes.Now i am trying to store array value on the bases of checkbox clicked.I mean that when i click check box the specific value of the array store in the string and if i uncheck then the value of string set to null.
For that i did:
-(void) checkBoxIsAcitiveClicked
{
NSLog(@"check box button clicked");
if( [UIImage imageNamed:@"checkbox_ticked.png"])
{
isActiveStr=[arrayPickerData objectAtIndex:17];
NSLog(@" is active value is %@ is fetched succesfuly",isActiveStr);
[CommonVar setIsActiveStrData:isActiveStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",isActiveStr);
}
else
{
NSLog(@"no vlaue send");
isActiveStr=nil;
[CommonVar setIsActiveStrData:isActiveStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",isActiveStr);
}
}
1)CommonVar is my common class
2)setIsActiveStrData is my class method in commonvar class
3)isActiveStr is my NSMutableString.
4)arrayPickerData is my NSMutableArray
Now i dont know how to check the condition that button image is checked.png or unchecked.png
Please help me
Thank You
A: UIImage *uncheckmark = [UIImage imageNamed:@"checkbox_unticked.png"]; // Unticked image
[checkbutton setImage:uncheckmark forState:UIControlStateNormal];
UIImage *checkmark = [UIImage imageNamed:@"checkbox_ticked.png"]; // ticked image
[checkbutton setImage:checkmark forState:UIControlStateSelected];
[checkbutton addTarget:self action:@selector(selectedTouched:)
forControlEvents:UIControlEventTouchUpInside];
-(IBAction)selectedTouched:(id)sender{
UIButton *aButton = (UIButton*)sender;
// to check/unchecked and Implement your logic here
(aButton.selected) ? NSLog(@"Checked") : NSLog(@"Un-Checked");
[aButton setSelected:!(aButton.selected)];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Parse my nested xml? Hi i need to parse an xml file whose structure is as shown below in NSXMLParser,
<Root>
<Ancor>
<A1>,,,,,,,</A1>
<A2>,,,,,,,</A2>
<A3>,,,,,,,</A3>
<subContent>
<![CDATA[,,,,,,,,,,,,,,,,,,,]]?
</subContent>
</Ancor>
<Main id="1">
<Basic>,,,,,,,</Basic>
<Info>
<info1>,,,,,,</info1>
<info2>,,,,,,</info2>
<info3>,,,,,,</info3>
<subInfo id="1">
<subcontent1>,,,,,,</subcontent1>
<subcontent2>,,,,,,</subcontent2>
</subInfo>
<html>
<![CDATA[,,,,,,,,,,,,,,,,]]>
</html>
</Info>
</Mainid>
</Root>
Here inside main tags called Root n number of Main tags will come based on different different id,each Main tag contents i need to store and display in 1 page.
Can anybody help with some snippets of code?,Any help is appreciated in advance , Thank You.
A: xmlparser can detect the tags on its own .. all you need to do is compare the tags in delegates and get the values out... hope this helps..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Trying to unbind events on iPad2 with javascript Bit of background, we are creating an html5 'app' for the iPad, which has everything contained in a single page, and all the content is dynamic.
I have a dynamically generated anchor, which then has a click event bound to it as so:
$j(toElement).find(".moveSlideUp").bind('click', addSlideToPresentation_click);
This all works fine, however the problem is that once we navigate away from that page/section, and navigate back to it, the event handler is bound a second time, and thus fires twice (or 3 or 4 times etc...).
I have tried calling unbind before binding, but this makes no difference - any ideas?
A: You can bind handler in the same context which when is reloaded releases your handler as well. Or check if handler is already bound:
jquery check if event exists on element
test if event handler is bound to an element in jquery
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails 3: convert session[:params] to correct activerecord query I have two models, Foo and Bar, with same attributes, and I'm 'caching' user "search params" into a session variable, that ends into something like this:
session[:search_params] => {"price"=>"15.0", "air_conditioner"=>"0", "fireplace"=>"0", "number_of_rooms"=>"1", "balcony"=>"0"}
I'd like to search both Foo and Bar for entries that match this query.
For now, I'm doing:
@foo = Foo.new(session[:search_params])
search_attributes = @foo.attributes
search_attributes.delete 'id'
search_attributes.delete 'created_at'
search_attributes.delete 'updated_at'
@results = Foo.where(search_attributes)
@results += Bar.where(search_attributes)
that is REALLY UGLY.
Could anyone tell me a better/the correct way?
Thanks in advance.
EDIT
Also, some params in the session[:search_params] that are "0", are actually 'false' on the database (booleans) (filled by checkboxes), so I have to do some "conversion" into this fields so that the query is done correctly, i.e., getting for example air_conditioner => 'false' instead of air_conditioner => '0'.
A: You can use Dynamic Attribute-Based Finders: api.
So
@results = Foo.find_by_price_and_air_conditioner_and_fireplace_and_number_of_rooms_and_balcony(session[:search_params])
Also, you won't have to delete the extraneous information from session.
A: I wouldn't follow that path if I were you. I would go with a solution like https://github.com/ernie/meta_search
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# application on Apple IOS I have got C# .Net based applications. Is there any way I can run these applications for Apple IOS. I don’t have resources to develop all applications from scratch.
Many Thanks,
Ni
A: You can use the tools made by the mono project.
These will not support all of the MS namespaces (non of the windows specific ones, such as WMI) and your application code needs to be written to be cross platform (so using Path.Combine for directory paths instead of concatenations).
Try the MoMA tools to see if your code is cross platform and get recommendations for fixing it if it is not.
A: First of all, you can not just run your existing .NET programs unmodified on the iOS platform.
The .NET runtime does not work on iOS, nor will it (in relation to current app guidelines regarding runtime compilation). Mono has the same fate and will not run on the iOS platform.
Your only option is to get the code compiled to native iOS executables, and this will involve 3rd party tools.
One of those is the MonoTouch product. It is not free.
Note that this is not a technical limitation. The .NET runtime could run on the iOS platform if Microsoft, or Mono made it for that platform, but Apple does not allow such runtimes (the ones that download/execute not-yet-100%-compiled code) on their platform at all.
This is the same problem that prevents Flash from executing on the platform. The way Flash has gone to solve this is to compile the Flash programs to native iOS executables.
A: Take a look at Xamarin for IOS. Integrates nicely with Visual Studio otherwise you can use its own IDE.
You can also reference .net assemblies. Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: C++ unit test for testing performance (synthetic benchmark) is there any library just like unit testing library, but instead of testing for correctness, its testing the performance of such functions, the output is execution time, cpu instruction count, performance variance, cache-miss, etc..
A: I use gprof and valgrind for performance profiling. They certainly work on Linux and you can pretty much do all the things you mention.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to remove a string from a string I am adding a string (a) to another string (b) before I store it in DB, when I retrieve the value from DB, I want to remove the string(b) from string (a). string (b) is a constant. How can I do it
string a= "text1";
string b="text2";
string c = a+b;
I want to remove b from c after I retrive it from db
A: c = c.Replace(b, "");
Would be a simple way to do so.
A: Rather than do any of that, create a computed column in the DB that has the extra text.
Less storage; less code.
A: Try String.Replace - MSDN documentation here.
A: As @SvenS has pointed in @Khaled Nassar answer, using String.Replace won't work "as is" in your situation.
One acceptable solution may @Mitch's one, but if you don't have that access to modify your database, maybe there's another solution in pure C#:
int indexOfB = c.LastIndexOf(b);
string cWithoutB = c;
if(indexOfB >= 0)
{
c.Substring(0, indexOfB);
}
This prevents replacing more than once the same string as b, because who knows if some user save the same text as b and logic shouldn't be removing it if it's not the one predefined by your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to check if String is null I am wondering if there is a special method/trick to check if a String object is null. I know about the String.IsNullOrEmpty method but I want to differentiate a null String from an empty String (="").
Should I simply use:
if (s == null) {
// blah blah...
}
...or is there another way?
A: An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.
And yes, you should just use
if (s == null)
Note that this will still use the overloaded == operator defined in string, but that will do the right thing.
A: If you are using C# 7.0 or above you can use is null:
if (s is null) {
// blah blah...
}
Also, note that when working with strings you might consider also using IsNullOrWhiteSpace that will also validate that the string doesn't contain only spaces.
A: You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:
textBox1.Text = s ?? "Is null";
The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.
More info here:
https://msdn.microsoft.com/en-us/library/ms173224.aspx
And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015
textBox1.Text = customer?.orders?[0].description ?? "n/a";
This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.
More info here:
https://msdn.microsoft.com/en-us/library/dn986595.aspx
A: To be sure, you should use a function to check for null and empty as below:
string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}
A: For .net 5 (probably also for .net Core 3.1)
Different possibility to write but always the same problem.
string wep = test ?? "replace";
Console.WriteLine(wep);
result: "replace"
or
string test=null;
test ??= "replace";
Console.WriteLine(test);
test="";
test??="replace";
Console.WriteLine(test);
*
*first try: "replace"
*second try: blank
string test="";
if(test is null)
Console.WriteLine("yaouh");
else
Console.WriteLine("Not yahouu");
Result: "Not yahou"
A: You can check with null or Number.
First, add a reference to Microsoft.VisualBasic in your application.
Then, use the following code:
bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
In the above, b and c should both be false.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "59"
}
|
Q: How do I solve a "java.lang.OutOfMemoryError: Java heap space"? I am writing some code to parse a very large flat text file into objects which are persisted to a database. This is working on sections of the file (i.e. if I 'top' the first 2000 lines), but I am running into a java.lang.OutOfMemoryError: Java heap space error when I try and process the full file.
I am using a BufferedReader to read the file line by line, and I was under the impression that this negates the requirement to load the entire text file into memory. Hopefully my code is fairly self-explanatory. I have run my code through the Eclipse Memory Analyser, which informs me that:
The thread java.lang.Thread @ 0x27ee0478 main keeps local variables with total size 69,668,888 (98.76%) bytes.
The memory is accumulated in one instance of "char[]" loaded by "<system class loader>"**
Helpful comments greatly appreciated!
Jonathan
public ArrayList<Statement> parseGMIFile(String filePath)
throws IOException {
ArrayList<Statement> statements = new ArrayList<Statement>();
// Statement Properties
String sAccount = "";
String sOffice = "";
String sFirm = "";
String sDate1 = "";
String sDate2 = "";
Date date = new Date();
StringBuffer sData = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line;
String prevCode = "";
int lineCounter = 1;
int globalLineCounter = 1;
while ((line = in.readLine()) != null) {
// We extract the GMI code from the end of the first line
String newCode = line.substring(GMICODE_START_POS).trim();
// Extract date
if (newCode.equals(prevCode)) {
if (lineCounter == DATE_LINE) {
sDate1 = line.substring(DATE_START_POS, DATE_END_POS).trim();}
if (lineCounter == DATE_LINE2) {
sDate2 = line.substring(DATE_START_POS, DATE_END_POS).trim();}
if (sDate1.equals("")){
sDate1 = sDate2;}
SimpleDateFormat formatter=new SimpleDateFormat("MMM dd, yyyy");
try {
date=formatter.parse(sDate1);
} catch (ParseException e) {
e.printStackTrace();
}
sFirm = line.substring(FIRM_START_POS, FIRM_END_POS);
sOffice = line.substring(OFFICE_START_POS, OFFICE_END_POS);
sAccount = line.substring(ACCOUNT_START_POS,
ACCOUNT_END_POS);
lineCounter++;
globalLineCounter++;
sData.append(line.substring(0, END_OF_DATA)).append("\n");
} else {
// Instantiate New Statement Object
Statement stmt = new Statement(sAccount, sOffice, sFirm,
date, sData.toString());
// Add to collection
statements.add(stmt);
// log.info("-----------NEW STATEMENT--------------");
sData.setLength(0);
lineCounter = 1;
}
prevCode = newCode;
}
return statements;
}
STACKTRACE: Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbPopulator' defined in class path resource [app-context.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
at Main.main(Main.java:11)
Caused by: java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2882)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:390)
at java.lang.StringBuffer.append(StringBuffer.java:224)
at services.GMILogParser.parseGMIFile(GMILogParser.java:133)
at services.DBPopulator.init(DBPopulator.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1468)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1398)
... 12 more
A: Adding more memory in the start parameters is IMHO a mistake. Those parameters are application wide. And may penalize by increasing gc times. Moreover, you might not know the size in advance.
You use MemoryMappedFiles and look at the java.nio.* to do so. Doing so you can load as you read, and the memory is not placed in the ordinary memory space.
By reading at a low level you do it in chunks of variable length. And the speed is important. If your file is large, it may take too much time to read it. And the quantity of Objects you store in JVM makes the GC works and the application slows down.
From the java reference:
*
*A byte buffer can be allocated as a direct buffer, in which case the Java virtual machine will make a best effort to perform native I/O operations directly upon it.
*A byte buffer can be created by mapping a region of a file directly into memory, in which case a few additional file-related operations defined in the MappedByteBuffer class are available.
*A byte buffer provides access to its content as either a heterogeneous or homogeneous sequence of binary data of any non-boolean primitive type, in either big-endian or little-endian byte order.
A: Maybe it is the statements object that is growing too large? If so, maybe you should persist it to the database in batches instead of all at once?
A: It seems your application is using the default memory allocated by the VM (about 64 MB if I remember correctly). Since your application is a special-purpose one, I'd suggest increasing the memory available for the application (e.g. running the app using java -Xmx256m would allow it to use up to 256 MB of RAM). You could also try running it using the server VM (java -server yourapp), which will try to optimize things a bit.
A: Another thing that can happen here:
if your file is bigger than half your heap and does not contain any linebreaks in.readLine() would try to read the whole file and fail in this case.
A: -Xmx1024M -XX:MaxPermSize=256M has solved my java.lang.OutOfMemoryError: Java heap space error.
Hope this will work.
A: code seems right to me. maybe I should have used StringBuffer in place of String.
String are pretty nasty in java, for each modification you perform on them, a new object is created, and refs can remain anywhere in the code.
Usually I read file lines inside a private method using local vars, just to be sure that no ref to String are left around.
The list you're getting back is a list of beans with String properties? If so, change 'em to StringBuffer and rerun the profiling.
Let me know if this helped you.
Regards,
M.
A: It seems that sData causes the overflow. There should be several (million?) statements in the text with the same GMI code.
Accumulations by char[] means either String or StringBuilder. Since it fails with resizing StringBuilder, it should be the reason.
Just try to output sData to stdout for debugging and see what happens.
A: Why don't you try to replace the line (if your using JDK 6, substring memory problem was solved in JDK 7)
String newCode = line.substring(GMICODE_START_POS).trim();
Replace line:
String newCode = new String(line.substring(GMICODE_START_POS));
A: I encountered the same problem a few months back
I used Scanner class:
Scanner scanner = new Scanner(file);
instead of:
BufferedReader in = new BufferedReader(new FileReader(filePath));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: failing An ANT build file if the java program it's referring to throws an Exception I have the following Ant target :
<target name="getArchiverStatus" depends="exportContent">
<java classname="com.test.cms.build.GetErrorCountForArchiver" failonerror="true">
<classpath>
<pathelement location="${cs.home}/${env}/main/main.jar" />
<fileset dir="${cs.home}/${env}/lib" includes="*.jar" />
</classpath>
<arg value="${cs.url}" />
<arg value="${cs.username}" />
<arg value="${cs.password}" />
<arg value="${ucm.archive.name}" />
<arg value="${ucm.workflow.logs.dir}" />
</java>
</target>
I want that this particular target should fail terminating further execution of the build file when the java class GetErrorCountForArchiver has thrown an Exception.Even after using Failonerror= true the next target is getting executed...
A: Make sure you use the fork=true and failonerror=true. I was running into the same issue but after having those two properties set I got it working as I wanted.
I had simple class
package jonathanmv.tests;
public class ContinuousIntegration {
public static void main(String[] args) throws Exception {
throw new Exception("This is supposed to happen");
}
}
Then a simple ant build file
<project name="Continuous Integration Build" basedir="." default="main">
<property name="package" value="jonathanmv.tests" />
<property name="src.dir" value="src" />
<property name="build.dir" value="build" />
<property name="classes.dir" value="${build.dir}/classes" />
<property name="jar.dir" value="${build.dir}/jar" />
<property name="jar.file" value="${jar.dir}/${package}.jar" />
<property name="lib.dir" value="lib" />
<property name="main-class" value="${package}.ContinuousIntegration" />
<path id="classpath">
<fileset dir="${lib.dir}" includes="**/*.jar" />
</path>
<path id="application" location="${jar.file}" />
<target name="clean">
<delete dir="${build.dir}" />
</target>
<target name="compile">
<mkdir dir="${classes.dir}" />
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" includeantruntime="false" />
<copy todir="${classes.dir}">
<fileset dir="${src.dir}" excludes="**/*.java"/>
</copy>
</target>
<target name="jar" depends="compile">
<mkdir dir="${jar.dir}" />
<jar destfile="${jar.file}" basedir="${classes.dir}">
<manifest>
<attribute name="Main-Class" value="${main-class}" />
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java fork="true" classname="${main-class}" failonerror="true">
<classpath>
<path refid="classpath" />
<path refid="application"/>
</classpath>
</java>
</target>
<target name="clean-build" depends="clean,jar" />
<target name="main" depends="clean,run" />
</project>
clean-build and main do not run because the run target fails due to the exception thrown by the main class. Notice that the following line is the one that does the trick in the run target
<!-- ... -->
<java fork="true" classname="${main-class}" failonerror="true">
<!-- ... -->
When I execute ant this is what I get
Buildfile: /home/team/workspace/CI/trunk/build.xml
clean:
[delete] Deleting directory /home/team/workspace/CI/trunk/build
compile:
[mkdir] Created dir: /home/team/workspace/CI/trunk/build/classes
[javac] Compiling 2 source files to /home/team/workspace/CI/trunk/build/classes
[copy] Copying 1 file to /home/team/workspace/CI/trunk/build/classes
jar:
[mkdir] Created dir: /home/team/workspace/CI/trunk/build/jar
[jar] Building jar: /home/team/workspace/CI/trunk/build/jar/jonathanmv.tests.jar
run:
[java] Continuous Integration ran
[java] 0 [main] INFO jonathanmv.tests.ContinuousIntegration - Continuous Integration > ran
[java] Exception in thread "main" java.lang.Exception: This is supposed to happen
[java] at jonathanmv.tests.ContinuousIntegration.main(Unknown Source)
BUILD FAILED
/home/team/workspace/CI/trunk/build.xml:41: Java returned: 1
Total time: 1 second
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to display "Message box" using MVC3 controller I have been facing an issue to display "Message Box" after executing of some code in controller
for ex:-
public ActionResult IsLoginExsit(CustomerDO loginData)
{
JsonResult jsonResult = new JsonResult();
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
jsonResult.Data = result;
}
return jsonResult;
}
as seen in above example, if result is true or false, then i would like to display message box stating that login is suceess or fail.
<!-- language: lang-.html -->
<form class="formStyle" action="#" method="POST" id="frmAuthenticate">
<div class="row">
<input class="text row" type="text" value="" id="txtUserName"/>
</div>
<div class="row">
<input class="text row" type="password" value="" id="txtPassword" />
</div>
<div class="row last">
<a class="link" href="">Forgot Password?</a>
<a class="button3" href="/Registration/Registration" title="Registration" >Signup</a>
<input type="submit" class="button4" id="btnGo" value="Go" />
</div>
</form>
If login is exist i want to navigate to "/Customer/CollaborationPortal", else i would like to display message "Authroization fail".
$("#btnGo").click(function (e) {
var RegData = getRegData();
if (RegData === null) {
console.log("Specify Data!");
return;
}
var json = JSON.stringify(RegData)
$.ajax({
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if(data.result == true){
location.href = "/Customer/CollaborationPortal";
}
else{
alert("Login failed"); //or whatever
}
}
});
return false;
});
function getRegData() {
var UserName = $("#txtUserName").val();
var Password = $("#txtPassword").val();
return { "UserName": UserName, "Password": Password };
}
Thanks in advance
A: There is no way do that in MVC as simple as in winforms application.
Simplest way to display message box on web page in your case is to change this action from ActionResult to JsonResult, and replace your if with:
return Json(new {result = result});
and, in web page you need to use ajax (i.e. submit a form using jquery's $.post) and in callback function check for result:
$("form input[type=submit]").click(function(){
var formData = $(this).closest("form").serialize();
$.post("urltoyourcontrollerhere/IsLoginExsit", formData, function(data){
if(data && data.result == true){ alert("Login exists!");}
});
});
UPDATE
The code you posted seems OK, but there is one problem. The success function:
success: function (data) {
location.href = "/Customer/CollaborationPortal";
}
This function will always perform redirect, no matter what controller has returned. You need to check if data.result (if you returned your json as Json(new {result = result});) is true, and then redirect, else display alert. So, try:
success: function (data) {
if(data.result == true){
location.href = "/Customer/CollaborationPortal";
}
else{
alert("Login failed"); //or whatever
}
}
Another thing:
var RegData = getRegData();
if (RegData === null)
If you want this to work, you need to return null from getRegData when one of textboxes is empty.
A: You CAN display a message box when done.
public ActionResult LoginExist(BAMasterCustomerDO loginData)
{
return new JavascriptResult { Script = "alert('Saved successfully');" };
}
A: You won't be able to display a message box using the server side code. You'll need to pass some data back to the view indicating the login status then write some client side code to display the message box.
A: You could use a property of your view model which will be passed to the view and which will contain this information:
var model = new MyViewModel();
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
model.IsLoginSuccess = result;
...
return View(model);
and inside your strongly typed view you would test the value of this property and display the message accordingly:
@if (Model.IsLoginSuccess)
{
<div>The Login was successful</div>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: VB.Net - Buttons missing on one client We're facing a strange problem here. One of our users cannot see two buttons on a form, that everybody else can see. I'm not sure if the buttons are not there or the window is smaller than it should be. The size of this window is fixed, so it cannot be adjusted manually. (it is like a pop-up window informt of the main window)
Our application is used by employees of our company all over the world. So they all have windows xp in different languages and their regional settings differ. But I can't see how that would make a difference.
Does anyone have an idea?
A: A reason for this might be that the user changed the DPI setting on its machine. Typically you would change that in the control panel, in the Display settings you can choose to have a font size of 100%, 125% and 150%. This affects the DPI and might push winforms controls further down the form, making them "invisible" (below the bottom boundary of the form).
Here are instructions on how to change DPI settings on Windows XP.
If this is the cause for your problem, you have to make sure your forms scale properly. Look at the MSDN documentation for automatic scaling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android camera error 100 For my project I am using MediaRecorder to record video.
This code is working on most of the devices, but in HTC Desire (with Android 2.3), when I call recorder.start(); it's throwing ERROR/Camera(25146): Error 100. Is anybody has any clue how to solve it?
My code is like this:
Camera camera = Camera.open();
Parameters parameters = camera.getParameters();
if (flash) {
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
else {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
}
camera.setParameters(parameters);
try {
camera.setPreviewDisplay(holder);
} catch (IOException e1) {
e1.printStackTrace();
}
camera.startPreview();
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
am = (AudioManager) context.getSystemService(Activity.AUDIO_SERVICE);
am.setMode(AudioManager.STREAM_VOICE_CALL);
am.startBluetoothSco();
try {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
if(android.os.Build.VERSION.SDK_INT>=8){
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cp = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
recorder.setProfile(cp);
}
else{
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
recorder.setVideoSize(CIF_WIDTH, CIF_HEIGHT);
recorder.setVideoFrameRate(FRAME_RATE);
}
recorder.setMaxDuration(maxduration*1000);
recorder.setPreviewDisplay(holder.getSurface());
String data_folder=Environment.getExternalStorageDirectory().getAbsolutePath() + settings.location_in_sdcard;
File ff=new File(data_folder);
if(!ff.exists()){
ff.mkdirs();
}
String path = data_folder+api.getCurrentTimeStamp()+".3gp";
recorder.setOutputFile(path);
try{
recorder.prepare();
}
catch (Exception ee) {
ee.printStackTrace();
}
}
catch (Exception e) {
Log.e("ls", e.toString(), e);
}
recorder.start();
Log Report:
09-27 18:11:37.358: ERROR/StagefrightRecorder(24740): Failed to set frame rate to 30 fps. The actual frame rate is 15
09-27 18:11:37.478: ERROR/QualcommCameraHardware(24740): frames in busy Q = 0
09-27 18:11:37.478: ERROR/QualcommCameraHardware(24740): frames in busy Q = 0 after deq and add to freeQ
09-27 18:11:37.478: ERROR/OMXNodeInstance(24740): OMX_UseBuffer failed with error -2147479547 (0x80001005)
09-27 18:11:37.478: ERROR/OMXCodec(24740): allocate_buffer_with_backup failed
09-27 18:11:37.478: ERROR/OMXCodec(24740): [ 09-27 18:11:37.478 24740:0x60a8 F/OMXCodec ]
09-27 18:11:37.478: ERROR/OMXCodec(24740): frameworks/base/media/libstagefright/OMXCodec.cpp:1863 err != OK
09-27 18:11:38.679: ERROR/Camera(25146): Error 100
09-27 18:11:40.121: ERROR/AudioService(1335): Media server died.
09-27 18:11:41.242: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.292: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.362: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.402: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.422: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.442: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.452: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.472: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.532: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.702: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.722: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.732: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.752: ERROR/OverlayLIB(1335): Error parameters for screen direction is not correct
09-27 18:11:41.762: ERROR/Overlay(1335): connect to socket failed
09-27 18:11:44.285: ERROR/HTC Acoustic(25182): ioctl ACOUSTIC_UPDATE_ADIE failed -1
09-27 18:11:44.285: ERROR/HTC Acoustic(25182): ioctl ACOUSTIC_UPDATE_ADIE failed -1
09-27 18:11:44.285: ERROR/HTC Acoustic(25182): ioctl ACOUSTIC_UPDATE_ADIE failed -1
09-27 18:11:44.305: ERROR/HTC Acoustic(25182): failed to open A2051 CSV files /system/etc/TPA2051_CFG.csv.
09-27 18:11:44.305: ERROR/AudioHardwareMSM7X30(25182): set_tpa2051_parameters fail
09-27 18:11:44.305: ERROR/AudioHardwareMSM7X30(25182): set_aic3254_parameters failed
09-27 18:11:44.315: ERROR/AudioPolicyManagerBase(25182): mSupportBacMic = 0
09-27 18:11:45.626: ERROR/AudioService(1335): Media server started.
09-27 18:12:42.191: ERROR/HtcLockScreen2.0(1335): MusicCtrl: updateImage~ exception:null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove the "result" overlays but not the "current position" overlay I my application there is button "show me",and a spinner to choose radius ,and one button "search" to search results,,
my problem i that when i tap on "show me" it shows the overlay at current location and when i search after choosing radius it shows the results in the map with overlays but my current position overlay removes..because i am using
List<Overlay> mapOverlays_results;
mapOverlays_results =mapView.getOverlays();
mapOverlays_results.clear();
but if i dont use these above lines and i decrease the radius old results also seen in the map..
How to remove the result overlays but not the current position overlay..
How to solve this..?
Thanks
A: As you've got more than one overlay (I'm guessing two), then instead of mapOverlays_results.clear(), you should try mapOverlays_results.remove(int arg), where arg will be the index of the overlay that isn't your position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to update listview in AlertDialog I have a dialog that contains a listview, the data of the list view comes from the parent of the dialog. Every time the dialog is about to be displayed, it should get data from the activity to build its list items. I know I should do this in onPrepareDialog(), but I don't know how to update the listview created by AlertDialog.builder, Could anyone help me?
My dialog is created from below code:
new AlertDialog.Builder(this)
.setTitle(title)
.setMultiChoiceItems(cityNames(), updateSelections(),
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
if(isChecked){
selections[whichButton] = true;
// Toast.makeText(MainActivity.this, cities.get(whichButton).getName(), Toast.LENGTH_SHORT).show();
}
}
})
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for(int i=0;i<selections.length;i++){
if(selections[i]==true){
removeCityFromScreen(i);
}
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.create();
A: I am creating a custom adapter for listview..doing like this :
dialog2 = new Dialog(SActivity.this);
ListView modeList = new ListView(SActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(SActivity.this);
builder.setTitle(" resul[s] ");
MySimpleAdapter adapter = new MySimpleAdapter(SActivity.this, data , R.layout.list_main,
new String[] { "name", "distance" ,"phone","web"},
new int[] { R.id.item_title, R.id.item_subtitle ,R.id.item_subtitle1 ,R.id.item_subtitle2});
modeList.setAdapter(adapter);
builder.setView(modeList);
dialog2 = builder.create();
dialog2.show();
A: Simple answer: After calling create() there's no chance to update the list. The builder inflates XML's and creates custom adapters when calling that. I would recommend to create / build the dialog every time you're about to display it.
Note: Af course you could provide a custom AlertDialog setup with an own multi choice implementation. Then you could easily updated it since you have access to the adapter of the list (compare this answer - you could create and set a new adapter in this case).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Giving right margin in button on being clicked in android I have a screen where I display five buttons inside a Linearlayout vertically.
this linear layout is inside a relative layout and aligned to parent right.
Now I need that when any button is clicked it should shift leftwards while others remain at the original position.
I am trying to give left margin to the button on being clicked but the problem is all the buttons are shifting and not only that one.
Here is the code
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.rightMargin = 20;
mColorButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
fillDataList(1);
mIsClicked = true;
//[start] setting the colour of button
mColorButton.setBackgroundResource(R.drawable.yellow_stick) ;
mColorButton.setLayoutParams(layoutParams);
mPatternButton.setBackgroundResource(R.drawable.brown_stick);
mDistributionButton.setBackgroundResource(R.drawable.brown_stick);
mShapeButton.setBackgroundResource(R.drawable.brown_stick);
mLesionButton.setBackgroundResource(R.drawable.brown_stick);
//[end] setting the colour of button
}
});
A: May be this is the problem:
By default all Buttons are left aligned and when you give right margin to a Button it expands its parent layout size. The parent expands it self with its child. So all the Button shifted left side.
try to give android:layout_gravity="right" to all Button in XML or code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PhoneGap and Javascript OOP I'm starting with phonegap and also trying to apply JavaScript OOP with it. But the problem are the method calls and stuff. imagine this:
I have a main controller in JavaScript, this file try to control most of the work-flow between network calls, database a change views.
This is my main.js.
var onlineStatus = false;
var mainModel;
var connectTo = "http://192.168.1.65/mobile/service/";
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", online, false);
document.addEventListener("offLine", offline, false);
function whenOnline() {
setOnline(true);
}
function whenOffline() {
setOnline(false);
}
function onDeviceReady() {
mainModel = new MainModel();
mainModel.openDatabase();
mainModel.startApplication();
}
and the mainModel is this:
function MainModel() {
this.isOnline = false;
this.database = null;
this.login = null;
this.getDatabase = function() {
return this.database;
};
this.openDatabase = function() {
this.login = new LoginModel();
this.database = window.openDatabase("wayacross", "0.2", "Test DB", 1000000);
};
this.startApplication = function() {
this.database.transaction(this.login.checkLogin, goLoggin);
};
}
And the Login Model:
function LoginModel() {
this.loginError = function() {
navigator.notification.alert('Login Error', // message
null, // callback
'Login', // title
'Done' // buttonName
);
goLogin();
};
this.isLogged = function(tx, results) {
//ajax code
};
this.checkLogin = function(tx) {
alert('checkLogin: Variable TX = '+ tx);
tx.executeSql('SELECT * FROM login', [], this.isLogged, this.loginError);
};
}
This is the code I have at the moment to control the start work-flow. The problem is when i call in mainModel.js this.database.transaction(this.login.checkLogin, goLoggin); it won't do nothing. When I change this.login.checkLogin to this.login.checkLogin() it works but the tx variable go as undefined.
I'm probably doing something wrong here but I don't know why. Maybe JavaScript OOP isn't supported with phonegap, thing that I don't truly believe.
Can you help?
Thanks in advance,
Elkas
A: The problem is that when you say this.login.checkLogin, you are getting a reference to the function but losing the reference to the object this.login which you want associated with the function. This is one of the fundamental properties of Javascript that you have to understand completely or you will always be confused when working with Javascript.
This is exactly what Function.prototype.bind is for. It is not available natively in older browsers (so most Javascript frameworks have their own implementation), but since you’re using PhoneGap, you’re probably targeting a modern mobile WebKit browser.
What Function.prototype.bind does is bundle a function and an object together into a self-contained "method reference". Internally, a method reference is simply a function that invokes your original function as a method of your object.
Here’s how you would use it:
this.database.transaction(this.login.checkLogin.bind(this.login), goLoggin);
Again, what you’re saying there is "bind checkLogin to this.login and give it back to me as a method reference, not just as a detached function".
(Coincidentally, I kind of invented Function.prototype.bind. I described it in an old article called "Object-Oriented Event Listening through Partial Application in Javascript", it was one of the first utilities to be included in Prototype, and now it’s been standardized in ECMAScript 5. For a more detailed explanation, you could probably dig up that article somewhere.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Download POP3 headers from a certain date (Python) I'm trying to write a pop3 and imap clients in python using available libs, which will download email headers (and subsequently entire email bodies) from various servers and save them in a mongodb database. The problem I'm facing is that this client downloads emails in addition to a user's regular email client. So with the assumption that a user might or might not leave emails on the server when downloading using his mail client, I'd like to fetch the headers but only collect them from a certain date, to avoid grabbing entire mailboxes every time I fetch the headers.
As far as I can see the POP3 list call will get me all messages on the server, even those I probably already downloaded. IMAP doesn't have this problem.
How do email clients handle this situation when dealing with POP3 servers?
A: Outlook logs in to a POP3 server and issues the STAT, LIST and UIDL commands; then if it decides the user has no new messages it logs out. I have observed Outlook doing this when tracing network traffic between a client and my DBMail POP3 server. I have seen Outlook fail to detect new messages on a POP3 server using this method. Thunderbird behaves similarly but I have never seen it fail to detect new messages.
Issue the LIST and UIDL commands to the server after logging in. LIST gives you an index number (the message's linear position in the mailbox) and the size of each message. UIDL gives you the same index number and a computed hash value for each message.
For each user you can store the size and hash value given by LIST and UIDL. If you see the same size and hash value, assume it is the same message. When a given message no longer appears in this list, assume it has been deleted and clear it from your local memory.
For complete purity, remember the relative positions of the size/hash pairs in the message list, so that you can support the possibility that they may repeat. (My guess on Outlook's new message detection failure is that sometimes these values do repeat, at least for DBMail, but Outlook remembers them even after they are deleted, and forever considers them not new. If it were me, I would try to avoid this behavior.)
Footnote: Remember that the headers are part of the message. Do not trust anything in the header for this reason: dates, senders, even server hand-off information can be easily faked and cannot be assumed unique.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to configure a Facebook app to be used across multiple domains? We have a website application that is deployed and customised for multiple customers, across different domains, we are developing a Facebook Connect app within this website, so people can see what their friends are doing through our sites.
I've set the site url and canvas url in my Facebook app to my localhost for debugging, I was wondering, what if I wanted to use this application across multiple domains? Will facebook only allow postback to one domain per application? Is it possible to configure multiple domains?
EDIT If this isn't possible how are large companies managing multiple domains? Will it have to be setup as one domain per application or is there a way to programatically add a new application through code?
EDIT There is further discussion on this issue here
A: Unfortunately, the September 30, 2011 blog post is worded in a misleading way. The relevant section is "Support for Multiple Domains in the Developer App." Reading that paragraph, it would appear that there are no restrictions in terms of which domains can be lumped together under one application.
However, when I tried adding a second domain to an existing application, I received an error message saying that the new domain must be derived from the Site URL. One comment on that blog post described a similar experience. And that restriction was confirmed by a reply to that comment by someone in Developer Relations at Facebook, explaining that "All app domains must be derived from the site URL."
I believe the confusion arises from incorrect wording in the post itself, which says "Your App’s URL (Website and/or Mobile Web URL) must be derived from one of the domains listed in the App Domain field."
*Update: Just to clarify what types of domains are allowed, let's say your Site URL is "mywebsite.com". You would be allowed to add "mywebsite.co.uk" as an additional App Domain, but you would not be allowed to add "myalternatewebsite.com".
A: I got a partial solution for this! Using this you can add one more domain that is you can have two different domains(independent of each other).
On the Basic settings tab, look for Mobile web url.
Add a url of your app on different domain and then try adding this domain in App Domains.
Hope it helps(little bit).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Groovy newInstance() method missing after set metaClass I define an metaclass
class MyMetaClass extends DelegatingMetaClass {
MyMetaClass(Class theClass){
super(theClass)
println theClass
}
Object invokeStaticMethod(Object object, String methodName, Object[] arguments) {
if(methodName == 'save') {
println 'save method'
return
} else {
return super.invokeMethod(object, methodName, arguments)
}
}
}
and class A:
class A {
private String a
String getA(){
return a
}
}
and register metaclass:
def amc = new MyMetaClass(A)
amc.initialize()
InvokerHelper.metaRegistry.setMetaClass(A, amc)
Now, I try create instance using:
A a2 = A.class.newInstance()
I get error:
Caught: groovy.lang.MissingMethodException: No signature of method: A.newInstance() is applicable for argument types: () values: []
at MyMetaClass.invokeStaticMethod(MyMetaClass.groovy:37)
at test.run(test.groovy:139)
What's the reason? My understanding is I have delegate other methods to super class, the newInstance() method should still callable.
A: I think:
return super.invokeMethod(object, methodName, arguments)
Should be:
return super.invokeStaticMethod(object, methodName, arguments)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count black spots in an image - iPhone - Objective C I need to count the number of black spots in an image(Not the percentage of black spots but the count). Can anyone suggest a step wise procedure that is used in image manipulation to count the spots.
Objective : Count black spots in an image
What I've done till now :
1. Converted image to grayscale
2. Read the pixels for their intensity values
3. I have set a threshold to find darker areas
Other implementations:
1. Gaussian blur
2. Histogram equalisations
What i have browsed :
Flood fill algorithms, Water shed algorithms
Thanks a lot..
A: you should first "label" the image, then count the number of labels you have found.
the label operation is the first operation done in a blob analysis operation: it groups similar adjacent pixels into a single object, and assign a value to this object. the condition for grouping generally is a background/foreground distinction: the label operation will group adjacent pixels which are part of the foreground, where background is defined as pure black or pure white, and foreground is any pixel whose color is not the color of the background.
the label operation is pretty easy to implement and requires not much resources.
_(see the wikipedia article, or this page for more information on labelling. a good paper on the implementation of the label operation is "Two Strategies to Speed up Connected Component Labeling Algorithms" by Kesheng Wu, Ekow Otoo and Kenji Suzuki)_
after labelling, count the number of labels (you can even count the labels while labelling), and you have the number of "black spots".
the next step is defining what a black spot is: converting your input image into a grayscale image (by converting it to HSL and using the luminance plane for example) then applying a threshold should do it. if the illumination of your input image is not even, you may need a better thresholding algorithm (a form of adaptive threshold)...
A: It sounds like you want to label the black spots (Blobs) using a binary image labelling algorithm. This should give you a place to start
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Deleting many object from cache fulfilling given condition I've got model X constructed per other model Y and user U. X is stored in django-cache under key 'X_Y.id_U.id'. Now i want to delete all models X binded to Y from cache (for all users). How can i do this well?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to get menu label in monkeyrunner.? I want to get the menu list items from an android phone. Are there any methods in monkeyrunner to fetch this?
A: From the monkeyrunner description:
Functional testing: monkeyrunner can run an automated start-to-finish
test of an Android application. You provide input values with
keystrokes or touch events, and view the results as screenshots.
Regression testing - monkeyrunner can test application stability by
running an application and comparing its output screenshots to a set
of screenshots that are known to be correct.
So i think, you can't fetch anything, but you can specify a "correct" screenshot and compare it automatically with an actual screenshot to make functional tests.
EDIT: However, you can let monkeyrunner "press" the menu-button via device.press(KEYCODE_MENU, DOWN_AND_UP), take a screenshot and compare it to another one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Identifying and dropping SSL packets I want to drop/block SSL packets between two machines (linux).
I can see the packets using ethereal and use iproute command (linux) to drop these packets.
Is this possible? If yes, what should I use with the iproute command?
Thanks.
A: You can't identify SSL packets at all by their contents, except for the first one in each direction. You could do it via the port number, as long as no form of START TLS was in use in the protocol, so it wouldn't work for SMTP, LDAP, etc. Otherwise you would have to follow entire TCP streams that start with a ClientHello.
Why do you want to do this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access hidden fields value if its Visibility set to false(using C#) How can I access the content of hidden field, where the hiddenfiled's visibility set to Visible=false in the server side using C#. I am not in a situation to use CSS's display:none instead of Visible=false.
A: When you set Visisble=false on the server side it won't actually render the control in the page so there is no way to get the value on the client side.
If you really can't put the value in the page some other way you could do an AJAX request to get the value when you need it?
A: If Visible is false, then the control did not go down to the client, so you cannot directly access it from javascript: it simply isn't there.
Equally, since it is a HiddenField (i.e.<input type="hidden"...>), there is no need to set display:none - it will never be visible, even if Visible is true (although, it will be in the source).
So: either set Visible to true, or come back to the server to get that value.
A: You can't - these fields are not being rendered to the client side.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create Dot Net Nuke user from code Can someone please tell me if it possible to create a new user in a dotnetnuke application from code? I have a list of users that I wish to be added via a windows service.
I've figured out how to write the t-sql side of things but I need to pass in the encrypted password into the procedure, I think I know how to do this as I have access to the machine key, but in the database there is an extra field called passwordsalt, how do I generate this?
A: UserController class has static methods:
CreateUser(ByRef objUser As UserInfo) As UserCreateStatus
GeneratePassword() As String
ChangePassword(ByVal user As UserInfo,
ByVal oldPassword As String,
ByVal newPassword As String) As Boolean
Before calling CreateUser, you'll need to create a UserInfo object and set the properties required for a user, such as the Username. UserController passes the UserInfo to the membership provider, which validates and creates the user. See UserController and AspNetMembershipProvider in the DNN source for more details.
A:
Can someone please tell me if it possible to create a new user in a
dotnetnuke application from code?
If it wasn't possible then dotnetnuke itself couldn't create a user. Look at the code for DotNetNuke and see how a user is created.
I've figured out how to write the t-sql side of things but I need to
pass in the encrypted password into the procedure, I think I know how
to do this as I have access to the machine key, but in the database
there is an extra field called passwordsalt, how do I generate this?
Do yourself a favor and do NOT run your own t-sql query use the method that creates a user instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WebResource reporting 404 file not found I'm working on a system that embeds various JS and CSS resources in the project dll, and access them using WebResource.axd. This all works fine locally, but if I download and install the app from our nightly build server, all our WebResources report a 404 error.
We initially though it was because the downloaded zip file was blocked, and for a while, unblocking the downloaded zip before extracting did work, however, now, nothing seems to work.
Swapping the downloaded dll with the one created locally makes the WebResources work, so it sounds like something is going on with the dll (either on the download server, or during the download process).
Anybody got any ideas what it might be?
A: So I managed to find the culprit myself, which was that the Modified Date timestamp on the DLL's was set to the future (our build server is in a timezone one hour ahead of ours), so for some reason WebResource wasn't picking them up.
Hope this helps someone in the future.
A: This normally occurs if you are using AJAX/3rd party controls. Most probably it is not a problem of missing WebResource.axd but some other reference / resource pointer is missing. Try debugging using the information provided on this site
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to escape the backslashes and the automatically generated escape character in file path in java I have very small and simple problem but I am not getting solutions on it.
Actually I am getting a CSV file path using file chooser.
I am entering the data in this csv file in to database using load data local infile query.
Suppose my entered file path is "C:\title.csv"
When I put this string in to query the you will see the \t combination in the path. This \t which is actually part of the file path and not the escape character '\t'. But the java and mysql consider it as escape character.
then I tried to replace '\' in the file path string with "\\" using following code line.
String filepath="C:\title.csv";
String filepath2=filepath.replace("\\","\\\\");
Still there is not effect on the file path and it still consider the '\t' as escape character.
So my question is how to solve this problem without changing the name of the file?
If we have path like
String filepath="C:\new folder\title.csv";
It will consider the \n and \t as escape character.
how to solve this problem if the name of the file or folder in path cause for escape character?
A: you need to use:
String filepath2=filepath.replace("\\","\\\\");
A: String filepath2=filepath.replace("\","\\") is not valid code - \ is a special character in string literals and needs to be escaped:
String escapedFilepath = filepath.replace("\\","\\\\"); //double all backslashes
A: Use a double slash in Java string literal to escape a slash :
String s = "c:\\new folder\\title.csv";
If an end user enters a string in a JFileChooser, the string variable will contain all the characters entered by the user. Escaping is only needed when using String literals in Java source code.
And use a prepared statement to insert strings into a database table. This will properly escape special characters and avoid SQL injection attacks. Read more about prepared statements in the Java tutorial about JDBC.
A: You have to use escaping in the initial literal (filepath), for example:
String filepath="C:\\title.csv"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Asynchronous File I/O in C++ I can't find information about asynchronous reading and writing in C++. So I write code, function read() works correctly, but synchronization doesn't. Sync() function doesn't wait for the end of reading.
For my opinion variable state_read in thread has incorrect value. Please, understand me why.
struct IOParams{
char* buf;
unsigned int nBytesForRead;
FILE* fp;
};
struct AsyncFile {
FILE* fp;
bool state_read;
HANDLE hThreadRead;
IOParams read_params;
void AsyncFile::read(char* buf, unsigned int nBytesForRead){
sync();
read_params.buf = buf;
read_params.fp = fp;
read_params.nBytesForRead = nBytesForRead;
hThreadRead = CreateThread(0,0,ThreadFileRead,this,0);
}
void AsyncFile::sync() {
if (state_read) {
WaitForSingleObject(hThreadRead,INFINITE);
CloseHandle(hThreadRead);
}
state_read = false;
}
};
DWORD WINAPI ThreadFileRead(void* lpParameter) {
AsyncFile* asf = (AsyncFile*)lpParameter;
asf->setReadState(true);
IOParams & read_params = *asf->getReadParams();
fread(read_params.buf, 1, read_params.nBytesForRead, read_params.fp);
asf->setReadState(false);
return 0;
}
Maybe you know how to write the asynchronous reading in more reasonable way.
A:
Maybe you know how to write the asynchronous reading in more reasonable way.
Since your question is tagged "Windows", you might look into FILE_FLAG_OVERLAPPED and ReadFileEx, which do asynchronous reading without extra threads (synchronisation via an event, a callback, or a completion port).
If you insist on using a separate loader thread (there may be valid reasons for that, though few), you do not want to read and write a flag repeatedly from two threads and use that for synchronisation. Although your code looks correct, the mere fact that does not work as intended shows that it's a bad idea.
Always use a proper synchronisation primitive (event or semaphore) for synchronisation, do not tamper with some flag that's (possibly inconsistently) written and read from different threads.
Alternatively, if you don't want an extra event object, you could always wait on the thread to die, unconditionally (but, read the next paragraph).
Generally, spawning a thread and letting it die for every read is not a good design. Not only is spawning a thread considerable overhead (both for CPU and memory), it can also introduce hard to predict "funny effects" and turn out to be a total anti-optimization. Imagine for example having 50 threads thrashing the harddrive on seeks, all of them trying to get a bit of it. This will be asynchronous for sure, but it will be a hundred times slower, too.
Using a small pool of workers (emphasis on small) will probably be a much superior design, if you do not want to use the operating system's native asynchronous mechanisms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Generate Winnovative PDF to be a certain width/height pixel size I'm looking to generate a PDF document from HTML using the Winnovative PDF Converter
I wish to convert the PDF to exactly 842 x 595 pixels
I've tried doing:
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A5
But this doesn't fit right. So I tried:
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Custom
pdfConverter.PdfDocumentOptions.CustomPdfPageSize = New SizeF(842, 595)
However this doesn't work right either as I think the size is measured in a different format to pixels?
How can I generate a PDF at exactly 842 x 595 pixels so that it matches my HTML content?
A: There are 2 things involved when rendering the HTML content to PDF. The PDF page size and the converter internal HTML viewer width. When FitWidth is enabled the HTML content can be scaled down to fit the PDF page width.
The PDF page size is expressed in points (1 point is 1/72 inch) and the internal HTML viewer window size is expressed in pixels (i pixel is 1/96 inch).
The PDF page A4 potrait size is 595 x 842 points and the HTML viewer width corresponding to the 595 points is 595 x 96 / 72 = 793 pixels.
So the settings of the converter are:
pdfConverter.HtmlViewerWidth = 793
pdfConverter.PdfDocumentOptions.PdfPageSize = new PdfPageSize(595,842)
You can find a description of all the HTML scaling and fitting options and sample code in the Control HTML Scaling in PDF Page demo. Below is a copy of the relevant code from that demo:
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Html Viewer Options
// Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width
// This is a preferred width of the browser but the actual HTML content width can be larger in case the HTML page
// cannot be entirely displayed in the given viewer width
// This property gives the size of the HTML content which can be further scaled to fit the PDF page based on selected options
// The HTML content size is in pixels and the PDF page size is in points (1 point = 1/72 inches)
// The converter is using a 96 DPI resolution to transform pixels to points with the following formula: Points = Pixels/96 * 72
htmlToPdfConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text);
// Set HTML viewer height in pixels to convert the top part of a HTML page
// Leave it not set to convert the entire HTML
if (htmlViewerHeightTextBox.Text.Length > 0)
htmlToPdfConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text);
// Set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels
// If this option is false then the actual HTML content width can be larger than HtmlViewerWidth pixels in case the HTML page
// cannot be entirely displayed in the given viewer width
// By default this option is false and the HTML content is not clipped
htmlToPdfConverter.ClipHtmlView = clipContentCheckBox.Checked;
// PDF Page Options
// Set PDF page size which can be a predefined size like A4 or a custom size in points
// Leave it not set to have a default A4 PDF page
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();
// Set PDF page orientation to Portrait or Landscape
// Leave it not set to have a default Portrait orientation for PDF page
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();
// Set PDF page margins in points or leave them not set to have a PDF page without margins
htmlToPdfConverter.PdfDocumentOptions.LeftMargin = float.Parse(leftMarginTextBox.Text);
htmlToPdfConverter.PdfDocumentOptions.RightMargin = float.Parse(rightMarginTextBox.Text);
htmlToPdfConverter.PdfDocumentOptions.TopMargin = float.Parse(topMarginTextBox.Text);
htmlToPdfConverter.PdfDocumentOptions.BottomMargin = float.Parse(bottomMarginTextBox.Text);
// HTML Content Destination and Spacing Options
// Set HTML content destination in PDF page
if (xLocationTextBox.Text.Length > 0)
htmlToPdfConverter.PdfDocumentOptions.X = float.Parse(xLocationTextBox.Text);
if (yLocationTextBox.Text.Length > 0)
htmlToPdfConverter.PdfDocumentOptions.Y = float.Parse(yLocationTextBox.Text);
if (contentWidthTextBox.Text.Length > 0)
htmlToPdfConverter.PdfDocumentOptions.Width = float.Parse(contentWidthTextBox.Text);
if (contentHeightTextBox.Text.Length > 0)
htmlToPdfConverter.PdfDocumentOptions.Height = float.Parse(contentHeightTextBox.Text);
// Set HTML content top and bottom spacing or leave them not set to have no spacing for the HTML content
htmlToPdfConverter.PdfDocumentOptions.TopSpacing = float.Parse(topSpacingTextBox.Text);
htmlToPdfConverter.PdfDocumentOptions.BottomSpacing = float.Parse(bottomSpacingTextBox.Text);
// Scaling Options
// Use this option to fit the HTML content width in PDF page width
// By default this property is true and the HTML content can be resized to fit the PDF page width
htmlToPdfConverter.PdfDocumentOptions.FitWidth = fitWidthCheckBox.Checked;
// Use this option to enable the HTML content stretching when its width is smaller than PDF page width
// This property has effect only when FitWidth option is true
// By default this property is false and the HTML content is not stretched
htmlToPdfConverter.PdfDocumentOptions.StretchToFit = stretchCheckBox.Checked;
// Use this option to automatically dimension the PDF page to display the HTML content unscaled
// This property has effect only when the FitWidth property is false
// By default this property is true and the PDF page is automatically dimensioned when FitWidth is false
htmlToPdfConverter.PdfDocumentOptions.AutoSizePdfPage = autoSizeCheckBox.Checked;
// Use this option to fit the HTML content height in PDF page height
// If both FitWidth and FitHeight are true then the HTML content will resized if necessary to fit both width and height
// preserving the aspect ratio at the same time
// By default this property is false and the HTML content is not resized to fit the PDF page height
htmlToPdfConverter.PdfDocumentOptions.FitHeight = fitHeightCheckBox.Checked;
// Use this option to render the whole HTML content into a single PDF page
// The PDF page size is limited to 14400 points
// By default this property is false
htmlToPdfConverter.PdfDocumentOptions.SinglePage = singlePageCheckBox.Checked;
string url = urlTextBox.Text;
// Convert the HTML page to a PDF document using the scaling options
byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=HTML_Content_Scaling.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
A: If you set the PdfConverter.PageWidth and PdfConverter.PageHeight attributes to 842 and 595 then that should cause your web content to fill the whole PDF page area.
There is also a FitWidth property which can be set to False if you want your web content to not be scaled down to fit the available page area. This will mean that your content will overflow the page if it is too large though.
Another point to raise about Winnovative PDF is that it is not easy to work with high resolution images, so depending on your PDF needs (and input) you may struggle to get good quality images - maybe that was just from my experience though.
Speaking of images, it seems that Winnovative PDF takes your input html and creates a single image of it all which then gets added to the PDF at screen resolution (72 dpi) and this can even make simple text look low quality.
If you fancied having a go at handle the html layout yourself you could always convert your content straight to PDF using another product such as ITextSharp which would allow more flexibility over higher resolution images. I really depends on your overall needs though
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get included method names How I can get all instance method names in the baz method call, which are only present in the Bar module (without other instance methods of this class) ?
class Foo
include Bar
def a
end
def b
end
def baz
#HERE
end
end
A: class Foo
include Bar
def a
end
def b()
end
def baz
Bar.instance_methods(false)
end
end
puts Foo.new.baz
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NSUserDefaults - storing and retrieving data I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.
I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.
here's the code that Im displaying the NSUserDefaults stored info on a UILabel:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];
NSLog(@"Value from standardUserDefaults: %@", aValue);
NSLog(@"Label: %@", myLabel);
myLabel.text = aValue;
if someone could point me in the right direction that would be great,
thanks
A: When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:
[[NSUserDefaults standardUserDefaults] synchronize];
This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.
A: Do not forget the use synchronize when you set some value
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:@"KEY_NAME"];
[defaults synchronize];
Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue = [defaults objectForKey:@"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : @"No Value";
Hope it helps
A: Put this text in
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];
NSLog(@"Value from standardUserDefaults: %@", aValue);
NSLog(@"Label: %@", myLabel);
myLabel.text = aValue;
}
And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults
A: In Swift we can do it following way:
To save value:
let defaults = UserDefaults.standard
defaults.set(YOUR_VALUE, forKey: "YOUR_KEY_NAME")
To get value:
let defaults = UserDefaults.standard
let data = defaults.objectForKey("YOUR_KEY_NAME")
For more details visit:
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Html Agility Pack merged queries I have a table kind of:
...some td's with not needed links
<td>1010</td>
<td>Building</td>
<td>Adress stree 55</td>
<td>00000 City</td>
<td>
<a href="http://www.adress.xy/file.kml" target="_self">
<img align="top" border="1" src="/custom/img/kml.gif" alt="Details" title="Details" />
</a>
</td>
I use this query to get the innertext information:
HtmlDocumet doc = new HtmlDocument();
doc.LoadHtml(html);
var node = doc.DocumentNode.Descendants("table")
.FirstOrDefault(x => x.Attributes["style"].Value == "table-layout:auto")
.Elements("tr")
.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToArray)).ToArray();
but I would also like to add to the array an url with .kml links.
So the question is: how is it possible to merge querys to get innertext and the kml link?
the result of this query is:
string[i][j]
where i= number of tr- elements and j - number of td- elements
Example:
string[0][0]="1010"
string[0][1]="Building"
I would like also to have: string[i][4] = "http://www.adress.xy/file.kml"
P.S. the whole table is here.
A: I wouldn't worry about getting arrays of arrays, it would be better if you got lists instead.
const string url = "http://www.rwth-aachen.de/go/id/yvu/scol/1/sasc/1/pl/313";
const string kml = "http://www.adress.xy/file.kml";
var newKml = new[] { kml };
var web = new HtmlWeb();
var doc = web.Load(url);
var xpath = "//table[@style='table-layout:auto']/tr[td]";
var rows = doc.DocumentNode.SelectNodes(xpath);
var table = rows
.Select(row =>
row.Elements("td")
.Skip(1)
.Take(4)
.Select(col => System.Net.WebUtility.HtmlDecode(col.InnerText))
.Concat(newKml)
.ToList()
).ToList();
I would consider making an anonymous type to represent your rows that way you could give more useful names you your columns. Perhaps even put the results in a DataTable instead.
Just in case you won't be able to use xpath for whatever reason (or you wanted to know the equivalent LINQ queries), you could replace the line that uses the xpath with this:
var rows = doc.DocumentNode.Descendants("table")
.Where(t => t.Attributes["style"].Value == "table-layout:auto")
.SelectMany(t => t.Elements("tr").Where(tr => tr.Elements("td").Any()));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF raised Duplex Event results in WinForm Event to null I have a winForm App that connects to WCF, using duplex channels with a custom Interface.
The callbacks work correctly, however attempting to raise an Event from a Callback Event has me stuck in the mud.
On the support class I use to connect to the WCF Service, I use a single Event to raise messages I then display in an output textbox control on the main application form.
The OnEvent in the support class is defined:
protected virtual void OnMsgEvent(SurfaceArgs e)
{
MsgEventEventHandler temp = MsgEvent;
if (temp != null)
{
temp(this,e);
}
}
The Event implemented from the WCF Callback is defined:
public void OnEvent4(string sValue)
{
OnMsgEvent(new SurfaceArgs(sValue, EventLogEntryType.Information));
}
When I make the call from the WCF Event, the OnMsgEvent validation for null always results in null at:
if (temp != null)
It's as if the Event being raised from the WCF is on a separate thread or something, and I'm not sure how to invoke it or delegate it so I can make the call to the OnMsgEvent.
For the moment, I'm passing a pointer to the main form and calling a public method. I expected this temp solution to require an Invoke on the Textbox control, but it doesn't.
The solution is probably something simple, I just don't see it yet. =)
A: After researching a similair question I later discovered:
Using a Callback to pass an Event to a WCF Client
I noticed a reference to the Callback used in the linked article being passed as a "this" object type.
The initial client design used a new instance of the Callback class when creating the InstanceContext.
So instead of using:
_context = new InstanceContext(new IMyCallback());
It worked the way I had expected when I changed it to:
_context = new InstanceContext(this);
The support class extends the IMyCallback interface, so maybe by passing "this" it satisfied the InstanceContext requirements of (object implementation). It works, so I'm not complaining!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to stream big files (like CSV/XML) in rails 3.1? In Rails 3.0 it was possible to stream big files, like CSV or XML, with the self.response_body hack.
Rails 3.1 killed this feature and added streaming. Only that streaming doesn't seem to work, or there isn't documentation on how to send large files. I tried with partials, without partials, with html.erb view instead of csv.erb, and nothing works.
How can you stream large files in rails 3.1?
A: if you use Apache/Phusion passenger, have you tried using the rack-based x-sendfile ?
EDIT: more info here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Class Loader Exception while working with Maps in android I got the following Class not found exception while working with map based application
09-26 15:33:19.810: ERROR/AndroidRuntime(27866):
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.zyksatwo/com.zyksatwo.MapRouteActivity}:
java.lang.ClassNotFoundException: com.zyksatwo.MapRouteActivity in
loader dalvik.system.PathClassLoader[/data/app/com.zyksatwo-1.apk]
09-26 15:33:19.810: ERROR/AndroidRuntime(27866): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1618)
09-26 15:33:19.810: ERROR/AndroidRuntime(27866): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1716)
09-26 15:33:19.810: ERROR/AndroidRuntime(27866): at
android.app.ActivityThread.access$1500(ActivityThread.java:124) 09-26
15:33:19.810: ERROR/AndroidRuntime(27866): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:968)
09-26 15:33:19.810: ERROR/AndroidRuntime(27866): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-26
15:33:19.810: ERROR/AndroidRuntime(27866): at
android.os.Looper.loop(Looper.java:130) 09-26 15:33:19.810:
ERROR/AndroidRuntime(27866): at
android.app.ActivityThread.main(ActivityThread.java:3806) 09-26
15:33:19.810: ERROR/AndroidRuntime(27866): at
java.lang.reflect.Method.invokeNative(Native Method) 09-26
15:33:19.810: ERROR/AndroidRuntime(27866): at
java.lang.reflect.Method.invoke(Method.java:507) 09-26 15:33:19.810:
ERROR/AndroidRuntime(27866): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-26 15:33:19.810: ERROR/AndroidRuntime(27866): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-26
15:33:19.810: ERROR/AndroidRuntime(27866): at
dalvik.system.NativeStart.main(Native Method) 09-26 15:33:19.810:
ERROR/AndroidRuntime(27866): Caused by:
java.lang.ClassNotFoundException: com.zyksatwo.MapRouteActivity in loader dalvik.system.PathClassLoader[/data/app/com.zyksatwo-1.apk
Please help me to figure out the mistake I did here
A: did you add <uses-library android:name="com.google.android.maps" /> in your menifest file?
if not then plz add this Tag inside your Application Tag in your Menifest.xml file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: running main thread frm another thread I have run a secondary thread which some operations are carried on. Then while executing in secondary thread i want to call some operations on main thread. Can any one have sample code for it. I could not find it from google.
Here is my sample call:
Glib::thread_init();
Glib::Thread *const myThread = Glib::Thread::create(sigc::mem_fun(*this, &MyClass::MyFunction), true);
myThread->join();
MyClass::MyFunction()
{
//here i want to call the function from main thread
AnotherFunction();
}
MyClass::AnotherFunction()
{
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Monodroid - Drag View with Touch event? I want to drag a view. Until now i tried it with a LinearLayout and margins and with a AbsoluteLayout.
AbsoluteLayout example:
button.Touch = (clickedView, motionEvent) =>
{
Button b = (Button)clickedView;
if (motionEvent.Action == MotionEventActions.Move)
{
AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(100, 35, (int)motionEvent.GetX(), (int)motionEvent.GetY());
b.LayoutParameters = layoutParams;
}
return true;
};
In every case I tried I got a curios behaviour. Here's why. The view i'm dragging follows my finger but jumps always between two positions. One postition hits my finger the other is somewhere to my fingers left-top. If I'm just writing my current position into a textview (without moving the view) the coordinates behave as expected. But if i'm also moving the view they are jumping again.
How can i avoid this?
EDIT: I used sounds comment on my question to implement a working draging for monodroid (it is done for Java/Android SDK in the linked site). Maybe others are interested in doing that some day, so here's my solution:
[Activity(Label = "Draging", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
private View selectedItem = null;
private int offset_x = 0;
private int offset_y = 0;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
ViewGroup vg = (ViewGroup)FindViewById(Resource.Id.vg);
vg.Touch = (element, motionEvent) =>
{
switch (motionEvent.Action)
{
case MotionEventActions.Move:
int x = (int)motionEvent.GetX() - offset_x;
int y = (int)motionEvent.GetY() - offset_y;
int w = WindowManager.DefaultDisplay.Width - 100;
int h = WindowManager.DefaultDisplay.Height - 100;
if (x > w)
x = w;
if (y > h)
y = h;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
LinearLayout.LayoutParams.WrapContent,
LinearLayout.LayoutParams.WrapContent));
lp.SetMargins(x, y, 0, 0);
selectedItem.LayoutParameters = lp;
break;
default:
break;
}
return true;
};
ImageView img = FindViewById<ImageView>(Resource.Id.img);
img.Touch = (element, motionEvent) =>
{
switch (motionEvent.Action)
{
case MotionEventActions.Down:
offset_x = (int)motionEvent.GetX();
offset_y = (int)motionEvent.GetY();
selectedItem = element;
break;
default:
break;
}
return false;
};
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Full width left-aligned list Is it possible to stretch and unordered list to fill the full page-width; floating list-items (left) inside of it, without list-items getting clipped if they overflow (hidden) the unordered list?
If I simply do overflow: none; on the unordered list, whatever list-items are inside, which wont fit a 100 percent, are not shown.
This is what I want...
http://roosteronacid.com/stackoverflow.png
Notice that the first and third list-items are shown, even if the unordered list isn't able to show/house them in their full width.
A: You should set ul to display: table, and li to table-cell. Here is example:
http://jsfiddle.net/simoncereska/4w92q/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: display images in tag using nsdata is this possible? my app will download a zip file from the server and I save all the images in an array like this:
ZipReadStream *read = [unzipFile readCurrentFileInZip];
NSMutableData *data = [[NSMutableData alloc] initWithLength:info.length];
int bytesRead= [read readDataWithBuffer:data];
if(bytesRead > 0)
{
[imagesData addObject:data];
[imagesName addObject:info.name];
}
then I filter w/c images to be displayed inside the uiview and w/c images to be displayed inside the uiwebview. I display the images inside the uiview like this:
UIImage *imageForThisQuestion = [[UIImage alloc]initWithData:[imagesData
objectAtIndex:indexOfThisImage]];
this works fine inside the uiview. but how do I display the some of the images inside the uiwebview? can I use the tag here? and also my uiwebview might appear in this format:
"blah blah blah blah <img src...> blah blah blah <img src...>"
A: You don't want to save an image in file to refer on it in html like < img src="myimage.png">, right? You can use data URI scheme to encode your image into URI, and use img tag like
< img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" >
Read hear how to base64 encode NSData of your image.
A: For anyone wanting a quick and clear answer and slip reading the whole article supplied above, this is the code you want to use:
NSString* imgInBase64 = [imageObject base64EncodedStringWithOptions:0];
NSString* imgSrcValue = [@"data:image/png;base64," stringByAppendingString:imgInBase64]
and you inject that string to any <img src="{{imgSrcValue}}"> element. Notice the 0 value to the base64EncodedStringWithOptions which may help you avoid crashes with images which produce huge Base64 strings. Also you can change the png to any supported image format
A: You have to load the HTML code with the correct baseURL:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Then, in your HTML code:
<img src="myimage.png">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Creating DateTime object from DatePicker and TimePicker control How to create DateTime object from DatePicker and TimePicker controls in Windows Phone 7?
DateTime object constructor accepts only int with years, months etc. Is there a smart way to combine date and time and assign it to DateTime ?
A: use
DateTime MyDateTime = ((DateTime) MyDatePicker.Value).Date.Add (((DateTime)MyTimePicker.Value).TimeOfDay);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: css cursor:pointer I have this code over here
.file-wrapper {
cursor: pointer;
display: inline-block;
overflow: hidden;
position: relative;
}
.file-wrapper input {
cursor: pointer;
font-size: 100px;
height: 100%;
filter: alpha(opacity=1);
-moz-opacity: 0.01;
opacity: 0.01;
position: absolute;
right: 0;
top: 0;
}
.file-wrapper .button {
background: #79130e;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
color: #fff;
cursor: pointer;
display: inline-block;
font-size: 11px;
font-weight: bold;
margin-right: 5px;
padding: 4px 18px;
text-transform: uppercase;
}
<span class="file-wrapper">
<input type="file" name="photo" id="photo" />
<span class="button">Choose a Photo</span>
</span>
in Safari and Google chrome browsers it does not show the cursor as pointer, so what's wrong?
A: Styling a <input type='file'> can be hit-and-miss.
A lot of functionality is removed from these fields, due to security issues, including some CSS styling functionality. This is because if a file input field can be styled to look like something else, it may be possible for a malicious site to trick users into uploading files without intending to.
The exact features which are disabled for file input fields varies between browsers, so my guess is that the cursor style is disabled for these fields in Webkit-based browsers but not in other browsers.
I can see in your Fiddle that you've made quite an effort to get around some of these restrictions by overlaying a button on top of your file input field, but my guess is that the cursor restriction is going to be harder to work around.
If this is the case, then it is something you are just going to have to live with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenGL performing very slowly Working on a game, and I was testing out my renderer. It unfortunately only runs at about 4 frames per second. Profiling reveals that surprisingly, only 5% of that runtime belongs to my code, and the remaining 95% of the total run time was spent in nvoglnt.dll.
Only one 256x256 texture is used though, and beyond that, the only openGL code I use outside of a few camera transformations is this following template of code. It is executed only 134217728 times for a total of 33554432 quads.
glTexCoord2f(u, v);
glColor3f(r, g, b);
glVertex3f(x, y, z);
What could I be doing wrong that's causing OpenGL to become so slow? Are there any common performance techniques I could use to improve it?
A: As datenwolf said, 134217728 is a lot of times. 33 million quads is even a lot if you were using vertex arrays. But modern cards should handle it pretty well.
The bottleneck here is completely the CPU, you're calling 134 million x 3 functions every frame. Since you're running at 4FPS. That's 1.6 billion function calls a second! No wonder it's running so slow.
What you should do is use Vertex Buffer Objects. It doesn't matter how volatile your data is, even if you have to update it every frame, it will be faster.
With that out of the way, I'm curious as to why you need to render 33 million volatile quads? If you give us a broader overview of what you are doing, we could propose other optimisation techniques.
A:
It is executed only 134217728 times for a total of 33554432 quads.
Each of those "few" calls makes your system to switch execution context between your program and the OpenGL driver. This is not "few". Honestly I'd consider this question some fine trolling, because each and every OpenGL tutorial these days will tell you not to use immediate mode for excactly that serious performance hit you observed, which immediate mode causes, i.e. glBegin, glEnd, glVertex and so on.
Use Vertex Arrays or better yet Vertex Buffer Objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Read bluetooth RSSI value using J2ME I want to get RSSI value using J2ME. How can I get that value.
A: AFAIK there is no API available for getting the Bluetooth RSSI value in Java ME.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7553688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.