text
stringlengths 8
267k
| meta
dict |
---|---|
Q: jQuery - attribute vs. property
Possible Duplicate:
.prop() vs .attr()
Is there a difference between an attribute and a property in the jQuery terminology? Is there an example that can clarify this point?
A:
Is there a difference between an attribute and a property in the jQuery terminology?
Yes, there is a difference.
For example...
<input type="text" name="age" value="25" />
jsFiddle.
The attribute would be the value attribute as in the markup. You would use attr('value').
The property would be the value property as accessed via the DOM API. You would use prop('value') (strictly speaking, you'd use val()).
Sometimes they can be very similar, but not always.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Graph API save login information I am using the Graph API for Facebook on my iPhone application. The problem is, I don't want the user to have to re enter their email address each time they want to login to integrate Facebook with my app. Is there a way to save and auto fill the login information using the Graph API?
A: Using the Graph API, there is no need for you to store the credentials, more than that, you should NOT store the credentials. As explained in the API dedicated help page the authentication process is handled by a secure token.
Meaning that if the user is already authenticated on Facebook using another application, it might be ( based on authentication process used ) already authenticated within your app.
You might check the token validity by using the isSessionValid method from the Facebook class.
Have a look to the iOS Facebook SSO link, it explains everything you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a digital clock with custom images for hours and seconds in iPhone? I am having 10 images from 0-10 for setting the hour and minutes of my digital clock. I am getting confused on how to set a custom image to digital clock so that it will start working.
This is my code:
- (void)viewDidLoad {
//timer to recursively call the showClock method.
timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(showClock) userInfo:nil repeats:YES];
[super viewDidLoad];
}
-(void)showClock
{
NSDate *dateShow= [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setTimeStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormat stringFromDate:dateShow];
NSDate * date = [NSDate date];
NSCalendar * calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * components =
[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger firstHourDigit = hour/60;
NSInteger secondHourDigit = hour%60;
NSInteger firstMinuteDigit = minute/60;
NSInteger secondMinuteDigit = minute%60;
[minfirstImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"0.png", firstHourDigit]]];
[minsecondImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%0.png",secondHourDigit]]];
[secfirstImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%0.png",firstMinuteDigit]]];
[secSecondImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%0.png",secondMinuteDigit]]];
}
When I run my app, the imageview is not displayed with the image. What may be the problem? Is there any problem in the calculation?
A: Rani...
I think used different images for timing is increase the your apps size , so i have one suggestion for you just check this code and make changes as per your requirement i think this is best way to display time as you want,,
for this code you have to create only one background image without text...
- (void)viewDidLoad {
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(showClock) userInfo:nil repeats:YES];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showClock
{
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate* now = [NSDate date];
int h = [[cal components:NSHourCalendarUnit fromDate:now] hour];
int m = [[cal components:NSMinuteCalendarUnit fromDate:now] minute];
int s = [[cal components:NSSecondCalendarUnit fromDate:now] second];
[cal release];
// NSInteger firstHourDigit = hour/60;
// NSInteger secondHourDigit = hour%60;
// NSInteger firstMinuteDigit = minute/60;
// NSInteger secondMinuteDigit = minute%60;
NSLog(@"\n Time :%d : %d : %d",h,m,s);
[imgViewHour setImage:[self getImageFor:[NSString stringWithFormat:@"%d",h]]];
[imgViewMnt setImage:[self getImageFor:[NSString stringWithFormat:@"%d",m]]];
[imgViewSec setImage:[self getImageFor:[NSString stringWithFormat:@"%d",s]]];
}
-(UIImage *)getImageFor:(NSString*)txt {
int w =50,h=35;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, w-6, h-6)];
lbl.text = txt;
lbl.textColor = [UIColor whiteColor];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont fontWithName:@"Arial" size:18];
lbl.font = [UIFont boldSystemFontOfSize:14];
[lbl setBackgroundColor:[UIColor clearColor]];
lbl.shadowOffset=CGSizeMake(0,2);
lbl.shadowColor = [UIColor blackColor];
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
[viewImage setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"imageBackGround.png"]]];
[viewImage addSubview:lbl];
UIGraphicsBeginImageContext(viewImage.bounds.size);
[viewImage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *Image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[viewImage release];
return Image;
}
Thanks ... :)
A: Maintain an array of UIImages and then break down the string character by character to check out what number there is:
create array for images
load images into array
create array for imageviews
put imageviews into array
loop 5 times
if we're on 2 then skip // dot
else create substring from that character and call integerValue on it
use that as index into array
set imageview at index to image at index
A: Take images name as from 0.png-9.png and try with below code it will help you
NSDate *dateShow= [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setTimeStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormat stringFromDate:dateShow];
NSDate * date = [NSDate date];
NSCalendar * calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * components =
[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger firstHourDigit = hour/10;
NSInteger secondHourDigit = hour%10;
NSInteger firstMinuteDigit = minute/10;
NSInteger secondMinuteDigit = minute%10;
int res=0;
for(int i =0;i<4;i++)
{
if(i==0)
res = firstHourDigit;
else if(i==1)
res = secondHourDigit;
else if (i==2)
res = firstMinuteDigit;
else
res = secondMinuteDigit;
NSString *str_imageName;
switch (res) {
case 0:
str_imageName=@"0.png";
break;
case 1:
str_imageName=@"1.png";
break;
case 2:
str_imageName=@"2.png";
break;
case 3:
str_imageName=@"3.png";
break;
case 4:
str_imageName=@"4.png";
break;
case 5:
str_imageName=@"5.png";
break;
case 6:
str_imageName=@"6.png";
break;
case 7:
str_imageName=@"7.png";
break;
case 8:
str_imageName=@"8.png";
break;
case 9:
str_imageName=@"9.png";
break;
default:
break;
}
if(i==0)
[minfirstImage setImage:[UIImage imageNamed:str_imageName]];
else if(i==1)
[minsecondImage setImage:[UIImage imageNamed:str_imageName]];
else if (i==2)
[secfirstImage setImage:[UIImage imageNamed:str_imageName]];
else
[secSecondImage setImage:[UIImage imageNamed:str_imageName]];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Troubleshooting ui.item in jQuery I'm currently using the jQuery sortable plugin and one of the things I can do is on change I can run a function:
$( "#listA, #listB" ).sortable({
connectWith: ".connected_sortable",
delay: 100,
receive: function(event, ui) {
alert(ui.item.text());
}
}).disableSelection();
In this case I'm using an alert. How do I figure out what objects are in the ui.item? text() currently gives me the text I've used in the but how do I find out all of the other information? More specifically the id? I couldn't find information on this in the jQuery Documentation. Is there a way to use Firebug to find out what functionality ui.item has?
Thank you!
A: console.log("%o", ui.item);
or set a breakpoint inside the function with firebug, then right click the ui and 'inspect in dom'.
A: You could also use
ui.item.attr("id");
ui is a normal jQuery wrapped element
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS :first-letter not working I'm trying to apply CSS styles to some HTML snippets that were generated from a Microsoft Word document. The HTML that Word generated is fairly atrocious, and includes a lot of inline styles. It goes something like this:
<html>
<head></head>
<body>
<center>
<p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span
style='font-size:12.0pt;line-height:115%;font-family:"Times New Roman"'>Title text goes here<o:p></o:p></span></b></p>
<p class=MsoNormal style='margin-left:18.0pt;line-height:150%'><span
style='font-size:12.0pt;line-height:150%;font-family:"Times New Roman"'>Content text goes here.<o:p></o:p></span></p>
</body>
</html>
...and very simply, I would like to style the first letter of the title section. It just needs to be larger and in a different font. To do this I am trying to use the :first-letter selector, with something kind of like:
p b span:first-letter {
font-size: 500px !important;
}
But it doesn't seem to be working. Here's a fiddle demonstrating this:
http://jsfiddle.net/KvGr2/
Any ideas what is wrong/how to get the first letter of the title section styled correctly? I can make minor changes to the markup (like adding a wrapper div around things), though not without some difficulty.
A: This is because :first-letter only operates on block / inline-block elements. SPAN is an inline element.
Taken from http://reference.sitepoint.com/css/pseudoelement-firstletter:
The :first-letter pseudo-element is mainly used for creating common
typographical effects like drop caps. This pseudo-element represents
the first character of the first formatted line of text in a
block-level element, an inline block, a table caption, a table cell,
or a list item.
A: ::first-letter does not work on inline elements such as a span. ::first-letter works on block elements such as a paragraph, table caption, table cell, list item, or those with their display property set to inline-block.
Therefore it's better to apply ::first-letter to a p instead of a span.
p::first-letter {font-size: 500px;}
or if you want a ::first-letter selector in a span then write it like this:
p b span::first-letter {font-size: 500px !important;}
span {display:block}
MDN provides the rationale for this non-obvious behaviour:
The ::first-letter CSS pseudo-element selects the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line.
...
A first line has only meaning in a block-container box, therefore the ::first-letter pseudo-element has only an effect on elements with a display value of block, inline-block, table-cell, list-item or table-caption. In all other cases, ::first-letter has no effect.
Another odd case(apart from not working on inline items) is if you use :before the :first-letter will apply to the before not the actual first letter see codepen
Examples
*
*http://jsfiddle.net/sandeep/KvGr2/9/
*http://krijnhoetmer.nl/stuff/css/first-letter-inline-block/
References
https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter
http://reference.sitepoint.com/css/pseudoelement-firstletter
A: You can get the intended behavior by setting the span's display property to inline-block:
.heading span {
display: inline-block;
}
.heading span:first-letter {
color: red;
}
<div class="heading">
<span>An</span>
<span>Interesting</span>
<span>Heading</span>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: Javascript : How do I achieve this execution order? I have something like this.
function a() {
ajax(callback_function);
}
callback_function() {
// done!, called after ajax is finished
}
function b() {
a();
c(); // make sure c is executed AFTER a is finished.
}
function c() {
// called after a()!
}
How do I make sure that the function c() is called AFTER a() is finished? I think I have to use another callback function, but unsure of what to do.
EDIT
Didn't make it clear. I'd prefer if I didn't call c() inside my callback_function since a() can be called without needing to call c().
A: You could call c() from your callback function
A: You can rework a so it takes a callback function as a parameter. That way, you can call it for the scenario where c needs to be called after and where it doesn't need to be called:
function a(callback) {
ajax(callback);
}
function callback_function() { }
function b() {
a(function() {
callback_function();
c();
});
}
function b2() {
a(callback_function);
}
function c() { }
A: you can wrap all your callbacks into an anonymous function :
function a(callback) {
ajax(function(){
callback_function();
callback();
});
}
callback_function() {
// done!, called after ajax is finished
}
function b() {
a(c);
// make sure c is executed AFTER a is finished.
}
function c() {
// called after a()!
}
or you could register another callback to your callback_function :
function a(callback) {
ajax(function(){
callback_function(callback);
});
}
callback_function(callback) {
// done!, called after ajax is finished
callback();
}
function b() {
a(c);
// make sure c is executed AFTER a is finished.
}
function c() {
// called after a()!
}
A more elegant (and better) way is to bind callbacks to a certain custom event such as "ajax-done" and after the ajax code successfully executes, you can trigger that specific event.
If you use jquery, the event-method is quite simple :
function a() {
ajax(function(){
$(window).trigger('ajax-done');
});
}
callback_function() {
// done!, called after ajax is finished
}
function b() {
a();
// make sure c is executed AFTER a is finished.
}
function c() {
// called after a()!
}
$(window).bind('ajax-done',callback_function);
$(window).bind('ajax-done',c);
Of course you can do the same thing without jquery, but it's a bit messier since you have to make sure that your code is cross-browser.
A: If you don't want to tie your callback with calling c() directly you have 2 options:
1.Either change a to this:
function a(fn) {
ajax(function() {
callback_function();
if (fn) fn();
});
}
And now you have:
function b() {
a(c);
}
2.Add a signal at the end of callback_function:
function callback_function() {
// ...
emit('callback_done', { param1: true, param2, false });
}
function b() {
connect('callback_done', c);
a();
}
A: No need to create another callback, simply call the c function in the end of callback function
function a() {
ajax(callback_function);
}
callback_function() {
// Do whatever you need with data from ajax
c();
}
function b() {
a();
}
function c() {
// called after a()!
}
A: If I've understood what you're trying to do properly, you could use an anonymous function for this particular case, which means you won't have to modify or duplicate your callback function:
function a() {
ajax(function() {
callback_function();
c();
});
}
function callback_function() {}
function c() {}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Better Exception Handling in JPA I used EJB3/JPA when persisting my entities and I am happy on how it is able to manage my DB related
task.
My only concern is on the exception handling. My sample code when saving entity always comes in this flavor.
Most of the tutorials that I read on the net comes in this flavor also with no regards to exception handling.
@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;
public void save(Student student) {
em.persist(student);
}
}
But I dont know whats the best way of exception handling in an EJB app?
What should be the best way when handling exception?
Is this how others is handling the exception? A try catch block on your session facade?
@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;
public void save(Student student) {
try {
em.persist(student);
} catch(Exception e) {
//log it or do something
}
}
}
or letting the method throw an exception?
public void save(Student student) throws Exception {
em.persist(student);
}
I dont know if my understanding is correct since I am still learning EJB.
Thanks
A: If you want you method to throw the exception got from em.persistance(...), then don't surround that statement with that try/catch block (cause that will catch every exception that's in that block).
The way you approach this problem depends on the application, whether there already exists some legacy code or not. In the case there is legacy code, I suggest you use the same approach (even in for some cases it's not speed optimal) to maintain consistency.
Otherwise I'd suggest following exceptions' "rule of thumb" - they should be treated in the first place where you have all the information you need about them to take an action, else throw them so someone else can handle. (If you throw them away make sure to throw the most specific form of exception that you could throw (not the general Exception)). Handling exceptions when using JPA is no different then handling Java exceptions in general.
I hope this was simple enough information about exceptions without starting a "religious conversation".
A: The idea of exception handling is doing some logic at a single point in case of any failure.
The try catch will be used at the final point where you need to handle exception or you need to convert an exception to another exception
Say your app has many layers namely Action, Facade, Persist
Delegate exception
In this case any exception that is thrown on Facade can be thrown to the above action layer.
In action the particular exception will be caught and handled with proper error message.
//This is in Facade Layer
public void save(Student student) throws AppException{
//exceptions delegated to action layer
//call to Persist Layer
}
Converting General Exception to App exception
Say in persistence you get and DBException like sqlException. This exception should not be send as such to Action or Facade layer, so we catch the particular exception and then throw a new exception (a user defined exception for application)
//This is in Persist Layer
public void save(Student student) throws AppException{
//converting general exception to AppException and delegating to Facade Layer
try{
em.persist(student);//call to DB. This is in Persist Layer
}catch(Exception e){
throw new AppException("DB exception", e)
}
}
In action Layer
You will catch your exception in action and then handle exception there
//This is in Action layer
public void callSave(Student student){
try{
//call Facade layer
}catch(AppException e){
//Log error and handle
}
}
A: If your combination is ejb with jpa, then all jpa exceptions are runtime exceptions.
ejb handling 2 types of exceptions 1) Application Exception 2) System Exception
Application Exceptions checked exceptions basically we are using business validation and business rules.
System Exceptions are runtime exceptions, so that if any runtime excpetion happend ejb container will interfer and convert the runtime exception as remote exception.
For ex:
in dao layer
public void store(Cargo cargo) {
entityManager.persist(cargo);
}
All jpa exceptions are runtime exceptions only.
in ejb service layer:
public TrackingId bookNewCargo(UnLocode originUnLocode,
UnLocode destinationUnLocode,
Date arrivalDeadline) {
Cargo cargo = new Cargo(trackingId, routeSpecification);
cargoRepository.store(cargo);
return cargo.getTrackingId();
}
in the ejb layer if any runtime exception happend, ejb container will interfere and convert into remote exception.
In the interface layer:
public String register() {
try {
String trackingId = bookingServiceFacade.bookNewCargo(
originUnlocode,
destinationUnlocode,
arrivalDeadline);
} catch (Exception e) {
throw new RuntimeException("Error parsing date", e);
}
so that like this jpa --> ejb --> interface
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How can I tell the debugger to break on auto_refcount_underflow_error I am writing my first OS X (10.6) Application with Xcode 4 and encounter this message:
malloc: reference count underflow for 0x2000b9540, break on auto_refcount_underflow_error to debug
I understand that I have a problem with my memory management, but I would like to narrow the point. So I hope that I can tell the debugger to break at the line of code where this error occurs. But I do not see any option to tell the debugger "break on auto_refcount_underflow_error". But I hope it is possible. Can you please tell me how?
Just in case that it is important for this: The error occurs in a GCD thread.
Best regards & thank you very much
Arno
A: Use the comand line of GDB. In Xcode 4, in the console window next to the (gdb) prompt, type
br auto_refcount_underflow_error
br is the break command and it sets a breakpoint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: reading txt file into perl's hash Hej sharp minds!
I need to load text file into hash. One line is the key, next line is the value. And that repeats several million times. Any suggestions how to do it in the best way?
And how much memory the hash table would need if let's say key is 15 characters and value is 50 characters?
Thanks
A: The following code should load the text file into the hash:
my %hash;
while (chomp(my $key = <DATA>)) {
chomp(my $val = <DATA>);
$hash{$key} = $val;
}
The memory overhead of the hash entries will depend on the architecture (32 vs. 64 bit) but should be on the order of a couple hundred bytes for the hash itself, and then about 30-60 bytes per key and value, plus the overhead of the key and value data types. You can use Devel::Size to check it yourself. Also read this.
So in your example, on a 64-bit platform, a million entries should cost roughly:
136 for the hash
58 + 15 + 58 + 50 == 181 per key/value pair x 1,000,000
181MB for a million entries of the sizes you specified.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When using Java classes from Jython, do you bother to use the getters and setters? Should you? It's well known that Python classes cannot have truly private members. The not-as-obvious implication of this is that Java classes' privates are made public to Jython. (Hide thy nakedness, Java!)
So, when using Jython, and accessing a Java classes' privates that would usually be exposed to other Java classes through getters and setters, do you bother to use those methods? Or do you just access the privates directly?
The more pertinent question would be, should you use the getters and setters? If there are side-effects of the methods, then the answer would undoubtedly be 'yes', but if the methods are just there because someone thought that a putting getters and setters everywhere is The Right Thing to do (IMO it's not, just make the damn thing public), then is there any reason to bother with all of Java's extra ceremony?
A: Although Jython can make non-public Java members accessible from everywhere, this is a feature that must be enabled explicitly. This alone is reason enough for me to honor the visibility of Java classes, otherwise you are risking works on my machine problems.
More principially, you should use the provided property accessors for classes that are not under your control unless you have a very good reason not to: You never know if future versions of the class will do more than just the bare minimum in their getters/setters.
Jython has the nice feature of hiding the accessor methods of JavaBean properties. Jython converts x.foo += 5 into x.setFoo(x.getFoo() + 5. Because usually the backing field of a property has the same name as the property itself, you may have confused this feature with "Jython makes the backing field accessible" even if it does not. I would definitively use this property-accessed-like-fields syntax of Jython: it makes your code more concise and easier to read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Windows phone 7 web browser control user agent The present user agent for the browser control that i see in the emulator is Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; Microsoft; XDeviceEmulator) and i want to change that to Mozilla/5.0 Windows NT 6.1 AppleWebKit/535.1 KHTML, like Gecko Chrome/14.0.835.187 Safari/535.1 or something similar.
How to code that in C# to change the user agent string for the web browser control.
A: Found a way webBrowser.Navigate("http://localhost/run.php", null, "User-Agent: Here Put The User Agent");
A: In Windows Phone 7.5, there is a Navigate method overload that allows setting the headers. There are 3 arguments ( URI, post_info, header_info) , not 4 as shown.
The overload worked for me.
Good luck.
-e
A: In the end I found an unbelievably simple answer, and that worked.
All you need do is to edit the Web Browser Control XAML. Add the property IsScriptEnabled="True"
Hope this solutions helps.
A: Would be something like this, in vb:
WebBrowser.Navigate(New Uri("URL"), byteArr, HttpRequestHeader.UserAgent & ":" & "Mozilla/5.0 (Linux; U; Android 2.3.4; fr-fr; HTC Desire Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
However, I cannot modify the headers already appended to the request, you can only add them, which I find pretty annoying.
Anyone have succeeded in doing this??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to add installed Glassfish 3.1 to Netbeans 7.0 I recently migrated to Netbeans 7.0(with glassfish 3.1) from 6.9(with glassfish 3.0). After that glassfish server ran just for the first time and when I restarted netbeans, since then, it doesnt show glassfish in the servers list.
Now when I am trying to add my already installed server to netbeans, on pointing to installation location of server, it says C:\Program Files\glassfish-3.1(my glassfish installation directory) does not have a usable default domain.
Then on selecting : Register Local Domain it asks for:
Enter the path to a directory that will contain a new domain.
On selecting any directory, it says : Unsupported domain at C:\Program Files\glassfish-3.1; Admin-listener is disabled or no enabled http-listener
How do I rectify this and add Glassfish support to my netbeans 7.0 ?
A: I just had the exact same problem and I managed to solve it this way:-
Just run NetBeans as Administrator & try again repeating your steps, everything will work!
I think that NetBeans doesn't have a right to create folders outside of it's own if you don't run it as an Administrator.
A: This issue also occurred for me in UNIX using GlassFish 4.1.1.
My fix involved gaining write privileges to my GlassFish folder (located for me in /usr/local/glassfish-4.1.1). This can be done by using the chmod command, which requires sudo access if not the owner.
A: I had same issue but this time Netbeans 8 with Glassfish 4.x win7, the way I solved it is below:
No need to run netbeans as administrator.
No need to dowload the Glassfish zip file, you'll dowload through netbeans IDE.
-create a dir where you'll place your glassfish installation files. In my case (win7) is:
C:\glassfish4
-Enter glassfish ide, go to Services / Servers / Add Server
-when Netbeans request your GlassFish location, browse the one we created above.
-select "Remote Domain"
-mark "I have read and accept licence agreement"
-press "Download" and select glasfish 4, ok.
this should start dowloading the Glasfish Server, just complete configurations steps.
A: This happens when Java EE is not activated in the IDE. In the Services window, the Servers node is then empty. The node allows to add a new server, and in the process activates Java EE. Now when trying to register, the IDE discovers that it already has the selected server, refusing to register it twice. Just cancel and use the existing server in the refreshed Servers node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: convert memo field in Access database from double byte to Unicode I am using Access database for one system, and SQL server for another system. The data gets synced between these two systems.
The problem is that one of the fields in a table in Access database is a Memo field which is in double-byte format. When I read this data using DataGridView in a Windows form, the text is displayed as ???.
Also, when data from this field is inserted in sql server database nvarchar(max) field, non-English characters are inserted as ???.
How can I fetch data from memo field, convert its encoding to Unicode, so that it appears correctly in SQL server database as well?
Please help!!!
A: I have no direct experience with datagrid controls, but I already noticed that some database values are not correctly displayed through MS-Access controls. Uniqueidentifiers, for example, are set to '?????' values when displayed on a form. You could try this in the debug window, where "myIdField" control is bound to "myIdField" field from the underlying recordset (unique Identifier type field):
? screen.activeForm.recordset.fields("myIdField")
{F0E3C822-BEE9-474F-8A4D-445A33F363EE}
? screen.activeForm.controls("myIdField")
????
Here is what the Access Help says on this issue:
The Microsoft Jet database engine stores GUIDs as
arrays of type Byte. However, Microsoft Access can't return Byte data
from a control on a form or report. In order to return the value of a
GUID from a control, you must convert it to a string. To convert a
GUID to a string, use the StringFromGUID function. To convert a string
back to a GUID, use the GUIDFromString function.
So if you are extracting values from controls to update a table (either directly or through a recordset), you might face similar issuers ...
One solution will be to update data directly from the recordset original value. Another option would be to open the original recordset with a query containing necessary conversion instructions so that the field will be correctly displayed through the control.
What I usually do in similar situation, where I have to manipulate uniqueIdentifier fields from multiple datasources (MS-Access and SQL Server for Example), is to 'standardize' these fields as text in the recordsets. Recordsets are then built with queries such as:
*
*SQL Server
"SELECT convert(nvarchar(36),myIdField) as myIdField, .... FROM .... "
*MS-Access
"SELECT stringFromGUID(myIdField) as myIdField, .... FROM .... "
A: I solved this issue by converting the encoding as follows:
//Define Windows 1252, Big5 and Unicode encodings
System.Text.Encoding enc1252 = System.Text.Encoding.GetEncoding(1252);
System.Text.Encoding encBig5 = System.Text.Encoding.GetEncoding(950);
System.Text.Encoding encUTF16 = System.Text.Encoding.Unicode;
byte[] arrByte1 = enc1252.GetBytes(note); //string to be converted
byte[] arrByte2 = System.Text.Encoding.Convert(encBig5, encUTF16, arrByte1);
string convertedText = encUTF16.GetString(arrByte2);
return convertedText;
Thank you all for pitching in!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should views set model data? I'm just trying to figure out a probably simple question.
Should views set model data directly or only call model methods that change their own data?
A: like everything else in software development, "it depends".
if you're using form inputs in your views and you just need to get the data from those inputs in to the models, set the data directly. You can do this any number of ways, including "change" events from the input fields, like this:
MyView = Backbone.View.extend({
events: {
"change #name", "setName"
},
setName: function(e){
var val = $(e.currentTarget).val();
this.model.set({name: val});
}
});
On the other hand, if you're kicking off business logic and other code that happens to set the data in the model (but really only does this as part of the business logic), then you should call a method on the model.
A "state machine" would be a good example of when you would do this. Or, in an image gallery that I wrote, I had some logic around the selection of an image for display. If an image is already selected, don't select it again. I put this logic in a method on my image model:
Image = Backbone.Model.extend({
select: function(){
if (!this.get("selected")){
this.set({selected: true});
}
}
});
As illustrated here, I like to run by the simple rule that if I have zero logic around the call to set, then I set it directly from wherever I am. If there is any logic related to the model, around the set, then I put it in the model.
Either way, when you do want to set data, you should use the set method. Bypassing this and setting the model's attributes directly through model.attributes will prevent a lot of Backbone's code from firing and potentially cause problems for you.
A: That depends on your programming style. I always set them directly. If the Law of Demeter sounds good to you and you're into object orientation (and possibly with a Java/Microsoft -stack background), then the style would be to create getter/setter methods.
If you on the other hand is in the "Size is the Enemy" camp (I also recommend Jeff Atwood's comments) the you certainly should set model data directly (as I hinted before, I'm in this camp myself).
That being said, Backbone.js models already have getter and setter methods .get and .set. You should not manipulate the .attributes member directly. I'm not as sure you shouldn't read from it, I tend to do that now and then and haven't run problems because of that yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to add more than one List in Android? How to assign more than one List in Android?
List<String> inc = dh.selectInct1();
ArrayAdapter<String> inc1 = new ArrayAdapter<String>(this,R.layout.list,R.id.textViewx,inc);
lvinc.setAdapter(inc1);
lvinc.setOnItemClickListener(this);
Here dh.selectInct1(); returns a list that is assigned into inc. Now I need to add one more list from database to this already existing inc. How to achieve it?
A: Simply join those two Lists using addAll(Collection c)
List<String> inc = dh.selectInct1();
List<String> inc2 = dh.selectInct2(); //select your data to second list
inc.addAll(inc2); // join them together
ArrayAdapter<String> inc1 = new ArrayAdapter<String>(this,R.layout.list,R.id.textViewx,inc);
lvinc.setAdapter(inc1);
lvinc.setOnItemClickListener(this);
*
*How do I join two lists in Java?
*List.addAll() documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to connect sql server using JTDS driver in Android i am new in android..
i want to connect sql server using JTDS driver.
can any one tell me..
thnx in advance...
A: Getting error "ClassNotFoundException" while using JTDS on ANDROID to direct access SQLSERVER?
After 3 hours RND, for finding solution for the same above error. I didnt get there is no error in the code, also I have import "jtds-1.3.0" library properly continues debugging of code still getting same error again and again.
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(
db_connect_string, db_userid, db_password);
}
I tried alternative to, changing line
...... Class.forName("net.sourceforge.jtds.jdbc.Driver");
to
...... (new Driver()).getClass();
...... (new Driver())
when I tried all of these, I tought there might be a problem in jtds-1.3.0 library, and what I did, just download the old version jtds-1.2.5 and import it; and the issue resolved.
So, friends out there If you getting same error and tried different ways already, try this.
A: It's weird that there is no example code on the jTDS website. I found this, it might be helpfull:
http://www.java-tips.org/other-api-tips/jdbc/how-to-connect-microsoft-sql-server-using-jdbc-3.html
import java.sql.*;
public class testConnection
{
public static void main(String[] args)
{
DB db = new DB();
db.dbConnect("jdbc:jtds:sqlserver://localhost:1433/tempdb","sa","");
}
}
class DB
{
public DB() {}
public voidn dbConnect(String db_connect_string, String db_userid, String db_password)
{
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(
db_connect_string, db_userid, db_password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
EDIT:
You will get ClassNotFoundException exception when your main class cannot be found. Find the following lines in your AndroidManifest.xml make sure they are correct:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ezee.app"
/*...*/
<activity android:name=".connect12"
Also make sure that the class exists at your_project_folder/src/com/ezee/app/connect12 (case sensitive I think)
A: in my experience, if you're using Android with a stand-alone installation of SQL Server, you must use 10.0.2.2 address instead of "localhost" or "127.0.0.1", according to Android specifics for accessing localhost servers.
I tried so, and have successfully connected to my SQL Server.
A: Exception in thread "main" java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.test.objectref.GroupBy.main(GroupBy.java:12)
To solve this issue had to add Jtds lib.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Store password in encrypted file with read & write access Is there a way to store a password in a secured file in unix system?
That file can be readable and writtable by Unix shell script.
I dont want to use any external libraries.
Help to give some idea or code snippet for native Unix encryptions.
Thanks!
A: By asking this question you basically tell everyone that the design of your system is flawed.
If you save a password, there are two use cases:
*
*Being able to check an entered password against the saved one
*Using the saved password for something (i.e. the application needs to retrieve it in plaintext)
For case 1 simply save a salted hash. That's secure and even if someone gets access to the hash he can't do much with it. Protecting it using standard UNIX filesystem permissions is way enough - chmod 600 and no other users (besides root) can access the file.
For case 2 encrypting it doesn't make much sense. Your application needs to be able to decrypt it anyway so it gives users looking at the file a false sense of security (if your application can decrypt it, everyone can). Using the filesystem permissions is usually secure enough.
Now you could say that even root shouldn't be able to access the password - a valid argument on a multi-user system. However, root could modify/replace your program anyway - so it would be a false sense of security again. Anyway, in that case you could encrypt it with a second password the user needs to enter everytime the password is to be read or written. Then you'd have something similar to the password manager browsers have where the stored passwords are protected with a master password.
A: You want to use the cryptographic API then. Take a look at this one: http://www.linuxjournal.com/article/6451?page=0,0
And if you want to do it by shell script, you can use 'md5sum' to encrypt strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Google Map in iPhone application I am beginner to iPhone application.
I want to know the way of using Goole Map.
Please help me.
A: Google maps are built-in in standard API provided by Apple. Have a look at MapKit framework that provides access to maps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: White screen to load cocos2d scene I am new in cocos 2d game development and developing a game where I need to reload scenes from view controller many times.For this i remove the scene and run it again.After 2 or more times the scene loads but white screen occurs and in console the error "OpenGL error 0x0506 in -[EAGLView swapBuffers]" is shows.
here is my code to add the scene-
if ([[CCDirector sharedDirector] runningScene] == NULL)
{
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:GL_DEPTH_COMPONENT24_OES
preserveBackbuffer:NO
sharegroup:nil
multiSampling:YES
numberOfSamples:4];
[director setOpenGLView:glView];
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
[director setAnimationInterval:1.0/60];
[window addSubview:glView];
[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer node]];
}
and code for remove the scene-
[[CCDirector sharedDirector].openGLView removeFromSuperview];
[[CCDirector sharedDirector] stopAnimation];
[[CCDirector sharedDirector] end];
[[CCDirector sharedDirector] release];
Please help me I am not getting where is the problem.
Thanks.
A: Two things of note:
*
*don't release CCDirector! All you need to do is call stopAnimation and later startAnimation
*don't remove the openGLView from its super view. Instead, just hide it: [CCDirector sharedDirector].openGLView hidden:YES]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SSIS package is not terminating I have a SSIS package which will execute a set of sql commands and some sps. there is one main sp in the package which will execute some sps in loop. But when i scheduled it as job in sql server, sps will be executed but it never comes out from the execution. It will stuck in that satage.
A: I would do some serious debugging here. It sounds like one of your stored procs either
1) has an endless loop somewhere
or
2) there is a significant amount of blocking happening
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are complexities of BigInteger.pow and BigInteger.isProbablePrime? What are complexities of Java 7's methods pow and isProbablePrime in the BigInteger class?
I know that simple implementation of Rabin's test is of O(k(log(n))^3) complexity and that can be reduced by incorporating the Schönhage-Strassen algorithm for the fast multiplication of long integers.
A: Assuming the standard algorithms, the complexities are:
pow() : O( M(n * exponent) )
IsProbablePrime() : O( M(n) * n )
where:
*
*n is the number of digits in the operand.
*exponent is the exponent of the power function.
*M(n) is the run-time for an n x n digit multiplication. Which I believe is O(n^2) as of Java 6.
Explanation for pow():
For an input operand of n-digits long raised to a power of exp, the output is roughly n * exp digits long. This is done by binary-powering algorithm where the operand is squared at each iteration. So the complexity becomes:
O( M(n) + M(2*n) + M(4*n) + ... M(n * exp/2) ) = O( M(n * exp) )
This is a geometric sum, so the sum becomes O( M(n * exp) ).
Explanation for IsProbablePrime():
For a fixed number of Rabin-Miller iterations, each iteration has O(n) multiplications of size n x n digits. Therefore, the complexity becomes O( n * M(n) ).
A: The short answer is that it isn't specified and therefore subject to implementor's choice.
A: If you want to have a look at the source, here it is: http://futureboy.us/temp/BigInteger.java.
Relevant material to your question here too: What complexity are operations on Java 7's BigInteger?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to set action in multiple buttons in navigation bar this is my code
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *segmentTextContent = [NSArray arrayWithObjects:
NSLocalizedString(@"button1", @""),
NSLocalizedString(@"button2", @""),
NSLocalizedString(@"button3", @""), nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] nitWithItems:segmentTextContent];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 400, 30);
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
}
three buttons are displayed but i don't know how to set action in button help me thanks in advance
A: add target at the time of segmentedControl creation like below
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
in that selector
-(IBAction) segmentAction:(id)sender{
UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
NSLog(@"Segment clicked: %d", segmentedControl.selectedSegmentIndex);
switch (segmentedControl.selectedSegmentIndex) {
case 0:
self.segmentLabel.text =@"Segment 1 selected.";
break;
case 1:
self.segmentLabel.text =@"Segment 2 selected.";
break;
default:
break;
}
A: You have to make 3 buttons and add them to an UIToolbar.
- (void)viewDidLoad
{
[super viewDidLoad];
// create a toolbar to have the buttons at the right side of the navigationBar
UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 150, 44.01)];
toolbar.tintColor = [UIColor clearColor];
[toolbar setTranslucent:YES];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// Create button1
UIBarButtonItem *button1 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(button1Pressed)];
[buttons addObject:button1];
[button1 release];
// Create button2
UIBarButtonItem *button2 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(button2Pressed)];
[buttons addObject:button2];
[button2 release];
// Create button3
UIBarButtonItem *button3 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(button3Pressed)];
[buttons addObject:button3];
[button3 release];
// stick the buttons in the toolbar
[toolbar setItems:buttons animated:NO];
//self.toolbarItems = buttons;
[buttons release];
// and put the toolbar in the nav bar
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithCustomView:toolbar] autorelease]];
[toolbar release];
}
...
- (void)button1Pressed
{
//do stuff
}
- (void)button2Pressed
{
//do stuff
}
- (void)button3Pressed
{
//do stuff
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot find symbol method d(java.lang.String,java.lang.String) When I compile the code below error occurs:
canot find symbol
location: interface org.apache.commons.logging.Log Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());`
This is my code:
//convertJSONtoArray
private void convertJSONtoArray(String rawJSON){
try {
JSONObject completeJSONObj = new JSONObject(rawJSON);
String json = completeJSONObj.toString();
Log.d(TAG,json);
JSONObject results = completeJSONObj.getJSONObject("results");
} catch (JSONException e) {
Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());
}
}
A: There are two possible reasons:
1. You are using Android
In that case replace the import for Apache Commons Logging Log with:
import android.util.Log;
2. You are developing in normal Java environment
Your import statement at the top of your class includes Apache Commons Logging Log, but the code was definitely not written for Commons Logging.
For Commons Loggig is should look like this:
private static final Log LOG = LogFactory.getLog(NAME_OF_YOUR_CLASS.class);
private void convertJSONtoArray(String rawJSON){
try {
JSONObject completeJSONObj = new JSONObject(rawJSON);
String json = completeJSONObj.toString();
if (LOG.isDebugEnabled()) {
LOG.debug(TAG,json);
}
JSONObject results = completeJSONObj.getJSONObject("results");
} catch (JSONException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(TAG,"JSON parsing error - fix it:" + e.getMessage());
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I resolve "Item has already been added. Key in dictionary:" errors? I have an application which got hung up when I tried to add items to it. When I checked the trace file I got this entry:
for (int i=0; i<objects.Count; i++)
{
DataModelObject dmo = (DataModelObject)objects.GetAt(i);
sl.Add(dmo.Guid, dmo);
}
}
I don't know how to solve this issue.
A: The exception indicates that you adding same key twice to your dictionary, to solve this issue you can start by insuring that the DataModelCollection objects which passed to the function has unique Key values (which in your case is a Guid data type) dmo.Guid
A: The problem is that in a sorted list each key needs to be unique. So you need to check that you aren't inserting the same key (guid value) twice. Code shown below:
for (int i=0; i<objects.Count; i++)
{
DataModelObject dmo = (DataModelObject)objects.GetAt(i);
if (!sl.ContainsKey(dmo.Guid))
{
sl.Add(dmo.Guid, dmo);
}
}
This will ensure that each key is unique. If however you are expecting more than one value for each key then you need to use a different type of collection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Check with textbox I have this question. I have a input type text and a button. Like this html:
<form id="browser-form">
<div class="filebrowser">
<input type="text" id="browser-filepath">
</div>
<div class="upload submit">
<a href="#" id="browser-submit" class="button">Uploaden</a>
</div>
</form>
But the question is. When the input type is empty. Je can not click on the button. When the input type is fil. Than you can click on the button. How can i fix that?
Thanks!
A: Assuming I've understood your question correctly, I think you want to prevent the link from doing anything unless the input has a value. If that's correct, then you can do this:
$("#browser-submit").click(function(e) {
if(!$("#browser-filepath").val()) {
e.preventDefault();
}
});
preventDefault is a method of the event object which, as the name suggests, prevents the default action of an event (in this case, following the link).
Here's a working example of the above.
A: function UpdateSubmitButton() {
var oTextBox = document.getElementById("browser-filepath");
var oButton = document.getElementById("browser-submit");
if(oTextBox.value == "") {
oButton.disabled = true;
}
else {
oButton.disabled = false;
}
}
Add an onchange="UpdateSubmitButton()" section to your text box, and you might want to add onload="UpdateSubmitButton()" to your document body.
This should do the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: This code should give output as the given format This is code in java for string.
int a=6;
int b=7;
System.out.println(a+"\"+b);
I want to comes the output is 6\7.
A: write this code:
System.out.println(a+"\\"+b);
A: In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash.
In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I think I'm doing it wrong (PHP Class creation & signs and more) Currently I have a class called user that I want to create with different variables, but I think I'm doing it wrong.
Currently I have a class "Unit" with these two functions
public function __construct($table, $id) {
require_once('database.php');
require_once('app.php');
require_once("postmark.php");
$this->table = $table;
$this->valid = true;
if(!$id) {
$this->valid = false;
}
$this->populate($id);
}
public function populate($id) {
$db = new DB();
$q = $db->where('id', $id)->get($this->table);
$resp = $q->fetchAll();
foreach ($resp as $row) {
foreach ($row as $key=>$value) {
if(!is_int($key))
$this->$key = html_entity_decode($value, ENT_QUOTES);
if(is_null($value)) {
$this->$key = null;
}
}
}
if(count($resp) <= 0) $this->valid = false;
$verdict = !$db->error;
$db = null;
unset($db);
return $verdict;
}
And then my "User" class extends it like so
public function __construct($id, $hash = null, $verify = null, $api = null) {
if($api)
$value = $this->apiToId($api);
else if($verify)
$value = $this->verifyToId($verify);
else if($hash)
$value = $this->hashToId($hash);
else
$value = $id;
parent::__construct("users", $value);
}
But I can't help but think this is poor in design. A few things I have seen in the past are the use of ampersands, possibly making it so I could do
$user = new User()->fromId($id);
Or
$user = new User()->withHash($hash);
Instead of passing it a long list of null params. That or I could improve the way inheritance works. While I like to think I know what I'm doing with PHP, I'd really like some help looking in the right direction. PHP's docs are so cumbersome, that I never no where to look, but always find cool useful tools. I'm wondering how I can improve this for more flexibility and structure.
A: *
*Move includes to the very top of your php file. Anything that needs to be conditionally included is probably poorly designed.
*Your unit class should be declared as abstract. This prevents anyone from instantiating a unit. You can only declare subclasses of it.
*Any functions relating to your class should be declared as methods. Thus, the example given in an answer now-removed is a terrible choice. The function alloc really should be a static function defined in User. Code snippet at bottom.
*Your init functions should be declared as static and return a new instance of the class. Defining an instance of the class to re-instantiate the class is just a bad idea.
*Your database connection should use a Singleton pattern. Look it up if you need to.
Post your full code and comment on this answer if you'd like some help implementing all of this.
$user = User::initWithHash($hash);
//your create method:
/**
* Creates and returns a new instance of the class. Useful
* @return an instance of User.
*/
public static function create() {
return new User();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquerymobile: mutli selection dropdown My jquerymobile form has a optgrouped multi section dropdown. Upon form loading I have to set some default options. I have tried like
$('#myselect')[0].selectedIndex = 2;
$('#myselect')[0].selectedIndex = 3;
$('#myselect')[0].selectedIndex = 5;
$('#myselect').selectmenu("refresh");
But only 5th option is getting selected, how to set selected option true for multiple options using js.
+++ EDIT ++++
<!DOCTYPE html>
<link rel="stylesheet" href="jquery.mobile-1.0b3/jquery.mobile-1.0b3.min.css" />
<script src="jquery.mobile-1.0b3/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$("#account").live("pagecreate", function(event){
if( navigator.userAgent.match(/android/i) ) {
loadOrgDropdown();
}
});
</script>
<script src="jquery.mobile-1.0b3/jquery.mobile-1.0b3.min.js"></script>
<script src="js/common.js"></script>
<script type="text/javascript">
function loadDropdown() {
jQuery.ajax(
{
url : 'PocketmediServices.php?service=getDropdownValues',
type : 'get',
dataType : 'json',
beforeSend : function(){
},
error : function(){
if (typeof Android != 'undefined') {
Android.dismissLoadinDialog();
}
},
success : function(data){
if(data.response.getDropdownValues.dropdownList !== undefined) {
var count = -1;
var selected = -1;
$.each(data.response.getDropdownValues.dropdownList, function(key, val) {
count++;
$('#myselect')
.append($('<option>', { value : val.item.Code })
.text(val.item.Name));
if($.inArray(val.item.optionval, previousSelected) >=0) {
$('#myselect')[0].selectedIndex = [3,5]; // hard coded for now.
}
});
$('#myselect').selectmenu("refresh");
}
},
complete : function(req){
},
});
} //loadDropdown
</script>
<div data-role="fieldcontain">
<label for="organization">Organization:</label>
<select name="organization" id="organization" data-native-menu="false" multiple >
<optgroup label="s" id="org_s"></optgroup>
<optgroup label="Support Networks" id="org_support_networks"></optgroup>
</select>
</div>
Thanks,
nehatha
A: Multiple select boxes deals with array for multiple values e.g.
$('#myselect').val([2,3,5]);
You can find examples @ http://api.jquery.com/val/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does correlation coefficient actually represent What does correlation coefficient intuitively mean? If I have a series of X and then a series of Y, and if I input these two into Weka multilayer perceptron treating Y as the output and X as input, I get a correlation coefficient as 0.76. What does this intuitively represent, and how I explain this to a business man or a non-techie person?
A: There are several correlation coefficients. The most commonly used, and the one that is referred to as "the one" is Pearson's product moment correlation.
A correlation coefficient shows the degree of linear dependence of x and y. In other words, the coefficient shows how close two variables lie along a line.
If the coefficient is equal to 1 or -1, all the points lie along a line. If the correlation coefficient is equal to zero, there is no linear relation between x and y. however, this does not necessarily mean that there is no relation at all between the two variables. There could e.g. be a non-linear relation.
A positive relationship means that the two variables move into the same direction. A higher value of x corresponds to higher values of y, and vice versa.
A negative relationship means that the two variables move into the opposite directions. A lower value of x corresponds to higher values of y, and vice versa.
Here you have a handful of examples:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I make a column editable only to a few users in SharePoint? I want to create a couple of columns in a doc library, which should be editable only for a few users. These users can be part of a single group. However currently, this is editable by all users and does not serve my purpose.
My SP site is created using WSS 3.0 and workflows are built using SP designer.
A: There is an interesting codeplex project (SPListDisplaySetting) which will fit your needs, I think?!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Split string into 2 strings based on a delimiter Does anybody know if there is a solid library based method to achieve the following.
Say I have the string
"name1, name2, name3, name4"
and I want to parse it into 2 strings based on the comma delimiter.
I would like the strings to look like this:
string1 = "name1";
string2 = "name2, name3, name4";
Any ideas?
A: Pattern pattern = Pattern.compile(", *");
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
string1 = inputString.substring(0, matcher.start());
string2 = inputString.substring(matcher.end());
}
A: you could use yourString.split(", ", 2).
String str = "name1, name2, name3, name4";
String[] parts = str.split(", ", 2);
String string1 = parts[0];
String string2 = parts[1];
System.out.println(string1); // prints name1
System.out.println(string2); // prints name2, name3, name4
You could also use yourString.indexOf(", ") and yourString.substring(...).
A: String s = "hello=goodmorning,2,1"
String[] str = s.split("="); //now str[0] is "hello" and str[1] is "goodmorning,2,1"
String str1 = str[0]; //hello
String[] str2 = str[1].split(","); //now str2[0] is "goodmorning" and str2[1] is "2,1"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Usecase Diagram I'm new to UML.I have a question.consider we have a user that can change user specification(change user password,Grant Access,...) for Use Case diagram which of these two picture is correct:
1)
2)
if No.1 is correct in what diagram we sould show details?thanks
A: I tend to say diagram #1 is correct, but this depends on your concrete requirements. Given the sample use cases I'd rather expect something like this:
*
*Actor Admin -> Modify User Authorization (matches grant/deny access)
*Actor Admin -> Change User Password
*Actor Admin -> Modify User Details (user specification)
*Actor End User -> Change User Password (variant of #2)
*Actor End User -> Modify User Details (variant of #3)
For detailing use cases in UML diagrams you have two options, an activity diagram and/or a sequence diagram. Neverthess, I'd be careful going that route, during your project you will have to put a lot of effort into maintaining those diagrams. My experience is that as soon as the first lines of code have been written no one will look at the beautyful diagrams any more. Rule of thumb - formal specification is a function of team complexity. If you have a global team with developers in different timezones it may make sense to put more effort into this kind of specification.
This has worked for me:
*
*Create a Use Case overview (either graphical like yours or simply a text document)
*Document use cases in form of user stories
*Use activity diagrams for complex processes, maybe spanning more than one use case, e.g. an order process
*Create a few sequence diagram to document the important technical aspects of your system like authorization, transaction management, end-to-end communication between all the different layers
Edit: The UML offers several types of diagrams to document and model different views on your system. The Use Case Diagram itself is not designed to document detailed, low-level aspects of your system. As per WikiPedia:
Use case diagram: describes the functionality provided by a system in terms of actors,
their goals represented as use cases, and any dependencies among those
use cases.
A: The diagram is just to give you an overview. The heavy-weight of the use case is the text description that goes along with it. There you describe the use case, the involved actors, pre- and postconditions and the actual steps of the use case in a sequence. Take a look at this textual specification and note the section headers. It is a pretty good example of how use cases should be described. Basically you want your descriptions split as in #2, but for an overview "big" picture it may be beneficial to also group them. So that you have e.g. use case "#1 Change User Specification" and then you have "#1a Change User Password", "#1b Grant Access", etc. .
Be cautious with use cases and user stories!
*
*Use cases are presented in a diagram as you have shown and are described in a rather strict format. They're meant to be a specification of a certain user action and allow you to document and prescribe the feature to a quite detailed level (from a user perspective, but also going into a system perspective sometimes).
*User stories on the other hand come from the agile world and are a much more simplified description of a "feature". It is important to clarify that user stories are not meant as specification! They don't include pre- and post conditions or a detailed basic and alternative flow description! They are meant to be so small to be described with a single sentence.
With user stories the programmer is free/required to solve issues on his own like what to do if there's an error and such. With use cases it's all documented, the error message itself and what should happen.
A: First case is better, use case should not be used for some functional decompostion, they are just use cases :). If the actions as "change password" can be viewed either as separate use cases or let's say more or less independent parts of other use cases, then you can <<include>> them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting input language Will be accepting input mainly in two languages (English & Arabic).
What would be the simplest way to detect which language was used?
A: This pear package may help, but I didn't use it:
http://pear.php.net/package/Text_LanguageDetect
A: Look at this post Checking browser's language by PHP? this is the only way I know of. to check the language of the browser, assuming this is the user's main language
A: There's no way to test 100% reliably, but you can try checking the Accept-Language header that the browser should send with its requests to determine which language to use. This will contain a list of languages the client is willing to accept, it also includes a quality score that the server can use to determine the preferred language.
Do provide the option for the user to manually set the language as well though, as I said it might not be 100% reliable.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html gives more technical details on the accept-language header.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Libreoffice Impress Export as Images extension does not work Libreoffice Impress Export as Images extension does not work. "Export as Images" Menu is not being added to File Menu.
Link- http://extensions-test.libreoffice.org/extension-center/export-as-images
I am using Libreoffice 3.4. Any suggestions would be helpful.
A: Quick workaround: start the Export as Images macro manually. It's located under My Macros -> ExportImages -> ExportImages. Look for a macro named ExportAsImages and run it. Once found and started, it works fine :) (i don't know why it doesn't show up in the File menu).
EDIT:
Editing the macro is possible using the built-in IDE: once it's installed, you can access its LibreOffice Basic source using Tools-> Macros -> Organize Macros... -> LibreOffice Basic.
It's also possible to run it from the command line, but in its current form, it requires user interaction to specify the output file name and graphics format. So i assume it isn't possible to run it completely in "headless" mode without modifying the source. To run it from the command line on Linux, converting the file /tmp/mypresentation.odp, use:
$ simpress /tmp/mypresentation.odp "vnd.sun.star.script:ExportImages.ExportImages.ExportAsImages?language=Basic&location=application"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How integrate Paypal in android Application? I try to integrate paypal with Android app using sandbox. I'm getting successfully longing with paypal but when I am doing payment then Screen will get invisible directly without Response.
How can I get the response for the above question?
This is my code.
private void invokeSimplePayment()
{
try
{
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal(Amt));
payment.setCurrencyType(Currency_code[code]);
payment.setRecipient("Rec_Email");
payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
startActivityForResult(checkoutIntent, request);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onActivityResults(int requestCode, int resultCode, Intent data)
{
switch(resultCode)
{
case Activity.RESULT_OK:
resultTitle = "SUCCESS";
resultInfo = "You have successfully completed this " ;
//resultExtra = "Transaction ID: " + data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
break;
case Activity.RESULT_CANCELED:
resultTitle = "CANCELED";
resultInfo = "The transaction has been cancelled.";
resultExtra = "";
break;
case PayPalActivity.RESULT_FAILURE:
resultTitle = "FAILURE";
resultInfo = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
resultExtra = "Error ID: " + data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
}
System.out.println("Result=============="+resultTitle);
System.out.println("ResultInfo=============="+resultInfo);
}
A: This is my code and it works fine. There are two classes.
For PayPal from sandbox to live environment you have to do 2 things: put the actual account holder in set recipient and get a live ID by submitting your app to PayPal
public class ResultDelegate implements PayPalResultDelegate, Serializable {
private static final long serialVersionUID = 10001L;
public void onPaymentSucceeded(String payKey, String paymentStatus) {
main.resultTitle = "SUCCESS";
main.resultInfo = "You have successfully completed your transaction.";
main.resultExtra = "Key: " + payKey;
}
public void onPaymentFailed(String paymentStatus, String correlationID,
String payKey, String errorID, String errorMessage) {
main.resultTitle = "FAILURE";
main.resultInfo = errorMessage;
main.resultExtra = "Error ID: " + errorID + "\nCorrelation ID: "
+ correlationID + "\nPay Key: " + payKey;
}
public void onPaymentCanceled(String paymentStatus) {
main.resultTitle = "CANCELED";
main.resultInfo = "The transaction has been cancelled.";
main.resultExtra = "";
}
The main class :
public class main extends Activity implements OnClickListener {
// The PayPal server to be used - can also be ENV_NONE and ENV_LIVE
private static final int server = PayPal.ENV_LIVE;
// The ID of your application that you received from PayPal
private static final String appID = "APP-0N8000046V443613X";
// This is passed in for the startActivityForResult() android function, the value used is up to you
private static final int request = 1;
public static final String build = "10.12.09.8053";
protected static final int INITIALIZE_SUCCESS = 0;
protected static final int INITIALIZE_FAILURE = 1;
TextView labelSimplePayment;
LinearLayout layoutSimplePayment;
CheckoutButton launchSimplePayment;
Button exitApp;
TextView title;
TextView info;
TextView extra;
TextView labelKey;
TextView appVersion;
EditText enterPreapprovalKey;
public static String resultTitle;
public static String resultInfo;
public static String resultExtra;
private String isuename;
private String isueprice;
Handler hRefresh = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case INITIALIZE_SUCCESS:
setupButtons();
break;
case INITIALIZE_FAILURE:
showFailure();
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Thread libraryInitializationThread = new Thread() {
@Override
public void run() {
initLibrary();
// The library is initialized so let's create our CheckoutButton and update the UI.
if (PayPal.getInstance().isLibraryInitialized()) {
hRefresh.sendEmptyMessage(INITIALIZE_SUCCESS);
}
else {
hRefresh.sendEmptyMessage(INITIALIZE_FAILURE);
}
}
};
libraryInitializationThread.start();
isuename=getIntent().getStringExtra("name").trim();
isueprice=getIntent().getStringExtra("price").replace("$", "").trim();
Log.v("isuename ",""+isuename);
Log.v("isueprice ",""+isueprice);
LinearLayout content = new LinearLayout(this);
content.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.FILL_PARENT));
content.setGravity(Gravity.CENTER_HORIZONTAL);
content.setOrientation(LinearLayout.VERTICAL);
content.setPadding(10, 10, 10, 10);
content.setBackgroundColor(Color.WHITE);
layoutSimplePayment = new LinearLayout(this);
layoutSimplePayment.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
layoutSimplePayment.setGravity(Gravity.CENTER_HORIZONTAL);
layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
layoutSimplePayment.setPadding(0, 5, 0, 5);
labelSimplePayment = new TextView(this);
labelSimplePayment.setGravity(Gravity.CENTER_HORIZONTAL);
labelSimplePayment.setText("C&EN");
labelSimplePayment.setTextColor(Color.RED);
labelSimplePayment.setTextSize(45.0f);
layoutSimplePayment.addView(labelSimplePayment);
// labelSimplePayment.setVisibility(View.GONE);
content.addView(layoutSimplePayment);
LinearLayout layoutKey = new LinearLayout(this);
layoutKey.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
layoutKey.setGravity(Gravity.CENTER_HORIZONTAL);
layoutKey.setOrientation(LinearLayout.VERTICAL);
layoutKey.setPadding(0, 1, 0, 5);
enterPreapprovalKey = new EditText(this);
enterPreapprovalKey.setLayoutParams(new LayoutParams(200, 45));
enterPreapprovalKey.setGravity(Gravity.CENTER);
enterPreapprovalKey.setSingleLine(true);
enterPreapprovalKey.setHint("Enter PA Key");
layoutKey.addView(enterPreapprovalKey);
enterPreapprovalKey.setVisibility(View.GONE);
labelKey = new TextView(this);
labelKey.setGravity(Gravity.CENTER_HORIZONTAL);
labelKey.setPadding(0, -5, 0, 0);
labelKey.setText("(Required for Preapproval)");
layoutKey.addView(labelKey);
labelKey.setVisibility(View.GONE);
content.addView(layoutKey);
title = new TextView(this);
title.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
title.setPadding(0, 5, 0, 5);
title.setGravity(Gravity.CENTER_HORIZONTAL);
title.setTextSize(30.0f);
title.setVisibility(View.GONE);
content.addView(title);
info = new TextView(this);
info.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
info.setPadding(0, 5, 0, 5);
info.setGravity(Gravity.CENTER_HORIZONTAL);
info.setTextSize(20.0f);
info.setVisibility(View.VISIBLE);
info.setText("Please Wait! Initializing Paypal...");
info.setTextColor(Color.BLACK);
content.addView(info);
extra = new TextView(this);
extra.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
extra.setPadding(0, 5, 0, 5);
extra.setGravity(Gravity.CENTER_HORIZONTAL);
extra.setTextSize(12.0f);
extra.setVisibility(View.GONE);
content.addView(extra);
LinearLayout layoutExit = new LinearLayout(this);
layoutExit.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
layoutExit.setGravity(Gravity.CENTER_HORIZONTAL);
layoutExit.setOrientation(LinearLayout.VERTICAL);
layoutExit.setPadding(0, 15, 0, 5);
exitApp = new Button(this);
exitApp.setLayoutParams(new LayoutParams(200, android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); //Semi mimic PP button sizes
exitApp.setOnClickListener(this);
exitApp.setText("Exit");
layoutExit.addView(exitApp);
content.addView(layoutExit);
appVersion = new TextView(this);
appVersion.setGravity(Gravity.CENTER_HORIZONTAL);
appVersion.setPadding(0, -5, 0, 0);
appVersion.setText("\n\nSimple Demo Build " + build + "\nMPL Library Build " + PayPal.getBuild());
content.addView(appVersion);
appVersion.setVisibility(View.GONE);
setContentView(content);
}
public void setupButtons() {
PayPal pp = PayPal.getInstance();
// Get the CheckoutButton. There are five different sizes. The text on the button can either be of type TEXT_PAY or TEXT_DONATE.
launchSimplePayment = pp.getCheckoutButton(this, PayPal.BUTTON_194x37, CheckoutButton.TEXT_PAY);
// You'll need to have an OnClickListener for the CheckoutButton. For this application, MPL_Example implements OnClickListener and we
// have the onClick() method below.
launchSimplePayment.setOnClickListener(this);
// The CheckoutButton is an android LinearLayout so we can add it to our display like any other View.
layoutSimplePayment.addView(launchSimplePayment);
// Get the CheckoutButton. There are five different sizes. The text on the button can either be of type TEXT_PAY or TEXT_DONATE.
// Show our labels and the preapproval EditText.
labelSimplePayment.setVisibility(View.VISIBLE);
info.setText("");
info.setVisibility(View.GONE);
}
public void showFailure() {
title.setText("FAILURE");
info.setText("Could not initialize the PayPal library.");
title.setVisibility(View.VISIBLE);
info.setVisibility(View.VISIBLE);
}
private void initLibrary() {
PayPal pp = PayPal.getInstance();
if(pp == null) {
pp = PayPal.initWithAppID(this, appID, server);
pp.setLanguage("en_US"); // Sets the language for the library.
pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
// Set to true if the transaction will require shipping.
pp.setShippingEnabled(true);
// Dynamic Amount Calculation allows you to set tax and shipping amounts based on the user's shipping address. Shipping must be
// enabled for Dynamic Amount Calculation. This also requires you to create a class that implements PaymentAdjuster and Serializable.
pp.setDynamicAmountCalculationEnabled(false);
// --
}
}
private PayPalPayment exampleSimplePayment() {
// Create a basic PayPalPayment.
PayPalPayment payment = new PayPalPayment();
// Sets the currency type for this payment.
payment.setCurrencyType("USD");
// Sets the recipient for the payment. This can also be a phone number.
payment.setRecipient("[email protected]");
// Sets the amount of the payment, not including tax and shipping amounts.
payment.setSubtotal(new BigDecimal(isueprice));
// Sets the payment type. This can be PAYMENT_TYPE_GOODS, PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
// PayPalInvoiceData can contain tax and shipping amounts. It also contains an ArrayList of PayPalInvoiceItem which can
// be filled out. These are not required for any transaction.
PayPalInvoiceData invoice = new PayPalInvoiceData();
// Sets the tax amount.
invoice.setTax(new BigDecimal("0"));
// Sets the shipping amount.
invoice.setShipping(new BigDecimal("0"));
// PayPalInvoiceItem has several parameters available to it. None of these parameters is required.
PayPalInvoiceItem item1 = new PayPalInvoiceItem();
// Sets the name of the item.
item1.setName(isuename);
// Sets the ID. This is any ID that you would like to have associated with the item.
item1.setID("87239");
// Sets the total price which should be (quantity * unit price). The total prices of all PayPalInvoiceItem should add up
// to less than or equal the subtotal of the payment.
/* item1.setTotalPrice(new BigDecimal("2.99"));
// Sets the unit price.
item1.setUnitPrice(new BigDecimal("2.00"));
// Sets the quantity.
item1.setQuantity(3);*/
// Add the PayPalInvoiceItem to the PayPalInvoiceData. Alternatively, you can create an ArrayList<PayPalInvoiceItem>
// and pass it to the PayPalInvoiceData function setInvoiceItems().
invoice.getInvoiceItems().add(item1);
// Create and add another PayPalInvoiceItem to add to the PayPalInvoiceData.
/*PayPalInvoiceItem item2 = new PayPalInvoiceItem();
item2.setName("Well Wishes");
item2.setID("56691");
item2.setTotalPrice(new BigDecimal("2.25"));
item2.setUnitPrice(new BigDecimal("0.25"));
item2.setQuantity(9);
invoice.getInvoiceItems().add(item2);*/
// Sets the PayPalPayment invoice data.
payment.setInvoiceData(invoice);
// Sets the merchant name. This is the name of your Application or Company.
payment.setMerchantName("C&EN");
// Sets the description of the payment.
payment.setDescription("simple payment");
// Sets the Custom ID. This is any ID that you would like to have associated with the payment.
payment.setCustomID("8873482296");
// Sets the Instant Payment Notification url. This url will be hit by the PayPal server upon completion of the payment.
//payment.setIpnUrl("http://www.exampleapp.com/ipn");
// Sets the memo. This memo will be part of the notification sent by PayPal to the necessary parties.
payment.setMemo("Hi! I'm making a memo for a payment.");
return payment;
}
@Override
public void onClick(View v) {
if(v == launchSimplePayment) {
// Use our helper function to create the simple payment.
PayPalPayment payment = exampleSimplePayment();
// Use checkout to create our Intent.
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this, new ResultDelegate());
// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
startActivityForResult(checkoutIntent, request);
} else if(v == exitApp) {
Intent in = new Intent();
in.putExtra("payment", "unpaid");
/*in.putExtra("condition", "false");*/
setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
finish();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != request)
return;
if(main.resultTitle=="SUCCESS"){
Intent in = new Intent();
in.putExtra("payment", "paid");
setResult(22,in);
}else if(main.resultTitle=="FAILURE"){
Intent in = new Intent();
in.putExtra("payment", "unpaid");
setResult(22,in);
// finish();
}else if(main.resultTitle=="CANCELED"){
Intent in = new Intent();
in.putExtra("payment", "unpaid");
setResult(22,in);
// finish();
}
launchSimplePayment.updateButton();
title.setText(resultTitle);
title.setVisibility(View.VISIBLE);
info.setText(resultInfo);
info.setVisibility(View.VISIBLE);
extra.setText(resultExtra);
extra.setVisibility(View.VISIBLE);
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent in = new Intent();
in.putExtra("payment", "unpaid");
setResult(1,in);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
A: PayPal Launches Android SDK for Developers
https://www.paypal-forward.com/innovation/paypal-launches-android-sdk-for-developers/
The documentation Here:
https://developer.paypal.com/webapps/developer/docs/integration/mobile/android-integration-guide/
A: package com.paypal;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
public class MainActivity extends AppCompatActivity {
public static String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox environments.
public static String CONFIG_CLIENT_ID = "Add your Client ID"; /// add your paypal client id
private static int REQUEST_CODE_PAYMENT = 1;
public static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID);
Button btn_payment;
String paypal_id,paypal_state,paypal_amount,paypal_currency_code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_payment = (Button)findViewById(R.id.btn_payment);
btn_payment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBuyPressed();
}
});
}
public void onBuyPressed() {
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getThingToBuy(String paymentIntent) {
return new PayPalPayment(new BigDecimal("1"), "USD", "sample item ",
paymentIntent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e("Show", confirm.toJSONObject().toString(4));
Log.e("Show", confirm.getPayment().toJSONObject().toString(4));
JSONObject json=confirm.toJSONObject();
JSONObject responce = json.getJSONObject("response");
paypal_id = responce.getString("id");
paypal_state = responce.getString("state");
JSONObject payment=confirm.getPayment().toJSONObject();
paypal_amount=payment.getString("amount");
paypal_currency_code=payment.getString("currency_code");
Toast.makeText(getApplicationContext(), "PaymentConfirmation info received" + " from PayPal", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "an extremely unlikely failure" +
" occurred:", Toast.LENGTH_LONG).show();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Toast.makeText(getApplicationContext(), "An invalid Payment or PayPalConfiguration" +
" was submitted. Please see the docs.", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
///////////////// decler paypal activity in manifest ///////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.paypal">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- for card.io card scanning -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- pay pal server decler -->
<service
android:name="com.paypal.android.sdk.payments.PayPalService"
android:exported="false" />
<activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
<activity
android:name="io.card.payment.CardIOActivity"
android:configChanges="keyboardHidden|orientation" />
<activity android:name="io.card.payment.DataEntryActivity" />
<!-- end -->
</application>
</manifest>
//////////////////// gradel ///////////////////
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.paypal"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.paypal.sdk:paypal-android-sdk:2.14.2'
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Python: How to get the created date and time of a folder?
Possible Duplicate:
How to get file creation & modification date/times in Python?
I would like to get the created date and time of a folder. Are there anyways to do that in python?
Thank you
A: You might use os.stat to retrieve this information.
os.stat(path).st_mtime // time of most recent content modification,
os.stat(path).st_ctime // platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: String seen as a Monoid Given a signature like this one or that one:
def foo[A, F[_]](implicit mon: Monoid[F[A]], pr: Pure[F]): F[A]
Assuming A is Char, is there a way to get a String instead of a List[Char]?
String does not take a type parameter, so I assume it's not possible. What's the next best option? Right now, I use mkString on the result, but that doesn't feel optimal.
I think String is a monoid with zero "" and append +...
A: It is possible to persuade String to masquerade as a higher-kinded type, and hence allow functions of the form of foo to be applicable. However, Scala's type inference isn't currently up to the job of inferring foo's type arguments, so you'll have to supply them explicitly,
// Assuming the the definitions of Pure and Monoid from Scalaz
type ConstString = {
type λ[X] = String
}
implicit def StringPure = new Pure[ConstString#λ] {
def pure[A](a: => A) = a.toString
}
val sm = implicitly[Monoid[String]]
val sp = implicitly[Pure[ConstString#λ]]
val f : String = foo[Char, ConstString#λ](sm, sp) // OK
Note that the Char type argument to foo is unused and can be anything, but must be something: in this case either Char is the natural choice, but Nothing or Any would do as well.
Note that this solution trades on String's special characteristics: values of all types are convertible to Strings so pure[A](a : => A) : String is implementable for all types A. Replicating this idiom for types other than String would most likely have to exploit some mechanism for implementing type-specific cases in the body of pure (eg. a pattern match of some sort).
A: The best solution I can think of it is to define an implicit conversion from List[Char] to String.
A: Your analysis, that scala's type-system will reject String as not being a "higher kinded type" * -> * is correct. That is, the type String is not assignable to F[_] for any F. You could try (I have not checked this) implicit conversions...
def foo[A, F[_], That](implicit mon: Monoid[F[A]], pr: Pure[F], FA_Is_That: F[A] <%< That)
...but this will not be that useful I suspect because you'd have to provide your own bespoke conversions where required but also because the performance would be terrible, assuming this is a hot part of the code.
Or, using the standard library, you could use the CanBuildFrom machinery but it's far from obvious how nicely this will mix with the scalaz-style typeclasses.
def foo[A, F[_], That](implicit mon: Monoid[F[A]], pr: Pure[F], b: CanBuildFrom[A, F[A], That]): That
In the body of the method, of course, you will need to use the builder to construct the return value, as opposed to the Monoid/Pure typeclasses, rendering them somewhat redundant, I suspect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Getting old Dao Object in ormlite I am using ormlite for sqlite database in my android application. It's a login based application and I have database in SD card. For user abc, the requirement is when user login with different user like xyz then application authenticate the user from the server and server replace the db for user xyz. But when I am trying to access the login credentials it is giving the old credentials while the database is reflecting the new credentials.
I also tried:
DaoManager.clearCache();
It is not working also I tried:
DatabaseManager<DatabaseHelper> manager = new DatabaseManager<DatabaseHelper>();
manager.releaseHelper(DatabaseHelperGenerator.getDataBaseHelperInstance())
After this when I tried to fire this query:
Dao<LoginAuthentication, Integer> loginAuthenticationDao = null;
DatabaseHelperGenerator.getDataBaseHelperInstance().
clearLoginDao(LoginAuthentication.class);
loginAuthenticationDao = DatabaseHelperGenerator.getDataBaseHelperInstance().
getUserDao(LoginAuthentication.class);
List<LoginAuthentication> loginAuthenticationList =
loginAuthenticationDao.queryForAll();
It is giving IllegalStateException :Database not open
Looking for help.
A: Seems to me that you are going in the wrong direction here.
*
*You are assuming that the DAO is caching objects for you but unless you have enabled an object cache on a particular DAO then that's not the case.
*DaoManager.clearCache() doesn't clear object caches but instead clears the cached DAO objects.
*Once you release the helper, the database connection is closed which is the reason why you are getting the IllegalStateException.
I'd do some debugging of your application or some logging of values to see where the problem lies. Here are some thoughts:
*
*If you are using an object cache, have you tried to disable it? Have you tried flushing the object cache by calling Dao.clearObjectCache()? Again, a cache will only exist if you have turned it on. It is not on by default.
*What code are you using to persist the login information? Anything different than other calls?
*How about using the Dao.queryRaw() methods to dump the database right after the insert?
*Any transactions?
Best of luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: callback for add-to-timeline plugin? When a user comes to my website and tries to allow publish_action permission, he will click on the 'add-to-timeline' plugin button.
Then a popup dialog appears and user will allow the required permission.
What I want to find out is that if we can specify any callback function to invoke after user allows the permission.
I know we can subscribe to 'edge.create' event through FB.Event.subscribe, but I couldn't find a similar solution for 'add-to-timeline'.
At least, it wasn't written on its document as far as I read.
Can somebody help me?
A: You can subscribe to the global events to accomplish this.
If you subscribe to auth.login, auth.authResponseChange, or auth.statusChange they will be called after the user authorized your application via 'add-to-timeline'.
So for example you could do this...
FB.Event.subscribe('auth.login', function(response) {
alert('The user has just authorized your application');
});
However I'm guessing what you want is the same thing that I wanted which is to have the action added to the timeline after the user clicks 'add-to-timeline' the first time and then on subsequent visits to your site just have it added to the timeline automatically.
To do that you would do this...
/** put your FB.init right here **/
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.status == 'connected') {
FB.api("/me/foobar:watch" + "?video=http://foobar.com/video/123","post",
function(response) {
if (!response || response.error) {
alert("Error");
} else {
alert("Post was successful! Action ID: " + response.id);
}
});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone-Development - EXC_BAD_ACCESS after UIView beginAnimations -> didStopSelector [UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(scrollViewScrolled)];
[scrollView setContentOffset:scrollToPosition];
[UIView commitAnimations];
//////////////////////////
- (void)scrollViewScrolled {
[self putScreenShotToScrollView];
[self loadImageStack];
}
//////////////////////////
- (void)putScreenShotToScrollView {
UIImageView *scrollViewScreenShotView;
float scrollViewScreenShotPositionX;
float scrollViewScreenShotPositionY;
CGRect scrollViewScreenShotFrame;
scrollViewScreenShotView = [[UIImageView alloc] initWithImage:usedImageStack.screenShot];
// So, always when the app try to access the usedImageStack.screenShot the exception EXC_BAD_ACCES determines the app
// usedImageStack and the property screenShot have an address, so not 0x0
}
Do you know what's the problem?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to retrive Image data from Image view in android I have two Image view I have to compare them. I don't know on which format I have to take them.I want to retrieve Image Data.
A: Here you are :)
imageView.getDrawable();
Then just compare two Drawables from both :)
A: (not sure but) i think first you need to store in drawable data type and and convert it in to Blob or String then you can compare
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF - Referencing multiple resources Experts,
In XAML I would like to create a many-to-many relationship between entities.
Basically I would like for multiple "Manager" objects to be able to manage multiple "Items". The following XAML should describe what I'm looking for:
<Grid>
<Grid.Resources>
<cc:Manager x:Key="Manager1"/>
<cc:Manager x:Key="Manager2"/>
</Grid.Resources>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
</cc.Manager.ManagedBy>
</cc:Item>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" /> <!-- ERROR HERE -->
</cc.Manager.ManagedBy>
</cc:Item>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager2" />
</cc.Manager.ManagedBy>
</cc:Item>
</Grid>
The attached property (Manager.ManagedBy) is of type ManagedByCollection...
ManagedByCollection : List<ManageBy>
With this I get the following error message:
The object 'Object' already has a child and cannot add 'StaticResourceExtension'. 'Object' can accept only one child. Line NN Position NN.
So, I wen't back to MSDN and realized there's a ContentPropertyAttribute to tell the XAML compiler what property is the default one when nothing else is specified. The LinearGradientBrush, for example, uses that attribute to enable us to write just ...
<LinearGradientBrush ... >
<GradientStop ... />
<GradientStop ... />
<GradientStop ... />
</LinearGradientBrush>
... instead of ...
<LinearGradientBrush ... >
<GradientStopCollection>
<GradientStop ... />
<GradientStop ... />
<GradientStop ... />
</GradientStopCollection>
</LinearGradientBrush>
So, I was thinking I just needed to specify the indexer of ManagedByCollection as the class' ContentProperty:
[ContentProperty("Item")
ManagerCollection : List<Manager>
Unfortunately, this does not resolve the issue. Currently the following works...
<cc.Manager.ManagedBy>
<ManagerCollection>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" />
<cc:ManagerCollection>
</cc.Manager.ManagedBy>
... but, again, I would prefer the more readble syntax:
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" />
</cc.Manager.ManagedBy>
Any help or hints would be appreciated.
A: You can initialize the collection explicitly in the constructor of Item:
public Item()
{
Manager.SetManagedBy(this, new ManagedByCollection());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: search bar not working? i have a SQL file where 5 different type of data is stored. I am adding this data in a dictionary specified with keys. and then i am adding this dictionary to tableData array as a dataSource for table and searchBar. But it is not searching anything.
adding code below
- (void)viewDidLoad {
[super viewDidLoad];
dataSource =[[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc]init];
searchedData = [[NSMutableArray alloc]init];
NSString *query = [NSString stringWithFormat:@"SELECT * FROM Vegetables"];
SQLite *sqlObj1 = [[SQLite alloc] initWithSQLFile:@"ShoppersWorld.sqlite"];
[sqlObj1 openDb];
[sqlObj1 readDb:query];
// [query release];
for (int i=0; i<[dataSource count]; i++) {
NSLog(@"data:%@",[dataSource objectAtIndex:i]);
}
while ([sqlObj1 hasNextRow])
{
NSString *name=[sqlObj1 getColumn:1 type:@"text"];
NSString *price=[sqlObj1 getColumn:2 type:@"text"];
NSString *quantity=[sqlObj1 getColumn:3 type:@"text"];
NSString *unit=[sqlObj1 getColumn:4 type:@"text"];
NSString *total=[sqlObj1 getColumn:5 type:@"text"];
dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: name,@"nameOfVegetables",
price,@"priceOfVegetables",
quantity,@"quantityOfVegetables",
unit,@"unitOfVegetables",
total,@"totalPriceOfVegetables",nil];
//NSLog(@"results:%@ %@",dict);
[dataSource addObject:dict];
}
[tableData addObjectsFromArray:dataSource];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
// Configure the cell.
else {
cell.productLbl.text= [NSString stringWithFormat:@"%@",[[tableData objectAtIndex:indexPath.row]objectForKey:@"nameOfVegetables"] ];
cell.bPriceLbl.text = [NSString stringWithFormat:@"Rs %d/Kg",
[[[tableData objectAtIndex:indexPath.row] objectForKey:@"priceOfVegetables"] intValue]];
cell.qtyLbl.text = [NSString stringWithFormat:@"QTY: %@ %@",[[tableData objectAtIndex:indexPath.row]
objectForKey:@"quantityOfVegetables"],[[tableData objectAtIndex:indexPath.row] objectForKey:@"unitOfVegetables"]] ;
cell.tPriceLbl.text = [NSString stringWithFormat:@"TOTAL: %@",[[tableData objectAtIndex:indexPath.row]
objectForKey:@"totalPriceOfVegetables"]];
}
return cell;
}
#pragma search operations
- (IBAction)search:(id)sender{
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,40,320,30)];
sBar.delegate = self;
[self.view addSubview:sBar];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
// only show the status bar’s cancel button while in edit mode
[sBar setShowsCancelButton:YES animated:YES];
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
[sBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] || searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
for (int i = 0; i < [dataSource count]; i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [dataSource objectAtIndex:i];
NSString *name = [NSString stringWithFormat:@"%@", [temp valueForKey:@"nameOfVegetables"]];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
sBar.hidden= YES;
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
[tableData addObjectsFromArray:dataSource];
@try{
[tableview reloadData];
}
@catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = @"";
}
A: In search delegate methods you manipulate not with searchedData but tableData array. As these name suggest, array searchedData is supposed to store filtered data.
By the way, your approach to use sqlite for data source and absorbing all database into array is wrong. In cellForRowAtIndexPath read from sqlite database only data you need at the moment.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// load from sqlite only data for this cell.
// Use searchBar.text with sqlite's LIKE to filter data from database
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = @"SignsCellIdentifier";
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSString *sql = [NSString stringWithFormat:@"SELECT fieldNameFromTable FROM TableName WHERE FieldToLookForIn LIKE \"%%%@%%\" LIMIT 1 OFFSET %u", searchBar.text ? searchBar.text : @"", row];
sqlite3_stmt *stmt;
int res = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
if (res != SQLITE_OK) {
NSLog(@"sqlite3_prepare_v2() failed"];
return nil;
}
if (sqlite3_step(stmt) == SQLITE_ROW) {
const unsigned char *name = sqlite3_column_text(stmt, 0);
cell.text = [NSString stringWithUTF8String:(const char*)name];
}
sqlite3_finalize(stmt);
return cell;
}
How to apply search in this approach? In textDidChange do nothing but call [tableView reloadData]. And in cellForRowAtIndexPath load data with sqlite LIKE using searchBar.text as search term. So reloadData will load only filtered records. searchBarSearchButtonClicked will call only resignFirstResponder of it's caller, removing keyboard off screen. It doesn't need to do anything more because search is already done. searchBarCancelButtonClicked will set text property of it's caller to nil, call reload data and again call resignFirstResponder.
- (void)searchBarCancelButtonClicked:(UISearchBar *)s {
s.text = nil;
[tableView reloadData];
[s resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)s {
// search is already done
[s resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[tableView reloadData];
}
numberOfRowsInSection should also request db with the same SELECT as in cellForRowAtIndexPath, but with SELECT COUNT. Writing this method will be your homework)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fullcalendar in ASP.NET and JSON response I am fetching my events with webservice:
Public Function webGetCalendarEvents(ByVal startDate As String, ByVal endDate As String) As String
Dim sDate As DateTime = ToUnixTimeSpan(startDate)
Dim eDate As DateTime = ToUnixTimeSpan(endDate)
Dim DS As DataSet = DBStoredProcedures.GetEventsCalendarJSON(95, sDate, eDate)
DS.Tables(0).TableName = "events"
Dim dataTable As DataTable = DS.Tables(0)
Dim jsonEvents As String = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable)
Return jsonEvents
The json response is like:
[
{
"id":589311,
"title":"My Title",
"priority":"",
"start":"2011-09-19T08:00",
"end":"2011-09-26T16:00",
"allDay":"false",
"editable":"true",
"EOSid":0
}
]
The problem is, that all my events are shown as allDay events. It seems like "false" value of "allDay" is not recognized.
I am evaluating the response inside fullcalendar.js file (version 1.5.2., line around 981):
success: function (events) {
events = (typeof events.d) == 'string' ? eval('(' + events.d + ')') : events.d || [];
How can I render events to accept "allDay" parameter?
A: SOLVED:
I changed my SQL procedure where I was generating "allDay" parameter. I changed from:
CASE WHEN EventTypeID=3 THEN 'false' ELSE 'true' END as allDay
to:
CASE WHEN EventTypeID=3 THEN CAST(0 as BIT) ELSE CAST(1 as BIT) END as allDay
This gave me JSON response:
{"allDay": false}
instead of:
{"allDay": "false"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble using java class within jruby I'm trying to use Java Opencl from within jruby, but am encountering a problem which I can't solve, even with much google searching.
require 'java'
require 'JOCL-0.1.7.jar'
platforms = org.jocl.cl_platform_id.new
puts platforms.class
org.jocl.CL.clGetPlatformIDs(1, platforms, nil)
when I run this code using: jruby test.rb
I get the following error, when the last line is uncommented:
#<Class:0x10191777e>
TypeError: cannot convert instance of class org.jruby.java.proxies.ConcreteJavaP
roxy to class [Lorg.jocl.cl_platform_id;
LukeTest at test.rb:29
(root) at test.rb:4
Just wondering whether anyone has an idea on how to solve this problem?
EDIT:
ok so I think I've solved the first part of this problem by making platforms an array:
platforms = org.jocl.cl_platform_id[1].new
but that led to this error when adding the next couple of lines:
context_properties = org.jocl.cl_context_properties.new()
context_properties.addProperty(org.jocl.CL::CL_CONTEXT_PLATFORM, platforms[0])
CodegenUtils.java:98:in `human': java.lang.NullPointerException
from CodegenUtils.java:152:in `prettyParams'
from CallableSelector.java:462:in `argumentError'
from CallableSelector.java:436:in `argTypesDoNotMatch'
from RubyToJavaInvoker.java:248:in `findCallableArityTwo'
from InstanceMethodInvoker.java:66:in `call'
from CachingCallSite.java:332:in `cacheAndCall'
from CachingCallSite.java:203:in `call'
from test.rb:36:in `module__0$RUBY$LukeTest'
from test.rb:-1:in `module__0$RUBY$LukeTest'
from test.rb:4:in `__file__'
from test.rb:-1:in `load'
from Ruby.java:679:in `runScript'
from Ruby.java:672:in `runScript'
from Ruby.java:579:in `runNormally'
from Ruby.java:428:in `runFromMain'
from Main.java:278:in `doRunFromMain'
from Main.java:198:in `internalRun'
from Main.java:164:in `run'
from Main.java:148:in `run'
from Main.java:128:in `main'
for some reason when I print the class of platforms[0] it's listed as NilClass!?
A: You are overlooking a very simple mistake. You write
platforms = org.jocl.cl_platform_id.new
but that line creates a single instance of the class org.jocl.cl_platform_id. You then pass that as the second parameter to org.jocl.CL.clGetPlatformIDs in
org.jocl.CL.clGetPlatformIDs(1, platforms, nil)
and that doesn't work, because the second argument of the method requires an (empty) array of org.jocl.cl_platform_id objects.
What the error says is: "I have something that is a proxy for a Java object and I can't turn it into an an array of org.jocl.cl_platform_id objects, as you are asking me to do.
If you just say
platforms = []
and pass that in, it might just work :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: C# Merging 2 dictionaries and adding values between them I am learning C# and needed to merge two dictionaries so I could add values found in both.
The first dictionary is payePlusNssf that holds a value for each key (key represents employee ID). So far I have employees 1,2,3,4 and 5
Dictionary<int, decimal> payePlusNssf = new Dictionary<int, decimal>();
paye.ToList().ForEach(x =>
{
var deductNSSF = x.Value + nssfAmount;
payePlusNssf.Add(x.Key, deductNSSF);
});
The 2nd dictionary is nhifRatesDictionary that holds rates to be added to each value per employee in the first dictionary.
Dictionary<int, IEnumerable<NHIFRates>> nhifRatesDictionary =
new Dictionary<int, IEnumerable<NHIFRates>>();
basicPayDictionary.ToList().ForEach(x =>
{
List<NHIFRates> nhifValueList = new List<NHIFRates>();
// Using Employee basic pay
decimal basicPay = x.Value;
bool foundflag = false;
foreach (var item in nhifBracketList)
{
if (basicPay >= item.Min && basicPay <= item.Max)
{
nhifValueList.Add(new NHIFRates { Rate = item.Rate });
foundflag = true;
break;
}
}
if (!foundflag)
{
nhifValueList.Add(new NHIFRates { Rate = 0m });
}
nhifRatesDictionary.Add(x.Key, nhifValueList);
});
struct NHIFRates
{
public decimal Rate { get; set; }
}
In summary I need this after merging and adding:
Dict 1 Dict 2 Result Dict 3
key value key rate key value
1 500 1 80 1 580
2 1000 2 100 2 1100
3 2000 3 220 3 2220
4 800 4 300 4 1100
5 1000 5 100 5 1100
How do I achieve this? I have looked at past similar problems on this site but have not been very helpful to me.
A: Not tested but try:
payePlusNssf.ToDictionary(
v => v.Key,
v => v.Value + nhifRatesDictionary[v.Key].Sum(nhifr => nhifr.Rate)
);
This assumes that since the value of nhifRatesDictionary is IEnumreable you want to sum over all the values in the enumerable. This should also work if the IEnumerable is empty. If you know that there is exactly one value for each key then you can use:
payePlusNssf.ToDictionary(
v => v.Key,
v => v.Value + nhifRatesDictionary[v.Key].Single(nhifr => nhifr.Rate)
);
A: What about a simple for cycle?
Dictionary<int,decimal> d3 = new Dictionary<int,decimal>();
for (int i = 1,i<=payePlusNssf.Count,i++)
{
d3.Add (i,payePlusNssf[i]+((nhifRatesDictionary[i])[0]).Rate);
}
If the ID numbers are not guranteed to be this simple you can use
foreach (var x in payePlusNssf)
{
d3.Add(x.Key,x.Value+ ((nhifRatesDictionary[x.Key])[0]).Rate);
}
Or do it completely differently, do not keep three separate dictionaries that are guaranteed to have the same keys and create an employee class like
class Employee
{
public decimal payePlusNssf;
public decimal nhifRate;
public decimal Sum
{
get { return payePlusNssf + nhifRate ;}
}
}
and have one Dictionary with everything - saves you problems with keeping the dictionaries all updated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GHC/Haskell profiling: function consumes time without being called I have compiled a Haskell program with GHC with enabled profiling.
$ ./server +RTS -M6m -p -RTS
I get a profile like:
individual inherited
COST CENTRE MODULE no. entries %time %alloc %time %alloc
poke_a4u64 Generator 2859 56436 0.0 0.0 0.4 0.4
storeParameter Generator 2860 0 0.4 0.4 0.4 0.4
ppCurrent Generator 2866 56436 0.0 0.0 0.0 0.0
ppFeedback Generator 2861 56436 0.0 0.0 0.0 0.0
It looks like storeParameter is never called, but consumes time and memory. Since storeParameter calls ppCurrent, I guess that storeParameter is called 56436 times, like ppCurrent. Why is not shown?
A: It's a bug in the ghc profiling. I don't know of a workaround, but Simon M has promised improvements in the next release.
A: I've found the entries column to lie in my own code: e.g. main getting called 6 times!
So I wouldn't worry too much about it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Memcache: multiple set / serializing I have a question about setting and retrieving memcached variables. Say, I have 5-10 objects with 10 attributes and I want to save those attribute in memcached - what is considered to be more efficient - saving object through serialization or multiple set for each attribute?
Obviously it's a payoff between:
*
*memory size + greater traffic(due to greater string size) and;
*connection time.
I'm using php with memcached lib.
A: As I know, Memcached library use serialization for PHP data anyway (except numbers and strings), so, usage of serialize is preferable. But if you really want to write your own "serialization" mechanizm which saves all attributes separately (this attributes values are strings/numbers or other objects?) you can use http://php.net/manual/ru/memcached.setmulti.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Uploading the video through iPhone App programmatically How can we upload the video through iPhone App programmatically, can any one please provide me some sample code for the same.
Got a sample from:
http://urinieto.com/2010/10/upload-videos-to-youtube-with-iphone-custom-app/
But always getting "NoLinkedYouTubeAccount Error" while uploading the video.
Please help me.
Many Thanks
iPhone Developer
A: Sign in via web to your account. Subscribe to a channel and it will work. This must link your Google's account to your Youtube's account.
A: I just resolved similar problem by creating a channel in Youtube's account. Please check for the settings of Youtube's account before uploading the video.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to add a context to whole controller in zendFramework there are posibility to add for example json context to specific action:
$this->_helper->ajaxContext()
->addActionContext('index', 'json')
->initContext();
but how about if I want to add jsonContext to two or all action in current controller;
I tryed:
$this->_helper->ajaxContext()
->addActionContext(array('index', 'second'), 'json')
->initContext();
but without result.
I know I can use:
$this->_helper->ajaxContext()
->addActionContext('index', 'json')
->initContext();
$this->_helper->ajaxContext()
->addActionContext('second', 'json')
->initContext();
but I am looking more original solution.
Thank you in advance.
A: I know this is an old question, but in case someone else is looking for a solution, I think subclassing Zend_Controller_Action_Helper_ContextSwitch is the way to go.
In my case, I subclassed it so that it considers "*" as a wildcard for "all actions" :
class My_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action_Helper_ContextSwitch {
/**
* Adds support logic for the "*" wildcard.
*
* @see Zend_Controller_Action_Helper_ContextSwitch::getActionContexts()
*/
public function getActionContexts($action = null) {
$parentContexts = parent::getActionContexts($action = null);
$contextKey = $this->_contextKey;
$controller = $this->getActionController();
if (isset($controller->{$contextKey}['*'])) {
$contexts = $controller->{$contextKey}['*'];
}
else {
$contexts = array();
}
return array_merge($parentContexts, $contexts);
}
/**
* Adds support logic for the "*" wildcard.
*
* @see Zend_Controller_Action_Helper_ContextSwitch::hasActionContext()
*/
public function hasActionContext($action, $context) {
if (!$result = parent::hasActionContext($action, $context)) {
$controller = $this->getActionController();
$contextKey = $this->_contextKey;
$contexts = $controller->{$contextKey};
foreach ($contexts as $action => $actionContexts) {
foreach ($actionContexts as $actionContext) {
if ($actionContext == $context && $action == '*') {
return true;
}
}
}
}
return $result;
}
}
And in my controller, I use the following syntax to set-up the context switch :
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch
->addActionContext('*', array('help'))
->initContext()
;
By doing this, the "help" context is available to every actions in my controller.
These samples have not been fully tested and are certainly not perfect, but they are a good starting point to solve the problem.
A: Well, your second version is wrong and your third version is overkill.
This is how I usually do it:
$this->_helper->ajaxContext()
->addActionContext('index', 'json')
->addActionContext('second', 'json')
->initContext();
If that is not enough for you, you could loop through all actions and add them to the context.
A: To add the context to ALL actions, you can place this into the init of your controller:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$action = $this->getRequest()->getActionName();
$contextSwitch->addActionContext($action, 'pdf')
->initContext();
This works as long as you don't use forward or redirect, since it adds the context to the current action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Opengl rotation at a point I want to rotate a shape in opengl, but I want to rotate it at a point. Namely I have a cylinder and I want to rotate it so it looks like it is spinning at the bottom and the spin 'size' increases until the object falls to the ground. How would I do this kind of rotation in opengl?
A: *
*Translate to the origin
*Rotate
*Translate back
So, if you want to rotate around (a,b,c), you would translate (-a,-b,-c) in step 1, and (a,b,c) in step 3.
(Don't be afraid of the number of operations, by the way. Internally all you do is multiply the transform matrix three times, but the pipeline that transforms the vertices is agnostic of how many operations you did, it still only uses the one final matrix. The magic of using a matrix for transformation.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: FSCK shows different results when checked as system and non-system disk I have a problem with UBUNTU 10.04 filesystem, which reports different results when a drive is mounted and checked with FSCK as the system drive and when it is checked by another system drive:
sudo fsck /dev/sdb1
fsck from util-linux-ng 2.17.2
e2fsck 1.41.11 (14-Mar-2010)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
57217 inodes used (24.81%)
42 non-contiguous files (0.1%)
65 non-contiguous directories (0.1%)
# of inodes with ind/dind/tind blocks: 0/0/0
Extent depth histogram: 50910/20
293868 blocks used (31.88%)
0 bad blocks
1 large file
43327 regular files
7242 directories
59 character device files
26 block device files
0 fifos
509 links
6549 symbolic links (6187 fast symbolic links)
5 sockets
--------
57717 files
sudo fsck -n -t ext4 /dev/sda1
fsck from util-linux-ng 2.17.2
e2fsck 1.41.11 (14-Mar-2010)
Warning! /dev/sda1 is mounted.
Warning: skipping journal recovery because doing a read-only filesystem check.
/dev/sda1 contains a file system with errors, check forced.
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Free blocks count wrong (628134, counted=628213).
Fix? no
Free inodes count wrong (173391, counted=173379).
Fix? no
/dev/sda1: ********** WARNING: Filesystem still has errors **********
/dev/sda1: 57217/230608 files (0.1% non-contiguous), 293722/921856 blocks
Whenever the drive is mounted as the system / boot drive, running fsck (check don't fix) shows INODE and BLOCK counts are wrong, yet checking the same drive from another system disk reports that it's fine.
Any ideas ?
A: This should probably be on SuperUser or ServerFault, not StackOverflow, but anyway:
you can only fsck -n a file system that is mounted read-only. While the file system is mounted read-write, it will be inconsistent until cleanly unmounted, or the journal is recovered. The important message is
Warning: skipping journal recovery because doing a read-only filesystem check.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Bluetooth HFP connection with Iphone, Droid We are developing a Bluetooth hands-free module in windows CE. We are able to establish successful hands-free connection with a number of phones (Samsung, LG, nokia) and able to receive ‘RING’ message on call alert.
But for Iphone (iphone4), after establishing a successful hfp connection, we are getting a ‘U’ message in reply to any AT commands instead of ‘OK’ or ‘ERROR’ message.
What may be the reason for this?
For DROID phones my device is detected as a hands-free device but I am not able to establish an hfp connection with it.
Regards,
Swdeveloper.
A: I don't know much about HFP but I've done plenty with AT-command driven devices. The "U" you're receiving could be a misinterpreted "OK" if your bits/speed/parity - or some related setting - are incorrect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to return result of transaction in JPA Just a background since I am used to using JDBC since I worked on an old project.
When saving into database, I always set the value to -1 for any unsuccessful insert
public class StudentDao{
//This dao method returns -1 if unsuccessful in saving
public int save(Student stud){
Statement st = con.createStatement();
try{
int val = st.executeUpdate("INSERT student VALUES(.......)");
}catch(Exception e){
return -1;
}
}
}
Based on the return I could could tell if the insert is successful so that I could do the exact logic.
(Tell the user that the transaction is incomplete...)
Now, I used EJB in persisting entity. Most of the tutorials that I am seeing only have this construct.
Netbeans is generating this code also with a 'void' return.
@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;
public void save(Student student){
em.persist(student);
}
}
When saving entity on a servlet, it just call the method like this code.
@WebServlet(name = "StudentServlet",
loadOnStartup = 1,
urlPatterns = {
"/addStudent",})
public class StudentServlet extends HttpServlet {
@EJB
private StudentFacade studentFacade;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//extract HTTP form request parameters then set
Student stud = Util.getStudent(request);
studentFacade.save(stud);
}
}
But how will I know if the insert is successful? (Dont catch the exception and then just let it propagate.
I have configured my error page so obviously this would catch the error???)
Sorry I am getting confused on integrating my EJB components but I am seeing its benefits.
I just need some advise on some items. Thanks.
A: The container will propagate the exception to the caller (if you don't do anything with it inside the EJB). That would be probably the SQLException I guess. You can catch it on the servlet and do whatever you want with it. If you use Container Managed Transactions (CMT) the transaction will be rolled back for you automatically by the container and the student object won't be added. As you said, you can of course leave the exception on the web layer as well and then prepare a special error page for it. All depends on your usage scenario.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: timeout value for ios facebook sdk request hey guys does the ios facebook sdk asynchronous request delegate allow developer to specify some sort of timeoutInterval value? i know that the nsURLRequest has a timeoutInterval value that u can set.
Thanks for your help.
scenario:
i make an async request call. the connection dies after the request call goes out and before the response comes back. currently, i have no way of detecting this. what i want is: i call line number 2. after 10 sec, no response comes back, line 5 would get execute. Or something along the line that there were an error.
1 - // async request call
2 - [facebook requestWithGraphPath:@"me/home" addParams:nil andDelegate:self];
3 - // delegate
4 - - (void) request :(FBRequest *)request didLoad:(id)result {}
5 - - (void) request :(FBRequest *)request didFailWithError :(NSError *)error {}
A: see Facebook ios SDK, FBRequest.m file at the beginning:
static const NSTimeInterval kTimeoutInterval = 180.0;
then it is used by a connect method. You can change it or patch the SDK so it could be set externally.
hope this helps
A: FBRequest.m applies it's timeoutInterval to NSMutableURLRequest, which ignores/overrides anything under 240 seconds. If your interested, read more about that here...
iPhone SDK: URL request not timing out
...otherwise it basically means the kTimeoutInterval in FBRequest.m is ignored if set to < 240, so don't bother with it.
I've just gone through this issue myself, I ended up using an NSTimer that will cancel the pending FBRequest's connection on timeout. see details here..
Facebook API - How to cancel Graph Request
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NHibernate Fluent group by I have this nhibernate criteria:
criteria.Add(Subqueries.PropertyIn("Id", DetachedCriteria.For<ReconItemReconSide>()
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("ReconItemFk"))
.Add(Projections.Min("ReconciliationSideFk")))
.Add(Expression.In(Projections.Property("ReconItemFk"), items))
));
-which becomes this query (I have removed some of the fields from the outer select to minimize the length here):
SELECT this_.Id as Id8_0_
FROM CI.BM_RECONCILIATION_SIDE this_
WHERE this_.Id in (SELECT this_0_.BM_RECON_ITEM as y0_,
min(this_0_.BM_RECONCILIATION_SIDE) as y1_
FROM CI.BM_RECON_ITEM_RECON_SIDE this_0_
WHERE this_0_.BM_RECON_ITEM in (345061 /* :p0 */,345877 /* :p1 */)
GROUP BY this_0_.BM_RECON_ITEM)
The problem is that I want the inner-select to select one field only (min(this_0_.BM_RECONCILIATION_SIDE)), but the groupby also add the groupby-field to the select.
I want to be able to create a groupby without having to project the groupby field itself.
The query should look similar to this:
SELECT this_.Id as Id8_0_
FROM CI.BM_RECONCILIATION_SIDE this_
WHERE this_.Id in (SELECT
min(this_0_.BM_RECONCILIATION_SIDE) as y1_
FROM CI.BM_RECON_ITEM_RECON_SIDE this_0_
WHERE this_0_.BM_RECON_ITEM in (345061 /* :p0 */,345877 /* :p1 */)
GROUP BY this_0_.BM_RECON_ITEM)
Any idea how to solve this ?
A: well, it seems like this is still an open issue with nHib.
like they always say- you're welcome to implement it yourself.. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RadioButton style that crash ( ? ) I wrote RadioButton style - and the code crash and i don't find any reason to having this crash.
<Style x:Key="RadioButtonStyle2" TargetType="RadioButton">
<Setter Property="Foreground" Value="#5DFFC8" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid>
<vsm:VisualStateManager.VisualStateGroups>
<vsm:VisualStateGroup x:Name="CheckStates">
<vsm:VisualState x:Name="Checked">
<Storyboard>
<DoubleAnimation Duration="0" Storyboard.TargetName="RadioButtonStyle2" Storyboard.TargetProperty="Opacity" To="1"/>
<ColorAnimation Duration="0" Storyboard.TargetName="RadioButtonStyle2" Storyboard.TargetProperty="Foreground" To="Black" />
</Storyboard>
</vsm:VisualState>
A: Note: the first block of code in this answer tries to repeat the problem:
<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<Style x:Key="RadioButtonStyle2"
TargetType="RadioButton">
<Setter Property="Foreground"
Value="#5DFFC8" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid>
<vsm:VisualStateManager.VisualStateGroups>
<vsm:VisualStateGroup x:Name="CheckStates">
<vsm:VisualState x:Name="Checked">
<Storyboard>
<DoubleAnimation Duration="0"
Storyboard.TargetName="RadioButtonPart"
Storyboard.TargetProperty="Opacity"
To="1" />
<ColorAnimation Duration="0"
Storyboard.TargetName="RadioButtonPart"
Storyboard.TargetProperty="Foreground"
To="Black" />
</Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>
<RadioButton x:Name="RadioButtonPart" Foreground="{TemplateBinding Foreground}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot"
Background="White">
<RadioButton Style="{StaticResource RadioButtonStyle2}" IsChecked="True">Test</RadioButton>
</Grid>
</UserControl>
If the shown code is all there is, there is a lot missing.
I pasted the code I used to test your style here and added some. Have a look at the exception in the designer it will probably look like this:
This should tell you what is wrong. In my code there is a mismatch between the type of the Foreground property (Brush) and the animation (Color).
You will can make them match by animating the color property of the brush (SolidBrush)
Below is a better working sample (still not complete but the animations work)
<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<Style x:Key="RadioButtonStyle2"
TargetType="RadioButton">
<Setter Property="Foreground"
Value="#5DFFC8" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid>
<vsm:VisualStateManager.VisualStateGroups>
<vsm:VisualStateGroup x:Name="CheckStates">
<vsm:VisualState x:Name="Checked">
<Storyboard>
<DoubleAnimation Duration="0"
Storyboard.TargetName="RadioButtonPart"
Storyboard.TargetProperty="Opacity"
To="1" />
<ColorAnimation Duration="0"
Storyboard.TargetName="radioButtonForegroundColor"
Storyboard.TargetProperty="Color"
To="Black" />
</Storyboard>
</vsm:VisualState>
<vsm:VisualState x:Name="Unchecked">
<Storyboard>
<DoubleAnimation Duration="0"
Storyboard.TargetName="RadioButtonPart"
Storyboard.TargetProperty="Opacity"
To="0.5" />
<ColorAnimation Duration="0"
Storyboard.TargetName="radioButtonForegroundColor"
Storyboard.TargetProperty="Color"
To="Red" />
</Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>
<RadioButton x:Name="RadioButtonPart"
IsChecked="{TemplateBinding IsChecked}"
Content="{TemplateBinding Content}">
<RadioButton.Foreground>
<SolidColorBrush Color="White"
x:Name="radioButtonForegroundColor" />
</RadioButton.Foreground>
</RadioButton>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot"
Background="White">
<StackPanel>
<RadioButton Style="{StaticResource RadioButtonStyle2}"
Content="Test 1" />
<RadioButton Style="{StaticResource RadioButtonStyle2}"
IsChecked="False"
Content="Test 2" />
</StackPanel>
</Grid>
</UserControl>
A: The real problem is
Storyboard.TargetName="RadioButtonStyle2"
RadioButtonStyle2 is the name of this Style. The TargetName should be the name of one of the controls you defined inside your ControlTemplate.
When you are trying to check a RadioButton with this style it will give you an error. If you use Expression Blend, go to the Checked state within this style, it will throw you an error saying,
An animation is trying to modify an object named 'RadioButtonStyle2', but no such object can be found in the Grid.
I see you are trying to change the Opacity and the Foreground color when this RadioButton is checked. To do this, you need to add a ContentControl inside the Grid. And change the Opacity of the Grid and the Foreground color of this ContentControl in the Checked visual state, not the style itself.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send mail in asp.net through proxy server i am trying to send mail through asp.net using the code mentioned below.
it works fine without proxy environment. but now i am working with proxy servers and use proxy settings to connect to internet.
it gives error 'Failure Sending Mail'
Please anyone help ?
MailMessage msg = new MailMessage("[email protected]", TextBox1.Text);
msg.Subject = TextBox2.Text;
msg.Body = TextBox3.Text;
SmtpClient s = new SmtpClient();
s.Host = "smtp.gmail.com";
s.EnableSsl = true;
s.Credentials = new NetworkCredential("[email protected]", "password");
s.Send(msg);
A: Add this to your web.config and replace your.proxy.address with the address of proxy server:
<system.net>
<defaultProxy enabled="true">
<proxy proxyaddress="your.proxy.address"/>
</defaultProxy>
</system.net>
A: It would have worked from your home connection where there is no firewall, but to work same code in a company where they are using a corporate firewall, you need to request them for opening SMTP ports for your smtp server. Default is 25 gmail uses 587 and 465
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Library for logging Call Stack at runtime (Windows/Linux) I need a way to record the function stack trace in a debug log to help me diagnose a defect. The problem is that I need to implement this on Windows and Linux using C++.
After a little research, I have found that:
*
*For the Windows implementation, I can use StackWalk64 API function and family.
*Under Linux, I have found libunwind that sounds great.
*Or, I can use glibc's backtrace
Before starting work, I want some advice if this is the right way and to ask if there is an already written multi-platform library that can help. I suspect that I'm not the first programmer who needs this. :)
A: Google Breakpad handles all of this for you if you want to get crash dumps back from the field.
A: I wrote 2 articles about this topic, including Googles breakpad as well as a very thin self written approach that works for windows and linux:
Postmortem Debugging - http://drdobbs.com/tools/185300443
Post-Mortem Debugging Revisited - http://drdobbs.com/architecture-and-design/227900186
A: Some years ago I wrote this: http://drdobbs.com/cpp/191100567
Basically some macros log the place where the stack unwind happens when an exception is thrown.
An updated version of the framework can be found in the library Imebra (http://imebra.com)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: how to reload the activity without refreshing? i switch to next screen and then comes back to the original and wants to pick up where i left off , save and restore data.In Activity 1:i have more than 10 buttons i can select and unselect button,if go to next screen and if i come back it should not reload,it should show me where i leftoff,
up1 = (Button) findViewById(R.id.adultup1);
up1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (upt1 == 0) {
up1.setBackgroundResource(R.drawable.adultup1);
upt1 = 1;
} else {
up1.setBackgroundResource(R.drawable.adultup1_pressed);
upt1 = 0;
}
}
});
A: Look at image (and read text too) here: http://developer.android.com/reference/android/app/Activity.html
If you need to not reload state, you should think about what are you doing in each activity state.
If you do:
Activity1 -> startActivity(Activity2) -> Activity2 -> Activity2.onBackPressed -> Activity1
than, there is no reloading. On return from second to first you got called onResume
but If you do:
Activity1 -> startActivity(Activity2) -> Activity2 -> startActivity(Activity1) -> Activity1
then you need to save your state in some external class (static class member) and load Activity1 state from it in onCreate state.
The same would be (as you can see from image), when app proccess is killed, and user returns to interrupted activity.
If you simply return to Activity1 using finish() on Activity2, there will be no call to onCreate, just onResume
Store Button state
public static int _state = -1;
onCreate(Bundle savedInstanceState){
if(_state == -1){
_state = 0;
// this is first time we're using "_state" variable, so do init
} else {
// this is second or later, so just load state variable and setup UI
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How many swaping & comparsions in each sorting algorithm? class Sort
{
int[] arr;
int counter=0;
//Constructor
public Sort()
{
arr = new int[10000];
}
string address;
public void SwitchCase(int Case)
{
switch (Case)
{
case 1:
address = @"C:\Users\Aqib Saeed\Desktop\case1.txt";
break;
case 2:
address = @"C:\Users\Aqib Saeed\Desktop\case2.txt";
break;
case 3:
address = @"C:\Users\Aqib Saeed\Desktop\case3.txt";
break;
default:
break;
}
}
//Read file for input
public void FillArray()
{
using (StreamReader rdr = new StreamReader(address))
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToInt32(rdr.ReadLine());
}
}
}
// Insertion Sort
public void InsertionSort()
{
int insert;
for (int i = 1; i < arr.Length; i++)
{
insert = arr[i];
int moveItem = i;
while (moveItem > 0 && arr[moveItem - 1] > insert)
{
arr[moveItem] = arr[moveItem - 1];
moveItem--;
counter++;
}
arr[moveItem] = insert;
}
}
public void Counter()
{
Console.WriteLine(counter);
}
//Bubble Sorting
public void BubbleSort()
{
int temp;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
counter++;
}
}
}
}
//Selection Sorting
public void SelectionSort()
{
int min, temp;
for (int i = 0; i < arr.Length; i++)
{
min = i;
for (int j = i + 1; j < arr.Length; j++)
if (arr[j] < arr[min])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
counter++;
}
}
// Write Output to file
public void Writer()
{
using (StreamWriter wrtr = new StreamWriter(@"C:\Users\AqibSaeed\Desktop\SortedOutput.txt"))
{
for (int i = 0; i < arr.Length; i++)
{
wrtr.WriteLine(arr[i]);
}
}
}
}
static void Main(string[] args)
{
Sort srt = new Sort();
Console.WriteLine("Enter Case 1 OR 2 OR 3");
srt.SwitchCase(Convert.ToInt32(Console.ReadLine()));
srt.FillArray();
srt.BubbleSort();
srt.Writer();
Console.WriteLine("Sorted Output File Is Ready");
srt.Counter();
Console.ReadLine();
}
I implement my Sort class for sorting integers and place int counter to determine number of swaps and comparsions. But I am not sure it is working correctly! Is there any other way to determine number of swaping and comparsions?
A: You could create a class which implements IComparable to count the comparator access and a specialized collection which counts the swaps. Like that you dont have to count the access inside of the sort algorithms and you delegate the tasks more strict to code parts.
In the index operator you count the swap operations and in the IComparable implementation you count the comparisons
Example for a class SortItem which implements the IComparable:
public class SortItem<T> : IComparable<T> where T : IComparable
{
private static int _ComparisonCount = 0;
public static int ComparisonCount
{
private set
{
_ComparisonCount = value;
}
get
{
return _ComparisonCount;
}
}
public T Value
{
get;
set;
}
public static void ResetComparisonCount()
{
_ComparisonCount = 0;
}
#region IComparable<T> Members
public int CompareTo(T other)
{
ComparisonCount++;
return this.Value.CompareTo(other);
}
#endregion
}
and the sorting collection:
public class SortCollection<T> : IList<SortItem<T>>
{
public SortCollection(IList<T> sortList)
{
InnerList = sortList;
}
private IList<T> InnerList = null;
public T this[int key]
{
get
{
return InnerList[key];
}
set
{
SwapCount++;
InnerList[key] = value;
}
}
private int _SwapCount = 0;
public int SwapCount
{
private set
{
_SwapCount = value;
}
get
{
return _SwapCount;
}
}
public void ResetSwapCount()
{
_SwapCount = 0;
}
}
Here the execution:
List<Int32> baseList = new List<int>(new Int32 {6, 2, 7, 3, 1, 6, 7 });
SortCollection<Int32> sortList = new SortCollection<int>(baseList);
//do the sorting....
Console.WriteLine("Swaps: " + sortList.SwapCount.ToString());
Console.WriteLine("Comparisons: " + SortItem<Int32>.ComparisonCount.ToString());
SortItem<Int32>.ResetComparisonCount();
sortList.ResetSwapCount();
A: You are only counting swaps and not counting comparisons. If you want to count comparisons then you need to add an extra counter that you increment every time you pass an if comparison.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: Scan for devices I'm looking for a way to scan for android devices in my area.
It should work without internetaccess nor gps.
Just knowing the mac-address is enough for this app.
The first way I was thinking of was to use bluetooth.
It's possible to scan for bluetooth devices, but it isn't possible to make your own device visibile forever (Android docs say that's possible, but it's limited to max 300 seconds).
The next what came up in my mind was to scan for wifi networks.
Almost every android phone uses wifi.
It's possible to scan wifi networks.
But is it possible to set my device as an accesspoint?
It can with systemsoftware but I would like to do it programmatically.
Does someone know if that's possible? Is there another way to let devices 'see' eachother?
Thnx
A:
But is it possible to set my device as an access point?
This is possible by reflection, but not recommended. However you cannot force others to join your Wifi network. That is entirely their prerogative.
Is there another way to let devices 'see' each other?
Yes it is possible to see other device on the network. Check out these answers. If you have your apk installed on their device you can even try WiFi multicasting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In .Net MVC3 how to handle server side error in JqGrid? I am using JqGrid with MVC 3.
Some errors are handled in the server side code when I am trying to delete a row.
How can I pass this error message to JqGrid?
For example, In the action method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id) {
Project project = dbContext.Projects.Find(id);
dbContext.Projects.Remove(project);
try {
dbContext.SaveChanges();
} catch (DbUpdateException){
// Send the error to JqGrid
}
return RedirectToAction("Index");
}
In JqGrid:
$('#DataTable').
jqGrid('navGrid', '#pager',
{ add: true, del: true, edit: true, search: false },
{ url: Url("Edit", controllerName), closeAfterEdit: true },
{ url: Url("Create", controllerName), closeAfterAdd: true },
{ url: Url("Delete", controllerName) }
);
the method URL simply creates the URL to the action method
A: I found the solution.
Just throw the exception from the catch block and JqGrid will catch it!
I did not expect it though!!!
Like:
try {
dbContext.SaveChanges();
} catch (DbUpdateException){
throw new Exception("Could not delete project.");
}
A: try
{
dbContext.SaveChanges();
return Json(true);
}
catch (DbUpdateException)
{
var json = new { msgkey = "Could not delete project." };
return Json(json);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create readonly viewer for Word, Excel and PDF-documents? We need to set up a page to make some highly confidential documents (PDF, Excel, Word) available for viewing only.
The page/documents needs to be as secure as possible (no save, no print etc). We recon that we can't stop print-screen, but hopefully we can limit most of the other options.
How do you best do this? I have currently only two options that I am considering:
*
*Open the documents inside an IFrame and experiment with javascript and css
*Create a viewer in Silverlight (or Flash)
If any of you have some ideas on how to achieve this, please tell me. It will be much appreciated!
A: Word and Excel don't offer a lot of security. I would convert everything you want secured into a PDF and use something like the PDF viewer referenced in this question: Flash document viewer. It's an open source plugin that will allow you to disable save and print and should go a long way towards deterring users from attempting to copy the documents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generate drop down from non-direct-link database table I got 3 tables in database, FOOD, FOODTYPE and FOODUNIT. FOOD is link with FOODTYPE with foreign key FoodTypeID, while FOODTYPE is in turn link with FOODUNIT with foreign key FoodTypeID as well.
Currently i got my strongly-typed view (FOOD) which display all food data. I got a dropdown for FOODTYPE table like this:
@model IEnumerable<HFMS1.Models.FOOD>
<td id="type@(item.FoodID)" class="dropdown">
@Html.DisplayFor(modelItem => item.FOODTYPE.FoodTypeName)
</td>
I need to generate another drop down for FOODUNIT, but since this table is not directly link with FOOD table, i got no idea how i going to call it, is it i need to pass ViewBag from controller ?
Really no idea about this. hope can get some help here. appreciate that.
A: You need to create a wrapper to use as your model that contains both FOOD and FOODUNIT (unless I'm misunderstanding the question).
So for instance create a class such as the bellow:
public class FoodViewModel
{
public IEnumerable<FOOD> Foods { get; set; }
public IEnumerable<FOODUNIT> FoodUnits { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: emoticons in message on Android I am developing a chat application(like Simple Gtalk) for android mobiles. I am facing few issues in display emoji's/emoticons.
I need to replace the special character to a emojis image. How can i do this?
*
*I select Image from grid.
*Display corresponding special character of image selected into Edit Text along with message i typed.
*When i click on send button i need to display emojis/ emotions instead of special character in the above list view where i display all the messages i receive from .NET web service. These images(emojis) are stored in drawable folder.
*
*I get these messages from web service. But I want to know how can I find and replace the special character with a emojis image along with my text message coming from web service.
A:
I need to replace the special character to a emojis image
You can refer to Emoji Picker.
Display corresponding special character of image selected into Edit Text along with message i typed.
This has already been answered on SO
But i want to know how can i find and replace the special character with a emojis image along with my text message coming from web service.
Check the Unicode chart.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to copy and paste changed some lines in (command mode) in Vim I has such code:
def foo
puts "foo"
end
and as result I need:
def foo
puts "foo"
end
def bar
puts "bar"
end
I would like to perform this in command mode (could you also refer some help?) but other solutions are also welcome.
A: To copy / paster use type : (with you cursor on def foo line)
y3yGP
It will copy the 3 lines at the end of the file. use xG where x is a line number to go at line x. (Use set number to see line number)
Then you can change foo in bar with command :
:x,ys/foo/bar/
With x the first line of the block, and y the last one :)
Hoping that helps you :)
A: Staying in insert mode I do the following (cursor on def foo):
S-vjjjyPgv:s/foo/bar/g
Nice trick for me is using gv to retrive last selection.
A: One can use the following Ex command (assuming that the cursor is
located on the def line).
:,/^end/t//|'[,']s/\<foo\>/bar/g|'[pu!_
To jump to the pairing end line, one can take advantage of the
% command extended by the matchit plugin.
:exe"norm V%y']o\ep"|'[,']s/\<foo\>/bar/g
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Dictionary DataStructure which method d[] or d.get()? While Using Python Dictionary DataStructure (which contains key-value pair) if i want to retrieve some value from my Dictionary i have two options d[''] and g.get('key') so i am confused now which is better and Why ?? I understand both some way but when it comes to memory consumption and evaluation in memory which one is better ??
Hoping for some Positive reply,
Regards.
A: If 'key' does not exist in the dictionary,
d['key']
will throw a KeyError, while
d.get('key')
will return None.
A: From the Python Library Docs
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map.
If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable. [...]
and
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
The difference lies in the return value. When you ask for the value corresponding to a non-existing key, you either want
*
*A KeyError raised
*A callback invoked
*A default value returned
Python provides the different functionalities through multiple methods.
There will be a performance hit using [] when the key is not found, either in calling _missing_ or raising the exception. As to which one is faster when the key IS present, I checked the source code. (I used 2.7.2 for this check.) In dictobject.c we see:
*
*get calls dict_get
*[] calls dict_subscript
Now if the values are present, in dict_get we have
if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
return NULL;
if (!PyString_CheckExact(key) ||
(hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
}
ep = (mp->ma_lookup)(mp, key, hash);
and in dict_subscript we have
assert(mp->ma_table != NULL);
if (!PyString_CheckExact(key) ||
(hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
ep = (mp->ma_lookup)(mp, key, hash);
The only difference is that get does an extra unpack tuple!
Significant? I have no idea. :-)
A: The difference is that if the key is missing, d[key] will raise a KeyError exception, whereas d.get(key) will return None (and d.get(key, default) will return a default value).
There are no noticeable differences in memory requirements.
A: They are different, especially if the key is not present in your dictionary (see here)
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map.
get(key[, default])
Return the value for key if key is in the dictionary, else
default. If default is not given, it defaults to None, so that this
method never raises a KeyError.
A: They both behave the same if the key exists. But if the key is not found d['key'] will raise a KeyError exception, whereas d.get('key') will return None. You can also supply a second argument to the get method which will be returned on a not-found condition: d.get('key', '') will return a null string if the key is not found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How to make checkboxes grey in a cxGrid column In cxGrid I have a column with property Options.Editing:=False; Properties:=CheckBox. So, user can not change state of the checkboxes. But the checkboxes still have custom color and user does't see that he can not edit them.
How do I make checkboxes grey in a cxGrid column, which one can not edit?
A: You can use OnCustomDrawCell event to draw a disabled checkbox.
Check out: http://www.devexpress.com/Support/Center/p/Q253981.aspx
A: You could make an OnCustomDrawCell event on the grid view, with something like:
if not AViewInfo.Item.Options.Editing then
ACanvas.Brush.Color := clGray;
A: Columns that are not editable will not become grey. This goes for all kinds of editors, be they checkboxes, textedits or whatever. The checkbox has a property for NullStyle that can be set to nssGrayedChecked, but this will only be displayed for NULL values.
You have some other options, though. The simplest may be to set the column to not focusable, as well as not editable (Options.Focusing = false). This will perhaps make it easier for your users to understand why they can't change the value. THe second easiest option is to use a custom style that in some way indicates a disabled/noneditable column, for instance by having a grey background color.
A: Use cxStyleRepository
<TcxGridDbColumn>.styles.Content
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to give limit in mongoexport in mongodb I want to take backup of only 100 records from a collection how can i give limit in query -q.
here what i tried giving limit but after giving limit in -q it is not inserting any record.
mongoexport --host localhost --db test --collection foo -q "{"limit":"1"}" > a.json
Please suggest how can i give limit number of record in mongoexport
http://www.mongodb.org/display/DOCS/mongoexport
A: mongoexport supports limit, so simply:
mongoexport --host localhost --db test --collection foo --limit 1 --out a.json
A: For those stuck on an older version of mongo that doesn't have the limit functionality, an alternative could be to run a query with limit that creates a new collection and export from this.
db.createCollection("limitedResults")
db.limitedResults.insert( (db.foo.find().limit(1)).toArray() )
then
mongoexport --host localhost --db test --collection limitedResults --out a.json
A: If you are using a *nix (or cygwin), you could use head -100
mongoexport --host localhost --db test --collection foo | head -100 > a.json
EDIT : as found on the mongodb mailing list, there is a feature request for this : https://jira.mongodb.org/browse/SERVER-2033
EDIT: this answer is more than 4y old. Mongodb has implemented a built-in feature, see other answers below.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: multithreading and reading from one file (perl) Hej sharp minds!
I need your expert guidance in making some choices.
Situation is like this:
1. I have approx. 500 flat files containing from 100 to 50000 records that have to be processed.
2. Each record in the files mentioned above has to be replaced using value from the separate huge file (2-15Gb) containing 100-200 million entries.
So I thought to make the processing using multicores - one file per thread/fork.
Is that a good idea? Since each thread needs to read from same huge file? It's a bit of a problem loading it into memory do to the size? Using file::tie is an option, but is that working with threads/forks?
Need your advise how to proceed.
Thanks
A: Yes, of course, using multiple cores for multi-threaded application is a good idea, because that's what those cores are for. Though it sounds like your problem involves heavy I/O, so, it might be that you will not use that much of CPU anyway.
Also since you are only going to read that big file, tie should work perfectly. I haven't heard of problems with that. But if you are going to search that big file for each record in your smaller files, then I guess it would take you a long time despite of the number of threads you use. If data from big file can be indexed based on some key, then I would advice to put it in some NoSQL databse and access it from your program. That would probably speed up your task even more than using multiple threads/cores.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FileWriter API: use blob to write data i have a blob url like blob:blahblah that points to a file. I want to write the file behind this blob to local filesystem. The writer.write() documentation says it accepts a file object (from input-type-file) and a blob. But it throws a type mismatch error when try this
fileEntry.createWriter(function(writer) {
writer.write(blob); //blob is a var with the value set to the blob url
i know the problem is that the blob does not get accepted but i would like to know how can i store a blob to the filesystem. i created the said blob earlier in the script from input-type-file and stored it's value in a var.
EDIT
Ok so i think i should have given more code in the first place.
first i create a blob url and store it in a var like this
files[i]['blob'] = window.webkitURL.createObjectURL(files[i]);
files is from an input-type-file html tag and i is looped for number of files. you know the gig.
then the variable goes through a number of mediums, first through chrome's message passing api to another page and then from that page to a worker via postMessage and then finally back to the parent page via postMessage again.
on the final page i intend to use it to store the blob's file to local file system via file system api like this..
//loop code
fileSystem.root.getFile(files[i]['name'], {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.write(files[i]['blob']);
});
});
//loop code
but the writer.write throws Uncaught Error: TYPE_MISMATCH_ERR: DOM File Exception 11
i believe this error is because the variable supplied to writer.write is a text and not a blob object from something like createObjectUrl (directly and not after passing through multiple pages/scopes) or not a window.WebKitBlobBuilder. So how can a blob's url be used to store a file?
A: From your edited code snippet and description, it sounds like you're writing the blobURL to the filesystem rather than the File itself (e.g. files[i]['name'] is a URL). Instead, pass around the File object between main page -> other page -> worker -> main page. As of recent (in Chrome at least), your round trip is now possible. File objects can be passed to window.postMessage(), whereas before, the browser serialized the argument into a string.
You 'fashion' a handler/reference to a Blob with createObjectURL(). There's not really a way to go from blobURL back to a Blob. So in short, no need to create createObjectURL(). Just pass around files[i] directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails Active Record Validation condition base class Material < ActiveRecord::Base
belongs_to :material_type
belongs_to :product_review
validates :url, :presence => true, :if => :url_presence?
validates :video, :presence => true, :if => :video_presence?
def url_presence?
if !self.title.blank? and self.material_type.title.eql? :url
true
end
end
def video_presence?
if !self.title.blank? and self.material_type.title.eql? :video
true
end
end
has_attached_file :video,
:url => "/system/video/:id/:attachment/:style/:basename.:extension",
:path => ":rails_root/public/system/video/:id/:attachment/:style/:basename.:extension",
:default_url => "/image/video.png"
end
I assumption if its finds Title fields fill and material_type is url than it perform validation for url field presence validation check, but it not helpful
A: I think you need to compare strings, not symbols.
validates :url, :presence => true, :if => :url_present?
validates :video, :presence => true, :if => :video_present?
def url_present?
self.title.present? and self.material_type.title == "url"
end
def video_present?
self.title.present? and self.material_type.title == "video"
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3.. error in opening zip file I was using maven to build and compile a spring project and here's what I got an error about "error in opening zip file.". I attached the settings.xml here to show that I configured the proxy right and the pom.xml.
[SETTINGS.XML]
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>XXXX</host>
<port>8080</port>
<username>XXXX</username>
<password>XXXXX</password>
<nonProxyHosts>localhost</nonProxyHosts>
</proxy>
[POM.XML]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wrox</groupId>
<artifactId>springfirst</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>springfirst</name>
<url>http://maven.apache.org</url>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<filtering>true</filtering>
</testResource>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring-version>2.0.6</spring-version>
<junit-version>3.8.2</junit-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
[ERROR MESSAGE]
E:\DOCUMENTS\ETC\TUTORIALS\begspringcode_091809\src\chapter1\springfirst>mvn -X compile
Apache Maven 3.0.3 (r1075438; 2011-03-01 01:31:09+0800)
Maven home: C:\maven2.2.1\bin\..
Java version: 1.6.0_15, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_15\jre
Default locale: en_PH, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from C:\maven2.2.1\bin\..\conf\settings.xml
[DEBUG] Reading user settings from C:\Users\AMT\.m2\settings.xml
[DEBUG] Using local repository at C:\Users\AMT\.m2\repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for C:\Users\AMT\.m2\repository
[INFO] Scanning for projects...
[DEBUG] Extension realms for project com.wrox:springfirst:jar:1.0-SNAPSHOT: (none)
[DEBUG] Looking up lifecyle mappings for packaging jar from ClassRealm[plexus.core, parent: null]
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.wrox:springfirst:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 42, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[DEBUG] === REACTOR BUILD PLAN ================================================
[DEBUG] Project: com.wrox:springfirst:jar:1.0-SNAPSHOT
[DEBUG] Tasks: [compile]
[DEBUG] Style: Regular
[DEBUG] =======================================================================
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springfirst 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[DEBUG] Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-pack
age, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]
[DEBUG] Lifecycle clean -> [pre-clean, clean, post-clean]
[DEBUG] Lifecycle site -> [pre-site, site, post-site, site-deploy]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.177s
[INFO] Finished at: Mon Oct 03 14:57:47 SGT 2011
[INFO] Final Memory: 1M/4M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3 (C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar): error in opening zip file -> [Help 1]
org.apache.maven.plugin.PluginDescriptorParsingException: Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3 (C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar): error in opening zip file
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.extractPluginDescriptor(DefaultMavenPluginManager.java:212)
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginDescriptor(DefaultMavenPluginManager.java:147)
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDescriptor(DefaultMavenPluginManager.java:261)
at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor(DefaultBuildPluginManager.java:185)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecution(DefaultLifecycleExecutionPlanCalculator.java:152)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecutions(DefaultLifecycleExecutionPlanCalculator.java:139)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:116)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:129)
at org.apache.maven.lifecycle.internal.BuilderCommon.resolveBuildPlan(BuilderCommon.java:92)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
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.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:114)
at java.util.jar.JarFile.<init>(JarFile.java:133)
at java.util.jar.JarFile.<init>(JarFile.java:112)
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.extractPluginDescriptor(DefaultMavenPluginManager.java:170)
... 25 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginDescriptorParsingException
'cmd' is not recognized as an internal or external command,
operable program or batch file.
E:\DOCUMENTS\ETC\TUTORIALS\begspringcode_091809\src\chapter1\springfirst>
A: Delete C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar or better still C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\ folder and try again.
Evidently, the jar file is incomplete or corrupted.
A: Deleting the repository folder solved the issue.
A: Got the same issue. This worked for me.
Check your maven version
HOME>> mvn -version
3.0.3
I updated this to maven 3.2.1 and change the path in bash_profile. Now check it again.
HOME>> mvn -version
If it is updated, delete the repository and close the terminal. Reopen the terminal and type
Project Path >> mvn clean install
If it not updated, then type following
HOME>> echo $JAVA_HOME
HOME>> which java
/usr/share/java(for e.g.)
HOME>> cd /usr/share/java
HOME>> open .
You will see maven old version contents in it. Replace the contents of this with new version contents.
Then delete the repository.
Project Path>> mvn clean install
Now all your maven jars will be downloaded.
Hope this will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Take screenshot from a view of AVFoundation programmatically I am running a video stream by using AVFoundation class, and I am placing an imageview on that to simulate some thing. So is it possible to take screen shot of the simulation. What's happening by using the earlier specified methods is I am getting only a view and a image view but there is no current video image given out byt the camera, only the image I put is visible in the photo saved into the library.
A: Try this ..... it will be help 4 u , This code will be write when Videos are Running
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
(or)
UIImage *thumbnail;
MPMoviePlayerController *moviePlayer1= [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayer1 play];
thumbnail = [[moviePlayer1 thumbnailImageAtTime:10 timeOption:MPMovieTimeOptionNearestKeyFrame] retain];
[moviePlayer1 stop];
[moviePlayer1 release];
It will give image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the Loop Invariant in the following code What is the Loop Invariant(s) in this sample code.
This is an excerpt code implemented in C programming language:
//pre-condition m,n >= 0
x=m;
y=n;
z=0;
while(x!=0){
if(x%2==0){
x=x/2;
y=2*y;
}
else{
x=x-1;
z=z+y;
}
}//post-condition z=mn
These are my initial answers (Loop Invariant):
*
*y>=n
*x<=m
*z>=0
I am still unsure about this. Thanks.
A: Your answers are indeed invariant but say little about the conditions of your loop. You always have to look for specific invariants. In this case it is quite easy since there are only two (exclusive) operations inside your loop.
The first x' = x/2; y' = 2*y; looks like it is invariant under x*y.
The second x' = x-1; z' = z+y; is not: x'*y' = x*y - y. But if you add z again it will be invariant. z'+x'*y' = z + y + x*y - y = z+x*y.
Fortunately also the first condition is invariant under z+x*y and thus we have found a loop invariant.
*
*pre-condition: z+x*y = m*n
*post-condition: x=0 (loop condition) and therefore we can deduce from our invariant: z = m*n
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Determine the blackberry processor programmatically? I want to determine the processor speed of the blackberry device programmatically.
Based on the processor speed i want to display few things on the app.
Please tell me how do i determine this programmatically.
Thanks
A: There's no way to do that. But you can determine device name and software version and use your own local dictionary with technical specifications of every device model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to dump a certain range of variant into the sheet? I have a variant like these
var = sheet1.Range("A1:P3600").Value
I have done some operarions and pushed the unwanted rows to the top in the variant. Now I have to copy the var variant to the other sheet from a certain range.
sheet1.range("A3444:P" & i).value = var(range(cells(r,"A").cells(l,"P"))
that is say var(350 to end of var) should be copied to the other sheet. Is it possible ? can we do like that ?
A: One way is to dump the reduced array to a second array, then the second array to your range
The code below makes a variant array with 3600 rows by 16 columns (ie A:P), data is dumped into the array for sample data (note you already have this array as Var), then a variable is used as a marker to reduce the array to a second array, the second array is then written to the range.
Updated to match your exact data locations. In your case you have Var1 already (your Var), so you just need the second portion of the code that starts at lngStop = 350 and make my code Var1 references Var
Sub TestME()
Dim Var1
Dim Var2
Dim lngCnt As Long
Dim lngCnt2 As Long
Dim lngCnt3 As Long
Dim lngCnt4 As Long
Dim lngStop As Long
Var1 = Sheet1.Range([a1], [p3600]).Value2
For lngCnt = 1 To UBound(Var1, 1)
For lngCnt2 = 1 To 16
Var1(lngCnt, lngCnt2) = "I am row " & lngCnt & " column " & lngCnt2
Next lngCnt2
Next lngCnt
lngStop = 350
ReDim Var2(1 To UBound(Var1, 1) - lngStop + 1, 1 To UBound(Var1, 2))
For lngCnt3 = lngStop To UBound(Var1, 1)
For lngCnt4 = 1 To UBound(Var1, 2)
Var2(lngCnt3 - lngStop + 1, lngCnt4) = Var1(lngCnt3, lngCnt4)
Next lngCnt4
Next lngCnt3
Sheet1.[a3444].Resize(UBound(Var2, 1), UBound(Var2, 2)).Value2 = Var2
End Sub
A: You can slap only a portion of your array onto the sheet, but only if that portion is at the top left of your array, i.e. only the first n columns and the first m rows. There is no straightforward way of slapping the the last n columns and the last m rows. In this case, you have to resort to transferring stuff to a second, smaller array, and then dump that onto the sheet, as in @brettdj's answer -- this works fine, but it's a bit roundabout and too much coding for my taste.
Instead, if you could push your "unwanted rows" down to the bottom of your array, then it would be a one-liner to slap the top rows of that array onto a sheet (omitting the last 350).
Here's an example where a 4 x 3 array is read in, and only the top-left 3 x 2 is slapped back onto the sheet. The secret is to make the target range smaller than the entire array.
Dim v
v = Range("A2:C5")
Range("E2:F4") = v
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Data Hog Notification I just like to ask how can you know that a certain application is using too much network? I wanted to create an android application that can notify the user if it is hogging your data. Thanks!
A: Yes, NetCounter has done something similar.
The data usage rates are polled using
// Reads the values.
long rx = SysClassNet.getRxBytes(inter);
long tx = SysClassNet.getTxBytes(inter);
I guess your service will keep a check on the running applications and the data tranfer rates.
Oh and NetCounter is GPLv3 license
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tomcat : Bypass basic Authentication for Specified IP Address I have configured tomcat for basic authentication.
I do not want anyone to have access to my web application but the app is serving web services.
So I want to bypass a specific ip address from basic authentication.( that ip should not require authentication.)
tomcat-users.xml :
<tomcat-users>
<user username="user" password="password" roles="user"/>
</tomcat-users>
web.xml :
<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>You must enter your login credentials to continue</realm-name>
</login-config>
<security-role>
<description>
The role that is required to log in to the Application
</description>
<role-name>user</role-name>
</security-role>
Thanks,
Chetan.
A: If you would like to allow just only a few IP addresses and disallow everybody else the Remote Address Filter Valve is what you need.
If you want that the clients from unknown IP addresses see the basic login dialog and could login you need a custom Valve. The source of the RemoteAddrValve (and it's parent class RequestFilterValve is a good starting point. Take a look my former answer too.
Anyway, below is a proof of concept code. It puts a filled Principal to the Request if the client is coming from a trusted IP so the login module will not ask for the password. Otherwise it does not touch the Request object and the user can log in as usual.
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.valves.ValveBase;
public class AutoLoginValve extends ValveBase {
private String trustedIpAddress;
public AutoLoginValve() {
}
@Override
public void invoke(final Request request, final Response response)
throws IOException, ServletException {
final String remoteAddr = request.getRemoteAddr();
final boolean isTrustedIp = remoteAddr.equals(trustedIpAddress);
System.out.println("remoteAddr: " + remoteAddr + ", trusted ip: "
+ trustedIpAddress + ", isTrustedIp: " + isTrustedIp);
if (isTrustedIp) {
final String username = "myTrusedUser";
final String credentials = "credentials";
final List<String> roles = new ArrayList<String>();
roles.add("user");
roles.add("admin");
final Principal principal = new GenericPrincipal(username,
credentials, roles);
request.setUserPrincipal(principal);
}
getNext().invoke(request, response);
}
public void setTrustedIpAddress(final String trustedIpAddress) {
System.out.println("setTrusedIpAddress " + trustedIpAddress);
this.trustedIpAddress = trustedIpAddress;
}
}
And a config example for the server.xml:
<Valve className="autologinvalve.AutoLoginValve"
trustedIpAddress="127.0.0.1" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android image view gravity How can I dynamically set the gravity ?
Bitmap bmp;
im = new ImageView (this);
bmp=getbmp(img);
im.setImageBitmap(bmp);
Now I would like to put the image in the top . Ho can I do this without android:gravity in main.xml ?
EDIT :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:scrollbars="vertical"
>
</ScrollView>
I have a frame layout and I add to it the image , and then the text and I would like the image to be on the top of the screen.
FrameLayout fm = new FrameLayout (this);
fm.addView(im);
fm.addView(fin); // fin = the text view
setContentView(fm);
A: Use ImageView.setScaleType() with ImageView.ScaleType.FIT_START as value.
A: You can put ImageView inside a LinearLayout and the use setLayoutParams of the LinearLayout to set gravity of the layout.
A: You can try this code if may be help you
xml file
<GridView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/gallerylistactivity_gallery"
android:columnWidth="90dp" android:numColumns="4"
android:verticalSpacing="5dp" android:horizontalSpacing="10dp"
android:gravity="center" android:stretchMode="spacingWidth"/>
.java file
public class GalleryListAdapter extends BaseAdapter{
private Context mContext;
private Integer[] mImageIds = { R.drawable.gallery_01,
R.drawable.gallery_02, R.drawable.gallery_03,
R.drawable.gallery_04, R.drawable.gallery_05,
R.drawable.gallery_06, R.drawable.gallery_07,
R.drawable.gallery_08, R.drawable.gallery_10,
R.drawable.gallery_09 };
public GalleryListAdapter(Context c) {
this.mContext = c;
}
@Override
public int getCount() {
return mImageIds.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
return imageView;
}
A: See "http://developer.android.com/reference/android/widget/ImageView.ScaleType.html".
A: Try this:
Bitmap bmp;
ImageView img= new ImageView (this);
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.icon);
img.setImageBitmap(bmp);
img.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL));
mLinearLayout.addView(img);
Please note that you need to set width and height of imageview in FrameLayout.LayoutParams(width,height,gravity) according to what gravity you want to set.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Getting and ordering rows with value greater than zero then rows with value zero I have a table like this
id title display_order
1 t1 3
2 t2 1
3 t3 5
4 t4 4
5 t5 2
6 t6 0
7 t7 7
8 t8 6
9 t9 0
10 t10 0
What I need is to have results like this
id title display_order
2 t2 1
5 t5 2
1 t1 3
4 t4 4
3 t3 5
8 t8 6
7 t7 7
...order of the rest is not important but should be in the result
6 t6 0
9 t9 0
10 t10 0
I can get this result with two SQL queries and then combine them.
Is there a way to do this with one SQL?
Thanks
A: Try the below one-
SELECT * FROM table_name
ORDER BY IF (display_order = 0, 9999999, display_order)
A: SELECT *
FROM atable
ORDER BY
display_order = 0,
display_order
When display_order is 0, the first sorting term, display_order = 0, evaluates to True, otherwise it evaluates to False. True sorts after False – so, the first sorting criterion makes sure that rows with the display_order of 0 are sorted at the end of the list.
The second ORDER BY term, display_order, additionally specifies the order for rows with the non-zero order values.
Thus, the two criteria give you the desired sorting order.
A: Here is the solution in T-SQL in case anyone needs it
SELECT * FROM Table ORDER BY CASE WHEN display_order = 0 THEN display_order END ASC,CASE WHEN display_order > 0 THEN display_order END ASC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Part of the screen disabled in landscape mode on view-based iPad app I am developing an iPad application with view-based template in landscape mode as it has to share a toolbar to all its views and provide the functionality similar to tabbar.
The problem is that any control added to a portion of the screen on the right side is disabled. For example, if a button is added, the part of it on that portion of the screen doesn't work.
Surprisingly, the width of that portion of the screen is equal to the width of the screen in landscape subtracted by the width of the screen in portrait so I think the problem has something to do with that.
Thanks in advance
A: I'm betting those controls are outside the bounds of their superview (or the superview's superview, or the super-super-superview, or…). When the view hierarchy does a hit test, it returns nil if the point is outside its frame, so subviews outside the frame can't be hit. Note that views in IB don't have the "clips subviews" option on by default, so it's hard to tell where the view bounds are. Also check the autoresize settings on those views--if one of the containing views isn't set to resize horizontally and it's sized to portrait width in the nib, it won't expand to landscape width when you rotate the device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Proper way to put a String into a List in java|groovy I have a code which executes a command in Linux box (ls - latr /home/ars | awk '{if(NR>1)print}') which gives me list of directories along with its information. How do I put it into some array or list so that depending on each line I can get filename, permissions etc from the (list or array)!!
Here is my code which prints an output at the bottom of my question
here cmd=ls - latr /home/ars | awk '{if(NR>1)print}'
function calling
HashMap<String,String> params = IntermediateResults.get("userparams")
Map env=AppContext.get(AppCtxProperties.environmentVariables)
def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )
String cmd="ls -latr "+rrs.get("linkpath")+" | awk '{if(NR>1)print}'"
String res=fClass.newInstance().fetchInformation( params, env, cmd )
my function called
public String fetchInformation( Map<String,String> params, Map env, String cmd )
{
try
{
Process proc = Runtime.getRuntime().exec(cmd);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
result.append(line);
println "$line" // This output is given at the end
}
int exitVal = proc.waitFor();
}
catch (IOException io)
{
io.printStackTrace();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
//println("\n\n"+result)
return result
}
my output
/data/u01/app/oracle/10.2.0/db_1:
total 260
-rwxr-xr-x 1 oracle dba 0 Jun 7 2005 root.sh.old
drwxr-xr-x 4 oracle dba 4096 Jan 17 2007 xdk
drwxr-xr-x 4 oracle dba 4096 Jan 17 2007 uix
drwxr-xr-x 3 oracle dba 4096 Jan 17 2007 tg4tera
drwxr-xr-x 3 oracle dba 4096 Jan 17 2007 tg4sybs
drwxr-xr-x 3 oracle dba 4096 Jan 17 2007 tg4ingr
drwxr-xr-x 3 oracle dba 4096 Jan 17 2007 tg4ifmx
So how can I put the above output in some List so that on each line I can get permissions, hardlink,owner, group,filesize,month, date, time, year and finally filename?
Update
This is what I am trying to do, is there a better way may be by using maps?
List<List<String>> frows = new ArrayList<List<String>>()
while ((line = br.readLine()) != null)
{
List<String> fileList= new ArrayList<String>()
result.append(line);
String[] strs = line.split(" ")
for(item in strs)
{
//print "$item "
fileList.add(item)
}
frows.add(fileList)
}
for (List<String> l : frows)
{
for (String s : l) {
print "$s"
}
println ""
}
A: You shouldn't use the system dependent ls-command, and parse it's error prone output. Consider a filename "foo\n
drwxr-xr-x 4 oracle dba 4096 Jan 17 2007 uix" for example.
Use java.io.File instead, read the directory, get File objects with names, time attributes.
You use a list like this:
List <File> result = new List<File> ();
// and in the loop:
result.add (file);
A: Create a class say FileDetail with properties permissions, hardlink,owner, group,filesize,month, date, time, year and filename. Inside your method
List<FileDetail> fileDetails = new ArrayList<FileDetail>();
while ((line = br.readLine()) != null)
{
FileDetail file = new FileDetail();
println "$line" // This output is given at the end
// parse - use space delimiter and String.split() API
String[] strs = line.split(" ");
// set values to "file"
// add to list
fileDetails .add(file);
}
return fileDetails;
Using Map,
List<Map<String, String>> files = new ArrayList<Map<String, String>>()
while ((line = br.readLine()) != null) {
Map<String, String> file = new Map<String, String>()
String[] strs = line.split(" ")
// Find the order of fields, but it is system dependent, may not work in futrue
file.add("PERMISSIONS", strs[0]); // and so on for next and you may need to trim map value
files.add(file);
println "$line"
}
return files;
A: An alternative would be to use JNA to access the native stat call for your platform...
This works for me under OS X. I saved it as stattest.groovy, and when executed by groovy stattest.groovy, it prints out the details about itself:
@Grab( 'net.java.dev.jna:jna:3.3.0')
@Grab( 'org.jruby.ext.posix:jna-posix:1.0.3' )
import org.jruby.ext.posix.*
File f = new File( 'stattest.groovy' )
POSIX posix = POSIXFactory.getPOSIX( [ isVerbose:{ false } ] as POSIXHandler , true)
FileStat s = posix.stat( f.absolutePath )
s.properties.each { name, val ->
println "$name: $val"
}
[ 'atime', 'blocks', 'blockSize', 'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime', 'nlink', 'rdev', 'st_size', 'uid' ].each {
println "$it() -> ${s."$it"()}"
}
prints out:
13:23:46 [tyates@mac] JNA $ groovy stattest.groovy
symlink: false
file: true
setuid: false
byteBuffer: java.nio.HeapByteBuffer[pos=0 lim=120 cap=120]
executableReal: false
structSize: 120
namedPipe: false
empty: false
blockDev: false
executable: false
fifo: false
class: class org.jruby.ext.posix.MacOSHeapFileStat
setgid: false
sticky: false
charDev: false
owned: true
directory: false
ROwned: true
readableReal: true
writableReal: true
readable: true
writable: true
groupOwned: false
socket: false
atime() -> 1317644640
blocks() -> 8
blockSize() -> 4096
ctime() -> 1317644636
dev() -> 234881026
gid() -> 1255
ino() -> 62213399
mode() -> 33204
mtime() -> 1317644636
nlink() -> 1
rdev() -> 0
st_size() -> 527
uid() -> 1114
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: adding datetime on video while video recording in iPhone i am new in iPhone sdk. I want to develop a project in which i need to record current date and time along while i am recording video. i am not getting how to do that. please help me out here.
please provide a sample if possible.
Thank You
A: NSDate datewill return a NSDate object with the current date and
time. Sample code to find the current date and time is as follows
NSDate *testDate=[NSDate date];
NSDateFormatter *formatterNew = [[NSDateFormatter alloc] init]; [formatterNew setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
NSString *dt = [formatterNewstringFromDate:testDate];
NSString *strDateTaken=dt;
NSLog(@"date=%@",strDateTaken);
[formatterNew release];
and you can easily save this date in NSUserDefault for later retrival
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: defining a method inside a class in python I'm taking my first steps in python programming, I have a class named node which holds a list of nodes (I think that legal) named sons. I tried to create a function that returns the length of the list but it fails. Here is my code:
class node:
name="temp"
ID=-1
abstract="a short description"
text="the full description"
sons=[]
def sLen(none):
print ("hello")
return len(self.sons)
and here is the error:
NameError: global name 'self' is not defined
if I try to remove the self:
NameError: global name 'self' is not defined
Clearly I have misunderstood something, but what?
A: class node:
name="temp"
ID=-1
abstract="a short description"
text="the full description"
sons=[]
def sLen(self): # here
print ("hello")
return len(self.sons)
n = node()
n.sons = [1, 2, 3]
print n.sLen()
A: The first argument of a class method is always a reference to "self".
Possibly you will find interesting answers here too: What is the purpose of self?.
Quoting the most important bit:
Python decided to do methods in a way that makes the instance to which
the method belongs be passed automatically, but not received
automatically: the first parameter of methods is the instance the
method is called on.
If you look for a more thorough discussion about classes definition in python, of course the official documentation is the place to start from: http://docs.python.org/tutorial/classes.html.
A: You called the first argument to the method none, not self.
return len(none.sons)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Joining results of two different aggregate functions on the same table I'm trying to combine two queries in order to determine which aircraft will be at a particular point (point ABCD) just before a particular time (2011-09-19 04:00:00.000). So far, I generate the last time an aircraft arrived at this point, and the last time an aircraft departed the point. My current idea is that if the last time it arrived is greater then the last time it departed the aircraft is still at point ABCD just before the specified time.
The first query finds the last time an aircraft arrived at a certain point:
select aircraft_id, MAX(arrival_datetime) as last_arrival
from flight_schedule
where arrival_datetime < '2011-09-19 04:00:00.000' and arrival_point='ABCD'
group by aircraft_id
and the second query finds the last time an aircraft has left this point:
select aircraft_id, MAX(departure_datetime) as last_departure
from flight_schedule
where departure_datetime < '2011-09-19 04:00:00.000' and departure_point='ABCD'
group by aircraft_id
Both of these queries generate the appropriate responses. I realise that in order to compare the last_departure to the last_arrival fields I need to join the tables somehow.
I'm not an SQL whiz, and in the past any table joins I've done have been between two completely different tables and haven't involved any aggregate functions so my normal subqueries and structure hasn't worked.
A: The easiest solution would be to
*
*turn each statement into a subquery
*join the results together
SQL Statement
select la.aircraft_id, la.last_arrival, ld.last_departure
from (
select aircraft_id, MAX(arrival_datetime) as last_arrival
from flight_schedule
where arrival_datetime < '2011-09-19 04:00:00.000' and arrival_point='ABCD'
group by aircraft_id
) la
full outer join (
select aircraft_id, MAX(departure_datetime) as last_departure
from flight_schedule
where departure_datetime < '2011-09-19 04:00:00.000' and departure_point='ABCD'
group by aircraft_id
) ld on ld.aircraft_id = la.aircraft_id
Note that I've used a full outer join. Most likely an inner join would suffice. The full outer join is only needed if there's ever an arival_datetime without a departure_datetime or vice versa (wich is unlikely to happen).
A: Try like this way :
select dpt.aircraft_id, last_arrival, last_departure
from
(
select aircraft_id, MAX(arrival_datetime) as last_arrival
from flight_schedule
where arrival_datetime < '2011-09-19 04:00:00.000' and arrival_point='ABCD'
group by aircraft_id
) dpt
inner join
(
select aircraft_id, MAX(departure_datetime) as last_departure
from flight_schedule
where departure_datetime < '2011-09-19 04:00:00.000' and departure_point='ABCD'
group by aircraft_id
) arr on dpt.aircraft_id = arr.aircraft_id
A: The following solution uses standard SQL and should work in most, if not all, the major RDBMSes:
SELECT
aircraft_id,
CASE
WHEN MAX(CASE arrival_point WHEN 'ABCD' THEN arrival_datetime END) >
MAX(CASE departure_point WHEN 'ABCD' THEN departure_datetime END)
THEN 'At the point'
ELSE 'Somwhere else'
END AS is_located
FROM flight_schedule
WHERE arrival_datetime < '2011-09-19 04:00:00.000' AND arrival_point = 'ABCD'
OR departure_datetime < '2011-09-19 04:00:00.000' AND departure_point = 'ABCD'
GROUP BY
aircraft_id
If your particular RDBMS supports CTEs and ranking functions, you could also try a different approach:
WITH events AS (
SELECT
aircraft_id,
arrival_datetime AS event_datetime,
'At the point' AS is_located
FROM flight_schedule
WHERE arrival_datetime < '2011-09-19 04:00:00.000'
AND arrival_point = 'ABCD'
UNION ALL
SELECT
aircraft_id,
departure_datetime AS event_datetime,
'Somewhere else' AS is_located
FROM flight_schedule
WHERE departure_datetime < '2011-09-19 04:00:00.000'
AND departure_point = 'ABCD'
),
ranked AS (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY aircraft_id
ORDER BY event_datetime DESC
) AS event_rank
FROM events
)
SELECT
aircraft_id,
is_located
FROM ranked
WHERE event_rank = 1
A: Thank you so much. I have worked 10 hours spanning two days to get this to work.
In summary, a primary query wraps around any number of sub queries and by naming the sub queries with aliases, you can push data from the sub queries to the main query:
SELECT N.Name_CO_ID, N.Name_Company, N.District_Count, D.DistrictName, D.District_Response
FROM (
SELECT Name_CO_ID, Name_Company, COUNT(dbo.SV_Name.Name_CO_ID) AS 'District_Count'
FROM SV_Name
JOIN dbo.SV_Activity ON dbo.SV_Name.Name_ID = dbo.SV_Activity.Activity_ID
JOIN dbo.SV_Product ON dbo.SV_Activity.Activity_PRODUCT_CODE = dbo.SV_Product.Product_PRODUCT_CODE
AND (dbo.SV_Activity.Activity_ACTIVITY_TYPE = 'COMMITTEE')
AND (dbo.SV_Product.Product_GROUP_3 = 'DIST')
AND (dbo.SV_Activity.Activity_THRU_DATE > GETDATE())
AND (dbo.SV_Name.Name_CO_MEMBER_TYPE = 'LSD')
GROUP BY Name_CO_ID, Name_Company) N
FULL OUTER JOIN (SELECT DistrictName, COUNT(DistrictName)AS 'District_Response'
FROM ODS_Landing
WHERE (StartDate > @StartDate1) AND (StartDate < @StartDate2)
GROUP BY DistrictName) D ON N.Name_COMPANY = D.DistrictName
WHERE District_Response > 0
ORDER BY Name_Company
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android - creating word document I want to create word(.doc) and excel(.xls) files on the android platform.
For excel I am able to use jexel jar, but I am unable to find any API for word files.
Can you tell me if there are any opensource/free API for writing word files on the android platform?
People have suggested Apache-POI but I am not able to implement it in android. Please let me know if Apache-POI really works on android or not.
A: Look at this thread, its java generally but it should also work on android platform What's a good Java API for creating Word documents?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Remove an element from a vector by value - C++ If I have
vector<T> list
Where each element in the list is unique, what's the easiest way of deleting an element provided that I don't know if it's in the list or not? I don't know the index of the element and I don't care if it's not on the list.
A: You could use the Erase-remove idiom for std::vector
Quote:
std::vector<int> v;
// fill it up somehow
v.erase(std::remove(v.begin(), v.end(), 99), v.end());
// really remove all elements with value 99
Or, if you're sure, that it is unique, just iterate through the vector and erase the found element. Something like:
for( std::vector<T>::iterator iter = v.begin(); iter != v.end(); ++iter )
{
if( *iter == VALUE )
{
v.erase( iter );
break;
}
}
A: Based on Kiril's answer, you can use this function in your code :
template<typename T>
inline void remove(vector<T> & v, const T & item)
{
v.erase(std::remove(v.begin(), v.end(), item), v.end());
}
And use it like this
remove(myVector, anItem);
A: If occurrences are unique, then you should be using std::set<T>, not std::vector<T>.
This has the added benefit of an erase member function, which does what you want.
See how using the correct container for the job provides you with more expressive tools?
#include <set>
#include <iostream>
int main()
{
std::set<int> notAList{1,2,3,4,5};
for (auto el : notAList)
std::cout << el << ' ';
std::cout << '\n';
notAList.erase(4);
for (auto el : notAList)
std::cout << el << ' ';
std::cout << '\n';
}
// 1 2 3 4 5
// 1 2 3 5
Live demo
A: From c++20
//LIKE YOU MENTIONED EACH ELEMENT IS UNIQUE
std::vector<int> v = { 2,4,6,8,10 };
//C++20 UNIFORM ERASE FUNCTION (REMOVE_ERASE IDIOM IN ONE FUNCTION)
std::erase(v, 8); //REMOVES 8 FROM VECTOR
Now try
std::erase(v, 12);
Nothing will happen, the vector remains intact.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How can I implement CBC-MAC with DES? I should implement a MAC-CBC generation method in C# with some information about the cryptography algorithm. Here's what I have:
*
*I should use DES.
*The key is byte[] {11, 11, 11, 11, 11, 11, 11, 11}
*The data (16 bytes) should be encrypted in 8-byte parts. First 8 bytes is encrypted using Instance Vector = new byte[8] (8 bytes with 0 value). (CBC?)
*that last 8 bytes of the encrypted value should be converted to Hex string. this is the result I should send.
With this information, I have implemented the following method:
public static string Encrypt(byte[] data)
{
var IV = new byte[8];
var key = new byte[] { 11, 11, 11, 11, 11, 11, 11, 11 };
var result = new byte[16];
// Create DES and encrypt.
var des = DES.Create();
des.Key = key;
des.IV = IV;
des.Padding = PaddingMode.None;
des.Mode = CipherMode.CBC;
ICryptoTransform cryptoTransform = des.CreateEncryptor(key, IV);
cryptoTransform.TransformBlock(data, 0, 16, result, 0);
// Get the last eight bytes of the encrypted data.
var lastEightBytes = new byte[8];
Array.Copy(result, 8, lastEightBytes, 0, 8);
// Convert to hex.
var hexResult = string.Empty;
foreach (byte ascii in lastEightBytes)
{
int n = (int)ascii;
hexResult += n.ToString("X").PadLeft(2, '0');
}
return hexResult;
}
The sample raw data they have provided me is: input=byte[] {0, 6, 4, 1, 6, 4, 1, 7, E, E, F, F, F, F, B, B) which should return the output of value: A7CBFB3C730B059C. This means the last eight bytes of encrypted data should be: byte[] {167, 203, 251, 60, 115, 11, 05, 156}.
But unfortunately using the above method, I get: 32D91200D0007632. meaning my encrypted data is not correct. (the last eight byte of my method's generated encrypted value is byte[] {50, 207, 18, 0, 208, 0, 118, 50}).
Is there any way that I can find out what I should do to get to A7CB...? Am I doing something wrong?
A: CBC-MAC requires a zero Initialisation Vector. Much better to specify the IV explicitly:
var IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
You say your key is byte[] { 11, 11, 11, 11, 11, 11, 11, 11 } are those bytes in hex or in base 10? You might want to try:
var key = new byte[] { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
and see if that works better.
A: The Mono project has a generic MAC-CBC implementation that should work on any SymmetricAlgorithm - even if it's used, internally, only to implement MACTripleDES.
You can find the MIT.X11 licensed source code here. Use it as-is or compare it to your own code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fill ImageAdapter with Int[] What I've Done
I have created a GridView in my layout. This GridView I'd like to fill over my ImageAdapter I've created of the Google Documentations: Hello GridView
The picturepath to my pictures, did i save into my datbase and I'd like to fill it over it. Because in my Datbase everything is a String I wrote in my Activity a short function which changes the String[] into a Int[], but I can't acces that over my ImageAdapter. Afterwards I applied the changes that Mrs. Nikita told me. Also I changed to lil thing to change the String[] to an int[] (is working now).
Question
What do I need to change to get the Int[] to my ImageAdapter that it imports my pictures and that they are shown in the GrindView.
Now I have a Nullpointer Exception at:
public int getCount() {
return mThumbIds.length;
}
The Code:
This is the Code of my SmileyConfigActivity.java:
package de.retowaelchli.filterit;
import de.retowaelchli.filterit.database.SmileyDBAdapter;
import de.retowaelchli.filterit.stats.ImageAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
public class SFilterConfigActivity extends Activity {
//Variablen deklarieren
private String name;
private String keyword;
private Integer[] info;
private SmileyDBAdapter SmileyHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sfilter_config);
SmileyHelper = new SmileyDBAdapter(this);
getImages();
}
public Integer[] getImages(){
SmileyHelper.open();
Cursor c = SmileyHelper.getAllSmileys();
startManagingCursor(c);
String[] picture = new String[] { SmileyDBAdapter.INFO };
int i;
for (i=0;i< picture.length-1;i++) {
info[i]=Integer.parseInt(picture[i+1]);
}
SmileyHelper.close();
//Hier wird die Grindview gefüllt
GridView gridview = (GridView) findViewById(R.id.SmileyGrind);
gridview.setAdapter(new ImageAdapter(this, info));
return info;
}
public void onClickSConfigSave(View v){
EditText edtTextName = (EditText)findViewById(R.id.SFConfigName);
EditText edtTextKeyword = (EditText)findViewById(R.id.SFConfigKeyword);
name = edtTextName.getText().toString();
keyword = edtTextKeyword.getText().toString();
final Intent i = new Intent(this, SmileyActivity.class);
startActivity(i);
}
}
This is the Code of my ImageAdapter.java:
package de.retowaelchli.filterit.stats;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import de.retowaelchli.filterit.SFilterConfigActivity;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c, Integer[] imageIds) {
mContext = c;
mThumbIds = imageIds;
}
//This Guy down here is giving me the NullpointerExcpetion now
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds;
}
And this is how i store the pictures to the Datbase (I only save to place where they are located):
int drawableID = context.getResources().getIdentifier("angel", "drawable", getPackageName());
iv.setImageResource(drawableID);
String info = String.valueOf(drawableID);
mDbHelper.open();
mDbHelper.createSmiley("You have received a heavenly message", info);
mDbHelper.close();
This is the Error-Log I get:
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): FATAL EXCEPTION: main
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.retowaelchli.filterit/de.retowaelchli.filterit.SFilterConfigActivity}: java.lang.NullPointerException
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.os.Looper.loop(Looper.java:143)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread.main(ActivityThread.java:4196)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at java.lang.reflect.Method.invokeNative(Native Method)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at java.lang.reflect.Method.invoke(Method.java:507)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at dalvik.system.NativeStart.main(Native Method)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): Caused by: java.lang.NullPointerException
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at de.retowaelchli.filterit.stats.ImageAdapter.getCount(ImageAdapter.java:25)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.widget.GridView.setAdapter(GridView.java:131)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at de.retowaelchli.filterit.SFilterConfigActivity.getImages(SFilterConfigActivity.java:54)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at de.retowaelchli.filterit.SFilterConfigActivity.onCreate(SFilterConfigActivity.java:30)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)
10-04 13:26:25.776: ERROR/AndroidRuntime(10099): ... 11 more
Thx for your help!
A: Try create constructor in ImageAdapter
public ImageAdapter(Context c, Integer[] imageIds) {
mContext = c;
mThumbIds = imageIds;
}
And in getImagesMethod replace
gridview.setAdapter(new ImageAdapter(this));
with
gridview.setAdapter(new ImageAdapter(this, info));
A: There seems to be a lot of pertinent info missing here but if you fill in the blanks I will update the answer. First problem is what are you retrieving in your getAllSmileys function?
What you need to understand is that a cursor is like a memory table of results. So you need to tell the cursor which record to fetch from by using move commands otherwise it is uniniitilaized. So assuming your smilleys are stored in the SmileyDBAdapter.INFO column then you can retrieve them like this:
SmileyHelper.open();
Cursor c = SmileyHelper.getAllSmileys();
if(c!=null)
{
int i=0;
info = new int[c.getCount()]();
//get the column index
int infoIndex = c.getColumnIndex(SmileyDBAdapter.INFO);
while(c.moveToNext()){
String infoItem = c.getString(infoIndex );
int infoItemInteger = Integer.parseInt(infoItem);
info[i++] =infoItemInteger;
}
}
c.close();
SmileyHelper.close();
You are storing the image id's in the database as string which is making things more complicated. There is no need to parse and valueOf the drawable resource ID's into and out of a text column in the database. Simply change the column type to integer and always work with integers for your images.
You can simply use Cursor.getInt() to retrieve the values.
A: I was trying this out and found this solution. The only one which worked.
public Integer[] getImages(){
SmileyHelper.open();
Cursor c = SmileyHelper.getAllSmileys();
ArrayList<Integer> infoList = new ArrayList<Integer>();
c.getColumnIndex(SmileyDBAdapter.INFO);
int ColumnIndex = c.getColumnIndex(SmileyDBAdapter.INFO);
if(c!=null)
{
while(c.moveToNext()){
String infoItem = c.getString( ColumnIndex );
infoList.add(Integer.parseInt(infoItem));
}
}
info = infoList.toArray(new Integer[]{});
c.close();
SmileyHelper.close();
//Hier wird die Grindview gefüllt
GridView gridview = (GridView) findViewById(R.id.SmileyGrind);
gridview.setAdapter(new ImageAdapter(this, info));
return info;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: parsing for xml values I have a simple xml string defined in the following way in a c code:
char xmlstr[] = "<root><str1>Welcome</str1><str2>to</str2><str3>wonderland</str3></root>";
I want to parse the xmlstr to fetch all the values assigned to str1,str2,str3 tags.
I am using libxml2 library. As I am less experienced in xml handling, I unable get the values of the required tags. I tried some sources from net, but I am ending wrong outputs.
A: Using the libxml2 library parsing your string would look something like this:
char xmlstr[] = ...;
char *str1, *str2, *str3;
xmlDocPtr doc = xmlReadDoc(BAD_CAST xmlstr, "http://someurl", NULL, 0);
xmlNodePtr root, child;
if(!doc)
{ /* error */ }
root = xmlDocGetRootElement(doc);
now that we have parsed a DOM structure out of your xml string, we can extract the values by iterating over all child values of your root tag:
for(child = root->children; child != NULL; child = child->next)
{
if(xmlStrcmp(child->name, BAD_CAST "str1") == 0)
{
str1 = (char *)xmlNodeGetContent(child);
}
/* repeat for str2 and str3 */
...
}
A: I usual do xml parsing using minixml library
u hope this will help you
http://www.minixml.org/documentation.php/basics.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: why is my apache / php is not running under the right user i used
echo exec("whoami");
and i got
authority\system
and in my httpd.conf
it says
User daemon
Group daemon
why is it not running on the right user ?
also i checked and created the user and restarted apache but still it's running under system
A: User and Group are ignored on non-POSIX systems. You need to modify the relevant service entry instead under Windows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Center jQuery info alert How can I center the text and icon in the standard jQuery info alert?
http://jsfiddle.net/3kHWa/
Thank you!
A: I have looked at the snippet and have it centered with this snippet http://jsfiddle.net/3kHWa/2/
<div class="ui-widget">
<div class="ui-state-highlight ui-corner-all" style="padding: 0pt 0.7em;">
<div style="width:auto;margin:0 auto;display:table;">
<span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"></span>
any size text</div>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FTP Connection Error 550 I can able see the root directory of the server unable to create folder and files. I am getting FTP error 550
A: FTP error 500 means invalid port, are you sure that you are using the right ports? Normally, it should be 21, sometimes 20... never heard of something else but it should be possible :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can find header controls in gridview? In a web application, how can I find the controls in header, and how can I bind the value dynamically to those controls? This is what my gridview looks like...
----------------------------------------------
| October | November |
product| | |
| self | Officer | self | officer|
----------------------------------------------
This is my gridview header. All are labels, now I want to find the label (october, noverber, self, officer..) how can I bind the data to them dynamically?
I have following code in gridview rowdatabound event.
foreach (GridViewRow gr in grdProducts.Rows)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Label lM = (Label)gr.FindControl("lblMon1");
lM.Text = month1 + "-" + year1;
lM = (Label)gr.FindControl("lblMon2");
lM.Text = month2 + "-" + year2;
lM = (Label)gr.FindControl("lblMon3");
lM.Text = month3 + "-" + year3;
}
}
A: You can find it with below code snippet....
protected void gridview__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Label lblOctober = (Label)GridView1.FindControl("NameOflabelOctober");
lblOctober.Text = "What Ever you want to give value here(Same thing you can do for rest of four control.... ".
}
}
A: Check out this example.... @Surya sasidhar
In Aspx page.. I added below gridview
<asp:GridView ID="grvGrid" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" OnRowDataBound="grvGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblMon1" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblblbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
At code behind page, I added below code.....
protected void Page_Load(object sender, EventArgs e)
{
GetTable();
grvGrid.DataSource = dstable;
grvGrid.DataBind();
}
protected void grvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Label lblnothing = (Label)e.Row.FindControl("lblMon1");
lblnothing.Text = "November";
}
}
private void GetTable()
{
dstable.Columns.Add("CustomerID", typeof(int));
dstable.Columns.Add("CompanyName", typeof(string));
//
// Here we add five DataRows.
//
dstable.Rows.Add(25, "Indocin");
dstable.Rows.Add(50, "Enebrel");
dstable.Rows.Add(10, "Hydralazine");
dstable.Rows.Add(21, "Combivent");
dstable.Rows.Add(100, "Dilantin");
}
Here is the result....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sort vector of struct element i am trying to sort vector of struct's elements,but i can't construct vector itself here is code
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct student_t{
string name;
int age,score;
} ;
bool compare(student_t const &lhs,student_t const &rhs){
if (lhs.name<rhs.name)
return true;
else if (rhs.name<lhs.name)
return false;
else
if (lhs.age<rhs.age)
return true;
else if (rhs.age<lhs.age)
return false;
return lhs.score<rhs.score;
}
int main(){
struct student_t st[10];
return 0;
}
when i declared vector<student_t>st i can't access element of struct,please give me hint how to do it
A: std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(student_t());
std::sort(st.begin(), st.end(), &compare);
You could also use this vector constructor instead of lines 1-2:
std::vector<student_t> st (10 /*, student_t() */);
Edit:
If you want to enter 10 students with the keyboard you can write a function that constructs a student:
struct student_t &enter_student()
{
student_t s;
std::cout << "Enter name" << std::endl;
std::cin >> s.name;
std::cout << "Enter age" << std::endl;
std::cin >> s.age;
std::cout << "Enter score" << std::endl;
std::cin >> s.score;
return s;
}
std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(enter_student());
A: to sort the vector:
sort(st.begin(), st.end(), compare);
and to read input to your vector you should first resize the vector or input to a temporary
variable and push it to your vector:
www.cplusplus.com/reference/stl/vector/vector/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: ExtJS 4 - Data in the grid not visible
I have a simple grid with the following code (along with the code of store and model).
var containerDetailsGrid = Ext.create('Ext.grid.Panel', {
store: storeVarContainerDetails,
tbar:[
{
xtype:'tbtext',
text:'Container Details'
}
],
columns: [
{
header : 'Ctr Size',
flex : 1,
dataIndex: 'ctrSize',
autoExpand:true,
align:'center'
}
],
height: 100
});
var storeVarContainerDetails = Ext.create('Ext.data.Store', {
model: 'VoyageMonitoringContainerDetailsModel',
proxy: {
type: 'ajax',
url: 'http://localhost/pnc/stores.php',
extraParams:{
action:'containerDetails'
},
reader: {
type: 'json'
}
},
autoLoad:true
});
Ext.regModel('VoyageMonitoringContainerDetailsModel', {
extend: 'Ext.data.Model',
fields: [
{type: 'string', name: 'ctrSize'}
]
});
The store is getting loaded and fetching the data but this data is just not getting displayed or actually is being visible in the grid.
When I inspect the grid element in DOM, then I can see the data to be there in 'td' of grid table, but that data is just not getting displayed.
There are other grids too on the page but all are displaying the data except this one. Also, there is no error being throw in console too.
Could anyone please throw some light at this that why it could be happening? Attached is a screen shot for more clarity.
PS: I am using ExtJS 4.
A: Posting the solution as an answer here so that it can help someone looking for the same and also I can mark this question as answered. The solution is - a grid should not be made the child of a container in a form, rather should be the child of fieldset in the form. I don't know the reason behind this, but works well for me. Hope this helps someone else too.
A: Did you try this on your store ?
autoLoad :true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Memory managment and JVM setting for solr I have a large Data storage(About 500GB pdf and video files) and my machine have a 4GB of RAM capacity, i want to index these file with solrj API's , what is the necessary setting for solrconfig and JVM to ignore heap size problem and other memory crash down during indexing?
is it any configuration to force garbage collector to deallocate the memory during indexing?
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Controlling placement of footer sections on page in Crystal Reports I use CrystalReport in Visual Studio 2005 and make a bill report ... this bill
I use the header - Details- and footer in this report ..
in details section I limit the record to 10 for every page
so if there is a bill contains 15 record ..
first 10 record in first page . and 5 in the second page when print
put the problems
1- the footer show in the second page only
2- in the second page the Fields in the footer Raised up beacuse the second page contains 5 records only
so if the record number in the report is not 10 so the footer fields raised up
so please any one help me to solve the problem
Notation : I limit the number of records for every page to 10 record only .. i need empty
records if the reports records < 10 \
Please any one help my
Thanks
A: Sorry I don't know 100% what your problem is (maybe post some screenshots) but there might be two possible problems/solutions:
*
*in CR Reports you've got document and page footer - if you use the document footer (don't remember the exact name) you will see this only once - just like a document header
*if the details parts get's to big the footers are AFAIK the first thing that get's striped so try to compress your details (or any other section) to get more area for the footer (or display only 9 items per page instead of 10 - just for trial)
To really fill your report with empty details you will have to append empty rows to your data and use conditional supresses in your CR to not show things like '0' but IMHO this will get a real pain and you should go without printing empty details - never seen a situation where you need this or where it is desired.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits