text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Eclipse - Maven Installation Error I am trying to install Maven Plugin for Eclipse , but i am geting this error .
I am using
Eclipse Java EE IDE for Web Developers.
Version: Indigo Release
Build id: 20110615-0604 Version of Eclipse .
Cannot complete the install because of a conflicting dependency.
Software being installed: m2e - Maven Integration for Eclipse 1.0.100.20110804-1717 (org.eclipse.m2e.feature.feature.group 1.0.100.20110804-1717)
Software currently installed: Maven Integration for Eclipse (Required) 0.12.1.20110112-1712 (org.maven.ide.eclipse.feature.feature.group 0.12.1.20110112-1712)
Only one of the following can be installed at once:
Maven Integration for Eclipse 0.12.1.20110112-1712 (org.maven.ide.eclipse 0.12.1.20110112-1712)
This version of m2eclipse cannot be installed on top of the already installed m2eclipse. Uninstall the previous version of m2eclipse and try the install again. 1.0.100.20110804-1717 (org.maven.ide.eclipse 1.0.100.20110804-1717)
Cannot satisfy dependency:
From: m2e - Maven Integration for Eclipse 1.0.100.20110804-1717 (org.eclipse.m2e.feature.feature.group 1.0.100.20110804-1717)
To: bundle org.maven.ide.eclipse [1.0.100.20110804-1717]
Cannot satisfy dependency:
From: Maven Integration for Eclipse (Required) 0.12.1.20110112-1712 (org.maven.ide.eclipse.feature.feature.group 0.12.1.20110112-1712)
To: org.maven.ide.eclipse [0.12.1.20110112-1712]
please refer to the screen shot of the error given below
http://imageshack.us/f/823/eclipsse.jpg/
A: You should simply uninstall m2eclipse version 0.12.x and retry installation. You are essentially trying to install both m2e and m2eclipse (read: older m2e) together.
My Eclipse JDT and m2e versions are:
Eclipse Java Development Tools 3.7.0.v20110520-0800
m2e - Maven Integration for Eclipse 1.0.0.20110607-2117
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Simulate mysql queries Is there a way to test the mysql queries, without modifying my database?
For example, can I run a delete from my_table where id=101 without actual delete anything? What about insert and update?
TY
A: If you just want to see how many rows would be deleted why not substitute 'delete' with 'select count(*)'?
A: You could start a transaction before running your queries and then rollback after running them. Note that to do this you'll require InnoDB or XtraDb tables (won't work on MyISAM).
To start a transaction send to MySQL the following statement:
START TRANSACTION;
And at the end of your queries run the following statement:
ROLLBACK;
Your database will never be modified from the point of view of other connections. Your current connection will see the changes until ROLLBACK, and after that the original state will be restored.
A: Copy your database to a test-database or auto-generate a import-script. Than you can test whatever you want on the test-database and restore it again using the script or import.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: User first_name and last_name limitations on Facebook and Twitter I need to know the maximum length of users first and last name that he can have on Facebook and Twitter. Our application allows to register using this social networks and we have limitations for the number of characters in user's first and last names.
Too long names can spoil slicing.
Can anybody help?
A: On twitter there's no first_name and last_name. However there is allocation to input name which is 20 Characters Max
You can update your twitter name (not username) via this
POST http://twitter.com/account/update_profile.json
https://dev.twitter.com/docs/api/1/post/account/update_profile
As for Facebook the maximum length for each field (that is first name and last name) is 75 Characters
A: On Twitter, your username can be up to 15 characters long and your display name can be up to 50 characters long. See “How to Change Your Username” in the Twitter Help Center. Those seem to be the longest they’ve ever been allowed to be.
On Facebook, your first, middle, and last names can currently each be up to 30 characters long. Don’t know if that has always been the case so keep an eye out for older accounts that could have chosen longer names before the limits were set.
Facebook doesn’t mention character limits on names in their “What names are allowed on Facebook?” Help Center article nor in the Graph API User documentation but I was able to reverse engineer the limits by trying to enter different lengths of names on the “General Account Settings” page. Entering anything over 30 characters long gives you the “Names can’t have too many characters” error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best practices to query SQLite database in ListFragment with CursorLoader? I'm using Android Compatibility Library in my project. I've set up ListFragment as described in the DevGuide (http://developer.android.com/reference/android/app/Fragment.html), and using a simple CursorLoader Christian made be used without content provider (CursorLoader usage without ContentProvider).
The question is where, in my ListFragment / parent Activity, should I open database, return the Cursor, create Adapter and setListAdapter?
So in my app, I have TitlesFragment, DetailsFragment, FragmentLayoutActivity, DetailsLayoutActivity.
Is the best practice...
*
*to open database in ListFragment's onActivityCreatedand close it in ListFragment's onDestroy like in code sample below
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Open database
playersDatabaseHelper = new PlayersDBAdapter(getActivity());
playersDatabaseHelper.open();
getLoaderManager().initLoader(0, null, this);
...
}
@Override
public void onDestroy() {
super.onDestroy();
if (playersDatabaseHelper != null) {
playersDatabaseHelper.close();
}
}
*query database and return the cursor in onCreateLoader, and create the Adapter and setListAdapter in onLoadFinished like in code sample below
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new MyCursorLoader(getActivity()) {
@Override
public Cursor loadInBackground() {
playersCursor = playersDatabaseHelper.getAllPlayers();
return playersCursor;
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Create an empty adapter we will use to display the loaded data.
playersAdapter = new RowAdapter(getActivity(), playersCursor, R.layout.players_overview_row);
// Allocate the adapter to the List displayed within this fragment.
setListAdapter(playersAdapter);
playersAdapter.swapCursor(cursor);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
Am I on the right track or should I move some of those somewhere? Thanks for your time!
A: Sorry no experience in CursorLoader yet and Fragment, but I already experienced use of SQLiteOpenHelper in the context of concurrent access by different threads & activities.
I will assume that PlayersDBAdapter is internally using a SQLiteOpenHelper class. but it is not clear what your methods open() and close() are doing?
What I did:
*
*define your SQLiteOpenHelper as an application wide singleton, not activity wide as you seem to do
*instantiate SQLiteOpenHelper single instance in your Application onCreate
*DON'T release SQLiteOpenHelper instance in any activity onDestroy, as when an activity stops, another one might still have to open the DB
*I guess SQLiteOpenHelper instance should be cleared in application onTerminate (not sure as onTerminate is in practice almost never called)
*I have DBAdapter object which gets a SQLiteDatabase reference with mySQLiteOpenHelper.getWritableDatabase()
*these DBAdapter are typically allocated in activity onCreate and released in onDestroy
At least this works, no crashs in an application with several thousands users.
Suggestions to improve that are welcome :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: How to change Value, Backcolor etc... in an Access Record programmatically? When I type the name of a control in a form (code side), I can modify the control backcolor, value etc... whereas I don't have any of those options in a report. How can I modify them ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Which approach is better when passing settings to an object? I want to set initial values of fields in an object, using $config. Which approach is better in terms of cleaner and more maintainable code?
Also, I would like to add that object will be initialized in a factory and not directly by client.
1. I pass $config to the object
<?php
class UserGreeting {
private $config;
public function __construct($config){
$this->config=$config;
}
public function greetings(){
echo 'Hello, '.$this->config->get('username');
}
}
?>
Pros:
*
*Easy to pass multiple parameters
Cons:
*
*The class is coupled with $config ( is it?). What I mean is that
apart from particular $config interface and parameters naming
conventions, I can't just plug this class into another program
without introducing $config
*Client code doesn't have to know which parameters are used by the
object, but that is more general thought
2. I set fields manually outside the object
<?php
class UserGreetingFactory{
public function __construct($config){
$this->config=$config;
}
public function getUserGreeting(){
$userGreeting=new UserGreeting();
$userGreeting->setUserName='John Doe';
return $userGreeing;
}
}
class UserGreeting {
private userName;
public function setUserName($userName){
$this->userName=$userName;
}
public function greetings(){
echo "Hello, {$this->userName}";
}
}
?>
Pros:
*
*The class doesn't care where his parameters are coming from
*Can reuse easily
*Easier to test(is it?). I mean that I don't have to deal with setting
up $config
Cons:
*
*Factory\Builder has to know which parameers to pass
*Lots of extra code for setters and passing parameters
A: First solution with ctor injection. But instead of a special config i would just pass the actual objects. In your case an User object.
<?php
class UserGreeting
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function greet()
{
printf('Hello, %s!', $this->user->getName());
}
}
A: Considering your idea's, I'd stick to a single variable. If you want to pass the variables per-method you'll have a lot of excessive code.
From an OOP point of view, you shouldn't put it in a single variable. An object has properties. An username is in fact a property so you should use it as property. That means that in PHP classes you'd need to make it a public variable and set the variables when you create the object.
A: The first way is better because of dependency injection. This code will be easier to test and to maintain.
The third way is to use Visitor pattern to inject dependencies.
A: You could use a static class with static methods. In effect they are like CONSTS, but you can enforce all kinds of rules within the static config class - that they conform to an interface for example.
Config::getUserName();
That way if you are going to be faced with a family of config objects, you can be assured they all have at least an entry for each expected value - otherwise a warning is chucked.
Might depend on your situation of course, and I expect there are many situations where you would not want to do this - but I will offer it up all the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails nested join with conditions I have the following join tables and (relevant models and tables)
*
*roles_users : user_id, role_id
*permissions_roles : role_id, permission_id, object_id, object_type
For a given user, permission and object, I would like to like to find if user has an associated permission for an object via its roles.
Any help with the relevant query would be much appreciated.
A: Given you have the user and the object, how about this:
allowed = user.roles.joins(:permissions => :object).where(:object => { :id => object.id }).any?
A: Try this:
class User
def has_permission?(permission, object)
RoleUser.joins(:permission_roles).where(
:roles_users => {
:user_id => id
},
:permission_roles => {
:permission_id => permission,
:object_type => object.class.base_class.name,
:object_id => object
}
).exists?
end
end
Now you can check the permission as follows:
current_user.has_permission?(@edit_permission, @blog_post)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "Command not found: grep" in karaf console I have strange problem with Servicemix version Fuse ESB 4.4.1.
Sometimes the part of the commands will not load and be not available. Usually this happens with quite often used by me command, grep. This looks as following:
karaf@root> list | grep spring
Command not found: grep
It seems to be random, restart usually helps. With previous versions of Fuse ESB it happened sometimes, but quite rare, now it happens quite often. Can someone help, what is causing the problem?
A: Perhaps completely unrelated, but I've encountered a number of boot-time race conditions in Karaf and its dependencies. Most importantly, this one that I filed:
https://issues.apache.org/jira/browse/KARAF-910
"Race between FeatureService and ConfigAdmin for resolving mvn: URLs?"
That particular defect only manifests if you have some non-standard settings for pax-url-mvn, but it's a symptom of the general problem that configadmin applies settings asynchronously, so it matters if the configadmin thread is faster or slower than the main OSGi bundle-starting thread.
I have not seen any Karaf Command problems related to that race, but my problem is superficially similar in that some bundle services randomly don't start.
A: The 'grep' command has a full name - shell:grep. You might try that to see if e.g. another command has been installed with the same short (unqualified) name and it's getting confused.
The other possibility is that the bundle that provides the grep service has stopped, possibly by accident.
osgi:list -t 0 -s
will show you a list of all the bundles by symbolic name, which includes this one: (the number may be different):
[ 18] [Active ] [Created ] [ 30] org.apache.karaf.shell.commands (2.2.3)
karaf@root> osgi:stop 18
You are about to access system bundle 18. Do you wish to continue (yes/no): yes
karaf@root> help | grep grep
Command not found: grep
karaf@root> osgi:start 18
You are about to access system bundle 18. Do you wish to continue (yes/no): yes
karaf@root> help | grep grep
shell:grep
As for why that bundle is being stopped -- maybe something (or someone) is explicitly stopping it? Or it's being stopped by accident?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 3.1 Upload images and save them to the database and render them back when needed? I'm building a Rails Application and i want to store some images to the database and render them back when i need them in the html.erb file.
Can someone point me at the right direction????
Also i have a side bar on my layout file and i want to render something in one controller and then something else in an other controller!
Is that possible?
This is the an exaple layout file but i don't want to render them on the layout
<div id="left_sidebar" class="column">
</div>
<div id="main_wrapper" class="column">
<%= yield %>
</div>
<div id="right_sidebar" class="column">
</div>
Thank you very much in advance!
A: You should not store image files in your database. I recommend you use gems like Carrierwave.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP redirect page with status code problem I am trying to redirect a page using HTTP 410 status using php header function as
header("HTTP/1.1 410 Gone");
header('Location: http://domain.com/down.php');
exit;
The problem is that even if I set a 410 status code...the status code will automatically change to 302
I have also tried with
header('Location: domain.com/down.php', true, 410);
exit;
It shows 410 redirection but the redirected page does not show anything. It shows a blank page.
Does anybody know if there is a solution for this?
A: The 410 error indicates that the Web server has no forwarding address for the URL, so can provide no redirection to the new Web server. So the blank page you got using the second snippet is correct.
The first code snippet also gives the correct result - Location creates a redirect to a given address.
So there is no errors in your code or in PHP. I'm not sure you do what you realy need =)
A: The last header line is a correct way to set the status code:
header('Location: domain.com/down.php', true, 410);
However, the Location header name requires a fully qualified URL, your URL looks incomplete. That's not valid.
Next to that you don't send any HTTP response body, so the browser can only display a blank page. To display a non-blank page, provide a response body:
header('Location: http://domain.com/down.php', true, 410);
echo '<h1>Gone.</h1><a href="http://domain.com/down.php">here.</a>';
exit;
Providing a response body is useful, because user-agents do not need to follow Location headers automatically, especially as with the 410 response code RFC 2616, no response header named Location is expected by a HTTP client.
Maybe you're looking for 301 Moved Permanently.
A: header('Location: http://domain.com/down.php', true, 410);
exit;
Should works. You forgot about protocol in URL.
Besides, AFAIU, Yo can use
header('Location: 'http://domain.com/'down.php');
header("HTTP/1.1 410 Gone");
exit;
But Are you sure you need Redirect and 4xx HTTP status?
A: Try to use some proper quotes?
header("HTTP/1.1 410 Gone");
header("Location: http://domain.com/down.php");
exit;
A: You have to include the error page :
header("HTTP/1.0 410 Gone"); include_once("410.html"); exit();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how to use data from ajax success in another function? i want to call jquery ajax function inside the function like this:
function mine(time){
$.get("test.php", function(data){
var mytime=data;
});
alert(mytime);
}
it just print undefined.
my test.php file is this:
<?php echo time(); ?>
i want that value of 'mydata' is current time of php server.
A: The callback function gets executed at a later time. Instead of document.write at, use jQuery's methods:
$.get("test.php", function(data){
var mytime=data;
// Replace 'body' with a selector for the element that displays time
$('body').text(mytime);
// Alternatively, call another function
someOtherFunction(mytime);
});
A: There may be chance of variable scope so define your variable like this
var mytime;
function mine(time){
$.get("test.php", function(data){
mytime=data;
});
document.write(mytime);
}
A: You need to use synchrone mode
function validerServeur(value) {
var retval;
$.ajax(
url: "test.php",
data: { valeur: value },
async: false, // <-- This disable asynchrone mdoe
succes: function(data) {
retval = data;
}
) ;
return retval;
}
A: add the document.write(time) INSIDE the $.get 's handler like:
$.get("test.php", function(data){
var mytime=data;
document.write(mytime);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Background images dissapearing in iOS Safari I'm working on a mobile version of a site and I'm emulating the iOS interface. There's a few places on the site where there's supporting background image sprites (chevron turns into loading gif / greyscale icon turns into colored icon).
It works flawlessly in desktop Safari, and is spotty on mobile Safari. The images will load sometimes, not others; the icons will load but the chevrons won't; they load on my iPhone but not my iPad and vice versa.
I'm getting no errors in the Debug Console. Here's the HTML and CSS:
CSS:
footer li a i {display:block; height:24px; width:24px; margin:0 auto;}
footer li a i.foo {background:url(../images/sprite-jobs.png) 0px 0px no-repeat;}
footer li a:hover i.foo {background:url(../images/sprite-jobs.png) 0px -24px no-repeat;}
HTML:
<li><a href="#link"><i class="foo"></i>Text</a></li>
I have also found that if I quit Safari via the multi-task bar and restart the app all background images return, however simply clearing the cache has no affect.
A: I experienced a related issue yesterday - I have vertical menu in which the currently selected page's menu item has a background "blob" graphic to the left of it. This works fine on all browsers. I then added the same background image as a rollover to the menu, using "a:hover". This works fine on all browsers but mobile/iOS Safari. When I use the menu on the iPad the blob-graphic completely disappears at some seemingly random interval and never comes back unless I update the image and html files on the server. (Clearing the Safari cache has no effect).
This is my guess as to why it happens and how I solved it...
The :hover behaviour on touch-screen devices such as the iPad/iPhone is broken (because you can't really hover on a touchscreen). So the effect of using a hover seems to be that the browser believes the image associated with the hover is redundant and therefore doesn't cache it. However when a page featuring the hover-image is next loaded, the request to the server will detect that the image-file has not been altered, and thus deem it unnecessary to retrieve it (from the server), and therefore try to use the local cached copy which, I am presuming, doesn't exist (or at least not correctly). This causes the image to disappear (all copies of it on the page vanish).
Thus if you use the same physical image-file for the background of the hover-item and for the current-page menu image (or any other image on the page), both/all will effectively disappear when the browser decides to use its (non-existant) cached version.
One solution is to have two identical image files, and use one for the hovered-over menu-item, and the other one for anywhere else it's required. Then it doesn't matter if mobile-Safari discards the one associated with the hover (as there is no rollover-effect on those devices), but it won't effect the graphic associated with any other menu items (e.g. to mark the current page or whatever).
Can you let me know if that solves your problem? I couldn't find anything about this particular bug despite hours of searching.
A: It's probably not disappearing per se but sliding twice as far down the image as you intended on Retina displays, a la:
enhancing image quality for iphone 4 from 72ppi to 326ppi
Simple test: Double the image vertically and try again. You'll most likely see a 1/2 size version of what you intended appearing there, because of the iPhone 4's annoying way of handling background images.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: objectForKey returns nil on a dictionary I am creating a recipe manager app for iPad. I am using the split view template which loads data for the recipes from a plist which is structured in this way. The table view on the left works perfectly. It loads the data from the plist. The problem is the detail view. As you can see I have inserted a NSLog lines in the DetailViewController.m file since every string I passed to the text field resulted as nil. Strangely, when I tried to NSLog from the RootViewController.m with:
NSLog(@"%@", [detailViewController.ricetta allKeys])
it worked.
Any suggestions?
I tried to post as much lines as possible to explain the problem as well as possible.
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>Risotto alla zucca</string>
<key>ingredients</key>
<string></string>
<key>description</key>
<string></string>
<key>photo</key>
<string></string>
</dict>
<dict>
<key>name</key>
<string>Semi di zucca al forno</string>
<key>ingredients</key>
<string></string>
<key>description</key>
<string></string>
<key>photo</key>
<string></string>
</dict>
<dict>
<key>name</key>
<string>Risotto ai funghi</string>
<key>ingredients</key>
<string></string>
<key>description</key>
<string></string>
<key>photo</key>
<string></string>
</dict>
</array>
</plist>
RootViewController.h
#import <UIKit/UIKit.h>
#import "RecipeConstants.h"
@class DetailViewController;
@interface RootViewController : UITableViewController {
NSMutableArray *ricette;
}
@property (nonatomic, retain) NSMutableArray *ricette;
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@end
RootViewController.m
...
@synthesize ricette;
- (void)viewDidLoad
{
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
NSString *path = [[NSBundle mainBundle] pathForResource:@"RicetteArray" ofType:@"plist"];
NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
self.ricette = tmpArray;
[tmpArray release];
}
...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.ricette count];
}
// Configure the cell.
cell.textLabel.text = [[self.ricette objectAtIndex:indexPath.row] objectForKey:NAME_KEY];
return cell;
}
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
detailViewController.ricetta = [self.ricette objectAtIndex:indexPath.row];
}
...
- (void)dealloc
{
[detailViewController release];
[ricette release];
[super dealloc];
}
@end
DetailViewController.h
#import <UIKit/UIKit.h>
#import "RecipeConstants.h"
@interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UISplitViewControllerDelegate> {
IBOutlet UILabel *lblTitolo;
IBOutlet UITextView *ingredientiTxtView;
IBOutlet UITextView *descrizioneTxtView;
IBOutlet UIImageView *fotoImgView;
NSDictionary *ricetta;
}
@property (nonatomic, retain) IBOutlet UILabel *lblTitolo;
@property (nonatomic, retain) IBOutlet UITextView *ingredientiTxtView;
@property (nonatomic, retain) IBOutlet UITextView *descrizioneTxtView;
@property (nonatomic, retain) IBOutlet UIImageView *fotoImgView;
@property (nonatomic, retain) NSDictionary *ricetta;
@property (nonatomic, retain) IBOutlet UIToolbar *toolbar;
@property (nonatomic, retain) id detailItem;
@end
DetailViewController.m
@synthesize lblTitolo, ingredientiTxtView, descrizioneTxtView, fotoImgView, ricetta;
...
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
lblTitolo.text = [ricetta objectForKey:NAME_KEY];
ingredientiTxtView.text = [ricetta objectForKey:INGREDIENTS_KEY];
descrizioneTxtView.text = [ricetta objectForKey:DESCRIPTION_KEY];
UIImage *img = [UIImage imageNamed:PHOTO_KEY];
fotoImgView.image = img;
NSLog(@"%@", [ricetta allKeys]);
}
...
- (void)dealloc
{
[_myPopoverController release];
[_toolbar release];
[_detailItem release];
[lblTitolo release];
[ingredientiTxtView release];
[descrizioneTxtView release];
[fotoImgView release];
[ricetta release];
[super dealloc];
}
@end
UPDATE:
Actually in the DetailViewController.m I have this method:
- (void)updateRicetta {
lblTitolo.text = [ricetta objectForKey:NAME_KEY];
NSString *myIngredients = [ricetta objectForKey:INGREDIENTS_KEY];
myIngredients = [myIngredients stringByReplacingOccurrencesOfString:@", " withString:@"\n"];
ingredientiTxtView.text = myIngredients;
NSString *myDescription = [ricetta objectForKey:DESCRIPTION_KEY];
myDescription = [myDescription stringByReplacingOccurrencesOfString:@". " withString:@"\n"];
descrizioneTxtView.text = myDescription;
NSString *nomeImmagine = [NSString stringWithFormat:@"%@.jpg", [ricetta objectForKey:PHOTO_KEY]];
[self.fotoImgView setImage:[UIImage imageNamed:nomeImmagine]];
}
which is called from RootViewController.m in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
using
[detailViewController updateRicetta];
I have the following two warnings:
'DetailViewController' may not respond to '-updateRicetta'
Instance method '-updateRicetta not found (return type defaults to 'id')
Another problem is that the detail view updates only when I click on a cell not at app loading.
A: I'm happy to be wrong about this, but it looks to me like when you call tableView:didSelectRowAtIndexPath: you set the recipe (ricetta?) in the DetailViewController but I don't see any instruction to tell the DetailViewController to display the new recipe.
You have code to update your DetailViewController in viewWillAppear:animated: but this will only happen when the view is going to appear - if your view has already appeared this method won't be executed.
I suggest you create a method in DetailViewController called updateRicetta which will look something like:
- (void)updateRicetta {
lblTitolo.text = [ricetta objectForKey:NAME_KEY];
ingredientiTxtView.text = [ricetta objectForKey:INGREDIENTS_KEY];
descrizioneTxtView.text = [ricetta objectForKey:DESCRIPTION_KEY];
UIImage *img = [UIImage imageNamed:PHOTO_KEY];
fotoImgView.image = img;
}
You could then call this from tableView:didSelectRowAtIndexPath: -
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
detailViewController.ricetta = [self.ricette objectAtIndex:indexPath.row];
[detailViewController updateRicetta];
}
As to the returning nil: my guess is that when viewWillAppear:animated: is called you have not yet selected an entry and therefore ricetta has not yet been set in the DetailViewController.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery validate submitHandler triggers validation When using the jQuery submitHandler method, I'm posting the form data via ajax to the server. On success, another method is called that resizes a popup and notifies the user its all complete.
My problem is however, whilst posting the data, the form is getting validated again causing undesired effects.
My understanding is submitHandler shouldn't trigger the validation again?
submitHandler: function(form) {
console.log('test');
}
In this instance, 'test' is being logged to the console, but the validation is being run once again (in this case, a server side validity check on an email address field).
I'm using a button type submit as the form element. Do I need to prevent defaults or something similar?
A: Your submitHandler should exist within the validate function. In addition you should call form.submit() yourself which will remove the recursive calls that would otherwise exist.
$("#myForm").validate({
submitHandler: function (form) {
console.log('test');
form.submit();
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: The facebook dialog api not working i develop an ios app and use the facebook dialog api, it worked fine over a month.
How ever it suddenly not work now
The reference facebook document from
http://developers.facebook.com/docs/reference/dialogs/
and i Tried the sampele link. the same error message appeared
http://m.facebook.com/dialog/feed?app_id=123050457758183&redirect_uri=http://www.example.com/response/&display=touch
Any one knows what happened.....
it shows "There was a problem generating the Feed story from the provided data."
it works today.
I think this problem was facebook server side error.
i didn't change any thing and it works today.
A: Same here, with that request (I removed good params but the error is here) :
http://developers.facebook.com/tools/debug/og/object?q=https%3A%2F%2Fm.facebook.com%2Fdialog%2Ffeed%3Flink%3Dhttp%253A%252F%252Ffr.xxx.com%252F%26description%3Dxxx%26caption%3Dxxx%26picture%3Dhttp%253A%252F%252Ffr.xxx.com%252Fimgs%252FlampeWho.png%26name%3Dxxx%26app_id%3Dxxx%26redirect_uri%3Dfbconnect%253A%252F%252Fsuccess%26sdk%3D2%26display%3Dtouch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: GWT SelectionModel is returning old selection I have a cell table with an async data provider. If I update the data via the data provider the table renders the new data correctly but the selection model still holds onto and returns old objects.
Any ideas how to refresh the selection model?
A: I think you should make your SelectionModel work with different instance of the same "logical" object using the appropriate ProvidesKey. For instance, you could use ProvidesKey that calls getId on the object, so that two objects with the same such ID would be considered equal; so even if the SelectionModel holds onto the old object, it can still answer "yes, it's selected" when you give it the new object.
FYI, this is exactly what the EntityProxyKeyProvider does (using the stableId of the proxy). And the SimpleKeyProvider, used by default when you don't specify one, uses the object itself as its key.
A: I came across the same issue. Currently I have this as single selection model.
SelectedRow = store it when you select it.
Then when data is reloaded you can clear it by
celltable.getSelectionModel().setSelected(SelectedRow, false);
I guess it is too late for you but hope it helps someone else.
A: Here is my manual method for refreshing the SelectionModel. This allows you to use the selectedSet() when needed and it will actually contain the current data, rather than the old data - including the removal of deleted rows and updated fields!
I have included bits & pieces of a class extending DataGrid. This should have all the logic at least to solve your problems.
*
*When a row is selected, call saveSelectionKeys().
*When the grid data is altered call refeshSelectedSet().
*If you know the key type, you can replace the isSameKey() method with something easier to deal with. This class uses generics, so this method attempts to figure out the object conversion itself.
.
public abstract class AsyncDataGrid<T> extends DataGrid<T> {
...
private MultiSelectionModel<T> selectionModel_;
private ListDataProvider<T> dataProvider_;
private List<T> dataList_;
private Set<Object> priorSelectionKeySet_;
private boolean canCompareKeys_;
...
public AsyncDataGrid( final ProvidesKey<T> keyProvider ){
super( keyProvider );
...
dataProvider_ = new ListDataProvider<T>();
dataList_ = dataProvider_.getList();
canCompareKeys_ = true;
...
}
private void saveSelectionKeys(){
priorSelectionKeySet_ = new HashSet<Object>();
Set<T> selectedSet = selectionModel_.getSelectedSet();
for( Iterator<T> it = selectedSet.iterator(); it.hasNext(); ) {
priorSelectionKeySet_.add( super.getValueKey( it.next() ) );
}
}
private void refeshSelectedSet(){
selectionModel_.clear();
if( priorSelectionKeySet_ != null ){
if( !canCompareKeys_ ) return;
for( Iterator<Object> keyIt = priorSelectionKeySet_.iterator(); keyIt.hasNext(); ) {
Object priorKey = keyIt.next();
for( Iterator<T> it = dataList_.iterator(); it.hasNext(); ) {
T row = it.next();
Object rowKey = super.getValueKey( row );
if( isSameKey( rowKey, priorKey ) ) selectionModel_.setSelected( row, true );
}
}
}
}
private boolean isSameRowKey( final T row1, final T row2 ) {
if( (row1 == null) || (row2 == null) ) return false;
Object key1 = super.getValueKey( row1 );
Object key2 = super.getValueKey( row2 );
return isSameKey( key1, key2 );
}
private boolean isSameKey( final Object key1, final Object key2 ){
if( (key1 == null) || (key1 == null) ) return false;
if( key1 instanceof Integer ){
return ( ((Integer) key1) - ((Integer) key2) == 0 );
}
else if( key1 instanceof Long ){
return ( ((Long) key1) - ((Long) key2) == 0 );
}
else if( key1 instanceof String ){
return ( ((String) key1).equals( ((String) key2) ) );
}
canCompareKeys_ = false;
return false;
}
}
A: I fixed my particular issue by using the following code to return the visible selection. It uses the selection model to determine what is selected and combines this with what is visible. The objects themselves are returned from the CellTable data which is always upto date if the data has ever been changed via an async provider (the selection model data maybe stale but the keys will be correct)
public Set<T> getVisibleSelection() {
/*
* 1) the selection model contains selection that can span multiple pages -
* we want to return just the visible selection
* 2) return the object from the cellTable and NOT the selection - the
* selection may have old, stale, objects if the data has been updated
* since the selection was made
*/
Set<Object> selectedSet = getKeys(selectionModel.getSelectedSet());
List<T> visibleSet = cellTable.getVisibleItems();
Set<T> visibleSelectionSet = new HashSet<T>();
for (T visible : visibleSet) {
if (selectedSet.contains(KEY_PROVIDER.getKey(visible))) {
visibleSelectionSet.add(visible);
}
}
return visibleSelectionSet;
}
public static Set<Object> getKeys(Collection<T> objects) {
Set<Object> ids = new HashSet<Object>();
for (T object : objects) {
ids.add(KEY_PROVIDER.getKey(object));
}
return ids;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Jquery not method problem with button tag i don't why but the not() method of jquery return the same value for two differents tests that are exclusive.
Look:
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script language="javascript">
$(function() {
$(':button, :submit').filter(function() {
$('#result').append('tag = ' + $(this)[0].tagName + "<br />");
$('#result').append('.not(\':submit\').length = ' + $(this).not(':submit').length + "<br />");
$('#result').append('.not(\':button\').length = ' + $(this).not(':button').length + "<br />");
$('#result').append('.is(\':button\') = ' + $(this).is(':button') + "<br /><br />");
});
});
</script>
<button>Btn1</button>
<input type="button" value="Btn2" />
<input type="submit" />
<div id="result">
</div>
Here are the results :
tag = BUTTON
.not(':submit').length = 0
.not(':button').length = 0
.is(':button') = true
tag = INPUT
.not(':submit').length = 1
.not(':button').length = 0
.is(':button') = true
tag = INPUT
.not(':submit').length = 0
.not(':button').length = 1
.is(':button') = false
Found a bug ?
A: No, this is by design. For the specific case of the button element, both the :submit filter and the :button filter are true. button elements have the submit type by default (see the MDN docs).
A: I assume you are confused by
.not(':submit').length = 0
.not(':button').length = 0
Your assumption is wrong, your tests are not exclusive. The jQuery documentation states:
:button: Selects all button elements and elements of type button.
:submit: Selects all elements of type submit.
Now, it happens to be that button elements have a type attribute and the default value is submit.
type = submit|button|reset [CI]
This attribute declares the type of the button. Possible values:
*
*submit: Creates a submit button. This is the default value.
*reset: Creates a reset button.
*button: Creates a push button.
So jQuery returns the correct results. not(:button).length returns 0 because we are dealing with a button elements. not(:submit).length returns 0 because that button element as a type attribute with value submit.
A: Change filter(function() {}) to each(function(){}) then you may be in luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which Layout is better to use? In My Application i have to use the Calculator.
The Different Button in Calculator should be like below image.
So, What should be better to implement such type of the Layout ?
I think gridView is good, but while thinking about the "0" Button and the Button below "C" button, I dont know how to set it in to the gridview.
So Anybudy tell me which one is the Best way to set this type of layout ?
recently i have use the relative layout to set this layout.
Please help me regarding this. and if the GridView is nice with this then tell me what should i have to do with that two buttons: one is "0" button and second is the Button that is below thee Button of "left errow".
Code to have Use the RelativeLayout:
<RelativeLayout android:id="@+id/calculationButtonLayout"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="@+id/totalAmount" android:layout_margin="10dp">
<RelativeLayout android:id="@+id/linear_layout" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_centerInParent="true" android:gravity="center_horizontal">
<!-- First row Start -->
<Button android:id="@+id/sevenNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="7" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/eightNumber" android:layout_toRightOf="@+id/sevenNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="8" android:textColor="#ffffff" android:textSize="22dp"
android:background="@drawable/selector_button"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/>
<Button android:id="@+id/nineNumber" android:layout_toRightOf="@+id/eightNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="9" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/acButton" android:layout_toRightOf="@+id/nineNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="AC" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/brown_button"/>
<!-- First row Finish -->
<!-- Second row Start -->
<Button android:id="@+id/fourNumber" android:layout_below="@+id/sevenNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="4" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/fiveNumber" android:layout_toRightOf="@+id/fourNumber" android:layout_below="@+id/eightNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="5" android:textColor="#ffffff" android:textSize="22dp"
android:background="@drawable/selector_button"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"/>
<Button android:id="@+id/sixNumber" android:layout_toRightOf="@+id/fiveNumber" android:layout_below="@+id/nineNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="6" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/clearButton" android:layout_toRightOf="@+id/sixNumber" android:layout_below="@+id/acButton"
android:layout_height="50dp" android:layout_width="50dp"
android:text="C" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/brown_button"/>
<!-- Second row finish -->
<!-- Third row Start -->
<Button android:id="@+id/oneNumber" android:layout_below="@+id/fourNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="1" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/twoNumber" android:layout_toRightOf="@+id/oneNumber" android:layout_below="@+id/fiveNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="2" android:textColor="#ffffff" android:textSize="22dp"
android:background="@drawable/selector_button"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"/>
<Button android:id="@+id/threeNumber" android:layout_toRightOf="@+id/twoNumber" android:layout_below="@+id/sixNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="3" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<!-- Third row finish -->
<!-- Fourth row Start -->
<Button android:id="@+id/zeroNumber" android:layout_below="@+id/oneNumber"
android:layout_height="50dp" android:layout_width="110dp"
android:text="0" android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:background="@drawable/selector_button"/>
<Button android:id="@+id/dotNumber" android:layout_toRightOf="@+id/zeroNumber" android:layout_below="@+id/threeNumber"
android:layout_height="50dp" android:layout_width="50dp"
android:text="." android:textColor="#ffffff" android:textSize="22dp"
android:background="@drawable/selector_button"
android:layout_marginTop="5dp" android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/>
<Button android:id="@+id/doNothing" android:layout_toRightOf="@+id/threeNumber" android:layout_height="wrap_content" android:layout_width="50dp"
android:textColor="#ffffff" android:textSize="22dp"
android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:background="@drawable/do_nothing_button" android:layout_alignBottom="@+id/dotNumber" android:layout_alignTop="@+id/threeNumber"/>
<!-- Third row finish -->
</RelativeLayout>
</RelativeLayout>
The Image that i got after this Layout is:
In this Image the Keypad is not fit to the Whole Middle Window. I want to fit it in to the Window also.
So What should i have to do for it ?
A: You should use Relative layout as it will adjust itself with different resolution screens.
A: Use Relative layout because its have more functionality and also easier than other layout ................... and you have also set component toRightof and toLeftof and also many functionality////////
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Full-Text Catalog unable to search Primary Key I have create this little sample Table Person.
The Id is a primary key and is identity = True
Now when I try to create a FullText Catalog, I'm unable to search for the Id.
If I follow this wizard, I'll end up with a Catalog, where its only possible to search for a persons name. I would really like to know, how I can make it possible to do a fulltext search for both the Id and Name.
edit
SELECT *
FROM [TestDB].[dbo].[Person]
WHERE FREETEXT (*, 'anders' );
SELECT *
FROM [TestDB].[dbo].[Person]
WHERE FREETEXT (*, '1' );
I would like them to return the same result, the first returns id = 1 name = Anders, while the second query don't return anything.
edit 2
Looks like the problem is in using int, but is it not possible to trick FullText to support it?
edit 3
Created a view where I convert the int to a nvarchar. CONVERT(nvarchar(50), Id) AS PersonId this did make it possible for me to select that column, when creating the Full Text Catalog, but It still won't let me find it searching for the Id.
A: From reading your question, I am not sure that you understand the purpose of a full-text index. A full-text index is intended to search TEXT (one or more columns) on a table. And not just as a replacement for:
SELECT *
FROM table
WHERE col1 LIKE 'Bob''s Pizzaria%'
OR col2 LIKE 'Bob''s Pizzaria%'
OR col3 LIKE 'Bob''s Pizzaria%'
It also allows you to search for variations of "Bob's Pizzaria" like "Bobs Pizzeria" (in case someone misspells Pizzeria or forgot to put in the ' or over-zealous anti-SQL-injection code stripped the ') or "Robert's Pizza" or "Bob's Pizzeria" or "Bob's Pizza", etc. It also allows you to search "in the middle" of a text column (char, varchar, nchar, nvarchar, etc.) without the dreaded "%Bob%Pizza%" that eliminates any chance of using a traditional index.
Enough with the lecture, however. To answer your specific question, I would create a separate column (not a "computed column") "IdText varchar(10)" and then an AFTER INSERT trigger something like this:
UPDATE t
SET IdText = CAST(Id AS varchar(10))
FROM table AS t
INNER JOIN inserted i ON i.Id = t.Id
If you don't know what "inserted" is, see this MSDN article or search Stack Overflow for "trigger inserted". Then you can include the IdText column in your full-text index.
Again, from your example I am not sure that a full-text index is what you should use here but then again your actual situation might be something different and you just created this example for the question. Also, full-text indexes are relatively "expensive" so make sure you do a cost-benefit analysis. Here is a Stack Overflow question about full-text index usage.
A: Why not just do a query like this.
SELECT *
FROM [TestDB].[dbo].[Person]
WHERE FREETEXT (*, '1' )
OR ID = 1
You can leave off the "OR ID = 1" part if by first checking if the search term is a number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java excel to pdf conversion I need to convert xlsx documents to pdf format.
I know that iText can save pdf documents and Docx4j can read and write xslx.
In fact our application use both for building reports.
But we have very difficult templates so I can't just read xslx(docx4j) and write it to pdf(iText). The formatting will be lost, so I need another conversion lib.
I also heard about commercial libraries like (Jxcell ) but want to use open source solution.
Can anyone help me?
A: i have using iText and apache poi:
FileInputStream filecontent = new FileInputStream(new File(sourcepath));
FileOutputStream out = new FileOutputStream(new File(destinationPath));
HSSFWorkbook my_xls_workbook = null;
HSSFSheet my_worksheet = null;
XSSFWorkbook my_xlsx_workbook = null;
XSSFSheet my_worksheet_xlsx = null;
Document document = new Document(PageSize.ARCH_E, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfDestination magnify = null;
float magnifyOpt = (float) 70.0;
magnify = new PdfDestination(PdfDestination.XYZ, -1, -1, magnifyOpt / 100);
int pageNumberToOpenTo = 1;
PdfAction zoom = PdfAction.gotoLocalPage(pageNumberToOpenTo, magnify, writer);
writer.setOpenAction(zoom);
document.addDocListener(writer);
Iterator<Row> rowIterator = null;
int maxColumn = 0;
if (fileType.equals(".xls")) {
try {
my_xls_workbook = new HSSFWorkbook(filecontent);
my_worksheet = my_xls_workbook.getSheetAt(0);
rowIterator = my_worksheet.iterator();
maxColumn = my_worksheet.getRow(0).getLastCellNum();
} catch (IOException ex) {
Logger.getLogger(PdfConversion.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (fileType.equals(".xlsx")) {
try {
my_xlsx_workbook = new XSSFWorkbook(filecontent);
my_worksheet_xlsx = my_xlsx_workbook.getSheetAt(0);
rowIterator = my_worksheet_xlsx.iterator();
maxColumn = my_worksheet_xlsx.getRow(0).getLastCellNum();
} catch (IOException ex) {
Logger.getLogger(PdfConversion.class.getName()).log(Level.SEVERE, null, ex);
}
}
PdfPTable my_table = new PdfPTable(maxColumn);
my_table.setHorizontalAlignment(Element.ALIGN_CENTER);
my_table.setWidthPercentage(100);
my_table.setSpacingBefore(0f);
my_table.setSpacingAfter(0f);
PdfPCell table_cell;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next(); //Fetch CELL
switch (cell.getCellType()) { //Identify CELL type
case Cell.CELL_TYPE_STRING:
//Push the data from Excel to PDF Cell
table_cell = new PdfPCell(new Phrase(cell.getStringCellValue()));
if (row.getRowNum() == 0) {
table_cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table_cell.setBorderColor(BaseColor.BLACK);
}
my_table.addCell(table_cell);
break;
}
}
}
document.add(my_table);
document.close();
System.out.println("Excel file converted to PDF successfully");
A: Does it have to be done in Java?
If yes, maybe take a look at Apache POI
Otherwise, why not have a small native app that utilises a PDF Printer, and calls the relevant APIs to print the file directly to PDF? Surely Java is not really made for doing this kind of work...
For example here's a Non-Java framework for that: PDF Class Library from Solidworks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making a DIV float between header and footer I have the below fairly simple java-script function on a webpage with a header, footer and a banner in between the header and footer right side of the body, to make the banner seem to be floating between the header and footer when users scroll the webpage.
$(window).scroll(function()
{
if ($(window).scrollTop() > headerHeight)
$(".banner").css("position", "fixed");
else
$(".banner").css("position", "relative");
}
I want the banner to be auto scrolled/floated/moved when user scrolls the browser window. The code works fine: it makes the banner float/move and stops the banner from floating/moving over the header. But I need to add one more condition: the banner must stop floating before the end of webpage is reached because a footer is present. This code now causes the banner to be moving/floating over the footer when user reaches the bottom of the page.
Can anyone help me in getting this condition included in the if block as an or condition?
A: You could probably just contain the banner within a container which touches the bottom of the header and the top of the footer, then enable scrolling within it's extents.
A: I would recommend you use the stickyfloat jquery plugin!
Demo: http://jsbin.com/eqihef
http://plugins.jquery.com/project/stickyfloat
It's a great little plugin which gives you a lot of control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: sqljdbc : JDBC driver sqljdbc.jar Vs sqljdbc4.jar I have a query regarding the jars sqljdbc.jar and sqljdbc4.jar which are used to connect to MS SQL Server 2005 for the systems where the JDK version 1.5 & 1.6 respectively. Now I would like to know, how these jars interpret the column whose datatype is 'XML' in one of the DB table in MS SQL Server 2005, when trying to access from both the systems where the JDK versions are 1.5 & 1.6 using sqljdbc.jar & sqljdbc4.jar respectively?
Is there any difference in interpreting the XML data type using sqljdbc.jar and sqljdbc4.jar?
Thank you very much in advance,
Regards,
Laaksha
A: From http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/8c1721c1-781f-4ad0-b656-a2494f3c3978:
"These two class libraries are used to support different scenarios. The sqljdbc.jar class library provides support for JDBC 3.0 and the sqljdbc4.jar class library provides support for JDBC 4.0."
A: If you are using Java7+, you will need to use sqljdbc4.jar. Using the sqljdbc.jar will result in:
Caused by: java.lang.UnsupportedOperationException: Java Runtime Environment (JRE) version 1.7 is not supported by this driver. Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Tracking marker clicks on Google Maps API - Analytics I'm trying to track the amount of people clicking on map markers with google Analytics, is this possible and if so, what are my options?
Thanks in advance!
A: The updated GA implementation is the following:
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
Example:
google.maps.event.addListener(marker, 'click', function() {
ga('send', 'event', 'Videos', 'play', 'Fall Campaign');
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
A: I don't know why this isn't better documented but here's how I got it to work in the end. Add gaq.push to the addListener function for the marker click. See the documentation linked by antyrat.
google.maps.event.addListener(marker, 'click', function() {
gaq.push(['_trackEvent', 'category', 'action', 'opt_label']);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
A: You can do this using Event Tracking functionality at Google Analytics. More about tracking system you can find at official documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Detect if div is visible in browser window I have multiple collapsible divs like so
+--------------+
| Div 1 |
+--------------+
| Div 2 |
+--------------+
| Div 3 |
+--------------+
Now when I click on one of the divs it expands
Question: How do I detect that expanded div was expanded over browser window (bottom border)?
A: You could try this, it's an untested idea off the top of my head so some modification may be needed.
var div1Height = $("#div1").height();
var div2Height = $("#div2").height();
var div3Height = $("#div3").height();
var windowSize = $(window).height();
//assign function for on click (you'll want to change this)
$("#div1, #div2, #div3").click(function(e){
if(div1Height > windowSize){
//assuming div1 is at the top
console.log("div 1 passing extents");
}
if((div2Height + parseInt($("#div2").position().top) > windowSize){
console.log("div 2 passing extents");
}
if((div3Height + parseInt($("#div3").position().top) > windowSize){
console.log("div 3passing extents");
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: append text to a file with powershell I have the following powershell command that recursively loops through all .sql files in a folder ($ScriptFolder) and appends it to another sql file ($TargetFile).
Get-ChildItem -path "$ScriptFolder" -recurse |?{ ! $_.PSIsContainer } |?{($_.name).contains(".sql")} | %{ Out-File -filepath $TargetFile -inputobject (get-content $_.fullname) -Append }
What I would like to do as each .sql is appended to the target file, add text to the target file at the point .sql is appended to it and add text after the .sql is appended to the target file.
I am new to powershell, so could anyone outline how i might do this? Thanks
A: Here's something that might do the trick for you:
Get-ChildItem -recurse -include "*.sql" |
Foreach-Object { Add-Content -Path $targetFile -Value "-- Begin $($_.FullName)--`r`n$(Get-Content $_ | Out-String)--End $($_.FullName)--`r`n"; }
That code will loop through all .sql files recursively, adding their contents to $targetFile as you did. It wraps each addition with --Begin <full path>-- and --End <full path>--. FYI, I pipe the output of Get-Content to Out-String because Get-Content returns an array of objects. If you leave out that pipe, this code will strip newlines from your source files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: About catching exception good practices I'm writing a little program in C++11 and really use exceptions for one of the first time.
I've got a question about how to catch the exceptions efficiently, and after some googling I still don't have the answer.
Here is the question :
What is the more efficient (or recommended) between catching the exception by (const?) lvalue reference, or by (const?) rvalue reference?
In code this give :
1)
try { throw std::exception{"what"}; }
catch (std::exception& ex) {}
2)
try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}
3)
try { throw std::exception{"what"}; }
catch (std::exception&& ex) {}
4)
try { throw std::exception{"what"}; }
catch (const std::exception&& ex) {}
A: You should catch by const lvalue reference (2):
try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}
Rationale:
In C++11 it is possible (via use of shared_future) that two threads could be unwinding the same exception at the same time. This can happen in your code even if you are not aware of shared_future being used, unless you control the entire application.
If two threads are caught unwinding the same exception simultaneously, and one or both of the threads modifies the exception, then you've got a race condition.
So as long as you don't have to modify the exception object in the catch clause, let the compiler enforce that policy for you - catch by const&. If you really do need to modify the exception, then make a copy of it, modify the copy and throw the copy. You can do this by catching by value if you are sure this won't slice your exception object (which is not usually the case if you are catching std::exception).
A: I suppose that exception should be caught in usual manner by lvalue-reference. Here's good explanation of rvalues-references use
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Multiple video sources combined into one I am looking for an efficient way to do the following:
Using several source videos (of approximately the same length), I need to generate an output video that is composed of all of the original sources each running in its own area (like a bunch of PIPs in several different sizes). So, the end result is that all the original are running side-by-side, each in its own area/box.
The source and output need to be flv and the platform I am using is Windows (dev on Windows 7 64bit, deployment to Windows server 2008).
I have looked at avisynth but unfortunately it can't handle flv and non of the plugins and flv splitters I have tried worked.
My current process uses ffmpeg in the following manner:
*
*Use ffmpeg to generate 25 png's per second per video, resizing the original as needed.
*Use the System.Drawing namespace to combine each set of frames into a new image, starting with a static background, then loading each frame into an Image and drawing to the background Graphics object - this gives me the combined frames.
*Use ffmpeg to combine the generated images to a video.
All this is very IO intensive (which is my processing bottleneck at the moment) and I feel there must be a more efficient way to reach my goal. I do not have much experience with video processing, and don't know what options are out there.
Can anyone suggest a more efficient way of processing these?
A: Do everything inside ffmpeg. You can do a lot of things with video filters. For example to join two videos side by side:
ffmpeg -i input0.avi -vf "movie=input1.avi [in1]; [in]pad=640*2:352[in0]; [in0][in1] overlay=640:0 [out]" out.avi
@Oded: That's basically what this command does. You can remove the pad filter and change the parameters of overlay filter to move the second video wherever you like.
ffmpeg -i big.avi -vf "movie=small.avi [small]; [in][small] overlay=10:10 [out]" out.avi
The link I provided describes the filter syntax. You can chain multiple filters together:
ffmpeg -i big.avi -vf "movie=small0.avi [small0]; [in][small0] overlay=10:10 [tmp];\
movie=small1.avi [small1]; [tmp][small1] overlay=30:10 [out]" out.avi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Salesforce, implementing questionnaires We have a customer who want to implement reasonably complex questionnaires in salesforce. Currently they use excel spread sheets. The questionnaires will have text, multiple choice and yes/ no answers and they will want the ability for an admin user to add and remove questions, rules etc. The answers to some questions will mean other questions will or will not be asked. The answers will also be combined to produce a score for the user.
I never even heard about Salesforce until yesterday. I've had a look around their web site but can't find the page "Implement questionnaires like this." Is this the sort of thing salesforce can do and if so please can you point me in the direction of the documentation for developing this sort of solution.
Thanks,
Patrick
A: Salesforce doesn't provide questionaire or survey functionality on its own. You could either develop your own solution using Visualforce and Apex, or use a partner application. My company uses Zoomerang for Salesforce and it integrates nicely with Salesforce.
A: I've implemented this successfully.
*
*Create sObject that holds Questions
*Create sObject that is junction of question and user called "Answer"
*Create visualforce page that displays questions and allows the user to input answers.
A: I would recommend to use the LWC component for this or you can achive this using flows in salesforce . This will provide a very good User interface and very interactive.
You need:
1. create objects
2. refer the trailhead trainings for lwc - it explains very well
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: mysql query plans I have a list of select statements and I wish to find out their query plans. Is there an easier way instead of having to prefix each one with explain?
In Sybase you can do this by setting a flag - just wonder if there is an equivalent?
A: You can abuse the slow query log for this:
Set long_query_time = 0, this will force MySQL to log all queries in the slow query log.
Now set where you want the log to appear, see: http://dev.mysql.com/doc/refman/5.1/en/log-destinations.html
Make sure you let the slow query log put your queries in a table, this is the default in 5.1+
Now write a stored procedure like so:
DELIMITER $$
CREATE PROCEDURE run_explain_on__the_slow_query_log(IN which_db VARCHAR(512))
BEGIN
DECLARE sql VARCHAR(10000);
DECLARE done INTEGER DEFAULT 0;
DECLARE cursor1 CURSOR FOR SELECT sql_text FROM mysql.slow_log
WHERE sql_text LIKE 'SELECT%'
AND (db = which_db OR which_db IS NULL);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cursor 1;
WHILE NOT (done) DO
FETCH cursor1 INTO sql;
SET sql = CONCAT('EXPLAIN EXTENDED ',sql);
PREPARE stmt FROM sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END WHILE;
END $$
DELIMITER ;
You may need to tweak it a bit, here's the create statement of the slow_log table.
CREATE TABLE mysql.slow_log(
start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
user_host MEDIUMTEXT NOT NULL,
query_time TIME NOT NULL,
lock_time TIME NOT NULL,
rows_sent INT(11) NOT NULL,
rows_examined INT(11) NOT NULL,
db VARCHAR(512) NOT NULL,
last_insert_id INT(11) NOT NULL,
insert_id INT(11) NOT NULL,
server_id INT(10) UNSIGNED NOT NULL,
sql_text MEDIUMTEXT NOT NULL
)
ENGINE = CSV
CHARACTER SET utf8
COLLATE utf8_general_ci
COMMENT = 'Slow log';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Multiple iOS developer licenses for a company My company has an iOS developer license, and like many others we have reached the 100 UDID limitation.
Since I have about 10 more months until the next time I can delete unused UDIDs I tried purchasing another IOS developer license for my company but got rejected from Apple since my company already holds a program enrollment.
How can I bypass this issue? I really need more UDIDs so I can send my applications to testers. Do I need to open an individual iOS programing license or is there another way to enroll a company to another iOS license.
A: This has been covered here. None of the answers look particularly appealing, but I doubt you'll get other advice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pass c_str return value of temporary object to printf Is the following piece of code valid?
class A { string m_name;
public:
string getName() { return m_name; }
}
.....
printf("%s", object.getName().c_str())
......
where object.getName() returns a temporary string object.
A: The temporary string will persist for until printf() completes so yes, it is safe and legal.
A: Looks valid to me, assuming get name will return a standard string object.
A: Provided object.getName() returns by value, or by reference to something that remains valid:
yes
A: Your code as I'm writing this:
class A { string m_name;
public:
string getName() { return m_name; }
}
.....
printf("%s", object.getName().c_str())
......
You ask, is the code valid?
No, the code is not valid, because
*
*there is a missing semicolon at the end of the class definition, and
*“....” is invalid as C++ code, and
*there is a missing semicolon at the end of the printf statement.
In short, the code will not compile.
Please, in the future, post code that can be compiled, so that people who want to help you can try it out for real as-is (and be sure that it is the code that you're asking about).
Now regarding style issues.
string getName() { return m_name; }
The lack of const is ungood style.
You should make the member function const, so that it then can be called on a const object.
Also, the get prefix is stylistically an abomination, in C++. Would you write getSin? The get prefix has a purpose in Java, but in C++ it is just visual noise and textual verbosity, i.e. it is like playing with a beach ball in a fine restaurant: what was nice on the beach (Java) is not so good in the restaurant (C++).
printf("%s", object.getName().c_str());
The .c_str() call is stylistically OK, because most C++ programmers do this and know that it is OK. If if it was a rarely used construction, then it could be bad style, because then other people might waste time checking whether it is formally OK. It's formally OK because the temporary lasts until the end of the full-expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Background-Install an apk file without submit interface. What the way to do ? android Background-Install an apk file without submit interface. What the way to do it?
A: Plain simple - you can't. The closest you can get is Android Market auto-updating your apps. Non-Market apps will allways require the user to accept the permissions used by the app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Observable DataContracts and Two-Way bindings In my WPF app, I use a WCF service to fetch data.
So naturally, at some point i had "complex" objects that require a DataContract to be passed as a whole to the WPF app.
Now of course, I need to respond to changes, and I implement INotifyPropertyChanged on my ViewModels, however since some objects are actually DataContracts, I would have to recompose those so that they implement INotifyPropertyChanged.
I feel like it's messy.
What i tried to do is implement the interface directly on the DataContract definition, but I can't react properly to a change.
For example, if a Two-Way databound TextBox has its text changed, my ViewModel should react to it by changing the value in the corresponding SQL table (through the WCF service), but since the object is defined on WCF side, I can't do that in the setter of the property.
What I do for now, is subscribe to the PropertyChanged event of the DataContracts, and use reflection to know which property changed and its new value.
But those objects are held in an ObservableCollection<T>, that's a lot of events, and it feels very brittle... what if i add/remove an element from the collection for example?
I do it like this (this is bad I think):
foreach (ImageInfo imgi in (param.Images as ObservableCollection<ImageInfo>))
{
imgi.PropertyChanged += (sender, args) =>
{
object newValue = Tools.GetProperty((sender as ImageInfo), args.PropertyName);
};
}
And then I'd send it back to the WCF service.
Is there a more elegant solution to this? should I implement INotifyPropertyChanged on the ViewModel only, and recompose the DataContracts instead?
Thanks!
A: So you want a real-time system that is linked to the database by the WCF server?
What about creating Model objects, whose Get/Set methods go to/from the database?
public class MyModel : INotifyPropertyChanged
{
private IMyModelService service;
public int Id { get; set; }
public MyModel (IMyModelService wcfService, int id)
{
this.Id = id;
this.service = wcfService;
AutoMapper.Map<MyModelDTO, MyModel>(service.GetMyModel(this.Id), this);
}
public int SomeValue
{
get
{
return service.GetSomeValue(this.Id);
}
set
{
service.SetSomeValue(this.Id, value);
RaisePropertyChanged("SomeValue");
}
}
}
You could also cache object properties locally and make the WCF service calls async, which would probably improve performance, although if more than one person can be modifying a single object you might need some kind of messaging system to alert the client that MyObject has changed when another user updates a property.
The ViewModel on the client would be responsible for creating the Model, not the WCF service.
public class LoadObject(int id)
{
CurrentObject = new MyModel(serviceReference, id);
}
A: Alright so after some time thinking it through, I implemented it like this for now but it might change because I meet with an expert next monday (I'll update if he gives me a better idea).
1) The WCF service has a DataContract such as:
[DataContract]
public class MyWcfData : INotifyPropertyChanged
{
public MyWcfData()
{
MyField = "";
}
[DataMember]
public string MyField;
[DataMember]
public string MyFieldModified;
}
Note: INotifyPropertyChanged is implemented the usual way, i just left it out for readability, and because i dont have my snippets on this computer.
When GetMyData() is called on the service, it returns an instance of that class, with only "MyField" populated. MyFieldModified is left to null.
On my DAL (so client-side), where MyWcfData is recieved:
public class MyDAL
{
//... some init code
public MyWcfData GetMyWcfData()
{
MyWcfData newData = m_WcfService.GetMyData();
newData.MyFieldModified = newData.MyField;
return newData;
}
}
The point here is that the data needs to be duplicated so that i can keep track of changes, and only update a property once in the end, even if the user changed it 10 times (i just compare everytime to the original value). But I don't want to send duplicated data over the wire, so instead i do the duplication in the DAL, before any business object has access to it.
On the ViewModel of my view:
public class MyViewModel
{
//.. some init code
DelegateCommand<MyWcfData> _GetDataCommand;
public DelegateCommand<MyWcfData> GetDataCommand
{
get
{
if (_GetDataCommand == null)
_GetDataCommand = new DelegateCommand<MyWcfData>(GetData);
return _GetDataCommand;
}
}
public void GetData(MyWcfData param)
{
m_WcfData = m_DAL.GetMyWcfData();
}
}
And then last but not least, in my XAML, i bind to MyFieldModified (in Two-Way binding) in a TextBox. I then use System.Windows.Interactivity to call a DelegateCommand upon the TextChanged event.
When that last command is fired, i put the change in a Queue (to keep track of the changes order) and i send it back to the Wcf service for data persistency when the user presses a Save button.
Note: I actually use a custom-made ObservableQueue<T> so that i can keep track of the number of changes and enable the save button accordingly through binding. I will make a blog post about it so stay tuned ;-)
Note2: I gave up on making it save every tiny change made instantly, even though in this case it would have worked because it's not a feature much used, and few changes are expected; but as pointed out in other answers it's bad practice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get duplicate attributes in xml using schematron I am writing few checks for XML file using schematron.
I want to write down a check so that there must be no duplicate attribute 'id' in any tag across the xml.
Please note, attribute 'id' can occur in any element across the xml.
I found something related to this but that was case for siblings only which used preceding-sibling function.
Please suggest.
A: This is the approach I use. It's horribly inefficient to execute an XPath statement across the entire document for every element that might have an id attribute. So, I use an xsl:key. The solution below uses ISO Schematron.
<schema xmlns="http://purl.oclc.org/dsdl/schematron"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
queryBinding="xslt2" schemaVersion="ISO19757-3">
<xsl:key name="xmlid" match="*[@id]" use="@id"/>
<pattern id="duplicate_id">
<rule context="*[@id]">
<assert test="count(key('xmlid', @id)) = 1">
Duplicated id in element "<name/>" - "<value-of select='@id'/>".
</assert>
</rule>
</pattern>
</schema>
The key caches all the elements that have an id attribute. The rule then applies to all elements with that attribute. The assertion simply counts the number of matches against the id attribute and produces an error message if the count isn't one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to supress or correct this? make: warning: Clock skew detected. Your build may be incomplete
Possible Duplicate:
Compling C++ on remote Linux machine - “clock skew detected” warning
I tried everything about this:
I am using a cross compiler to build on x86 and run (execute) on a different platform. I am getting this warning.
I tried everything including:
Error in Fedora Linux -- clock skew detected
and also changing the timestamps of all executables (inside the target platform)
I need two things:
1) any soutions to this?
2) How to supress this warning
Thanks in advance
FYI: I am using RPM build process to build my executables
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PrimeFaces 3.0.M3 I have been using PrimeFaces-2.0 with Tomcat 6.0 and now, I want to migrate to PrimeFaces 3.0 M3. I've added the jar into the classpath and into the /WEB-INF/lib but when I launch the application I have this error message 'java.lang.ClassNotFoundException: org.primefaces.resource.ResourceServlet' first and when I am in jsf file I can't see any component when I type 'p:(ctrl+space)'. I am using this namespace url 'xmlns:p="http://primefaces.prime.com.tr/ui"'. I don't know where the problem is.
Thks
A: XML namespace url changed to "http://primefaces.org/ui" and the ResourceServlet is not needed anymore, so you usually can just remove it from your web.xml
A: what u need to do is
<html xmlns ="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
Your Coding...
.....
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error:byte external allocation too large for this process Project was working fine suddenly it started giving this error. i even increased memory but no help. Can any one suggest what is the problem. What can be done to free the allocations.
09-28 15:26:55.998: ERROR/dalvikvm-heap(536): 1398784-byte external allocation too large for this process.
09-28 15:26:55.998: ERROR/GraphicsJNI(536): VM won't let us allocate 1398784 bytes
09-28 15:26:56.058: DEBUG/AndroidRuntime(536): Shutting down VM
09-28 15:26:56.058: WARN/dalvikvm(536): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): FATAL EXCEPTION: main
09-28 15:26:56.468: ERROR/AndroidRuntime(536): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.helper/com.helper.TabMainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.helper/com.helper.Warehouse}: android.view.InflateException: Binary XML file line #22: Error inflating class <unknown>
--------------
09-28 15:26:56.468: ERROR/AndroidRuntime(536): Caused by: android.view.InflateException: Binary XML file line #22: Error inflating class <unknown>
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.view.LayoutInflater.createView(LayoutInflater.java:513)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at java.lang.reflect.Constructor.constructNative(Native Method)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.view.LayoutInflater.createView(LayoutInflater.java:500)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): ... 32 more
09-28 15:26:56.468: ERROR/AndroidRuntime(536): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.Bitmap.nativeCreate(Native Method)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:488)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:462)
09-28 15:26:56.468: ERROR/AndroidRuntime(536): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:323)
MyXML.xml-------- if i remove listview it works fine
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_width="fill_parent">
<LinearLayout android:layout_width="fill_parent" android:id="@+id/linearfullview" android:layout_height="400sp"
android:background="@drawable/background_full_view" android:layout_alignParentTop="true"/>
<LinearLayout android:layout_width="wrap_content" android:layout_height="180sp"
android:layout_alignParentBottom="true" android:layout_marginTop="20sp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:gravity="bottom"
android:layout_marginTop="30dp">
<ListView android:id="@android:id/list" android:layout_width="130dip"
android:layout_height="wrap_content"
android:background="@drawable/splash_plate"
android:paddingTop="2sp"
android:paddingBottom="2sp"/>
</LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="4dp"
android:gravity="bottom"
android:layout_marginTop="30dp"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:id="@+id/linearFirst"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="4dp"
android:gravity="bottom"
android:layout_marginTop="30dp"
android:visibility="invisible">
<com.tcs.mobility.widget.WheelView
android:id="@+id/firstWheel"
android:layout_height="wrap_content"
android:layout_width="100dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:id="@+id/linearSecond"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:layout_alignParentRight="true"
android:paddingTop="4dp"
android:gravity="bottom"
android:layout_marginTop="30dp"
android:visibility="invisible">
<com.tcs.mobility.widget.WheelView
android:id="@+id/secondWheel"
android:layout_height="wrap_content"
android:layout_width="100dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:id="@+id/linearThird"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="4dp"
android:gravity="bottom"
android:layout_marginTop="30dp"
android:layout_alignParentLeft="true"
android:visibility="invisible">
<com.tcs.mobility.widget.WheelView
android:id="@+id/thirdWheel"
android:layout_height="wrap_content"
android:layout_width="200dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Myclass---
public class Warehouse extends ListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Inside Warehouse");
setContentView(R.layout.warehous);
linearLayoutFirst = (LinearLayout) findViewById(R.id.linearFirst);
linearLayoutFirst.setVisibility(View.GONE);
linearLayoutSecond = (LinearLayout) findViewById(R.id.linearSecond);
linearLayoutSecond.setVisibility(View.GONE);
linearLayoutThird = (LinearLayout) findViewById(R.id.linearThird);
linearLayoutThird.setVisibility(View.GONE);
String[] names = new String[] { "Inventory Ageing", "Inventory Carring Cost", "Inventory Turns"};
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,R.layout.warehouse_list,names));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
DataCreater dataCreater = new DataCreater();
firstArray=getConvertedArray(MainActivity.custArr);
dataCreater.closeAll();
secondArray=getConvertedArray(warehouseLocArr);
thirdArray = getConvertedArray(MainActivity.marketArr);
first = (WheelView) findViewById(R.id.firstWheel);
second = (WheelView) findViewById(R.id.secondWheel);
third = (WheelView) findViewById(R.id.thirdWheel);
custStr = activateWheel(first,firstArray);
locStr = activateWheel(second,secondArray);
marStr = activateWheel(third, thirdArray);
}
}
public String activateWheel(WheelView adapter,String[] arrayL)
{
System.out.println(" adapter"+adapter);
adapter.setAdapter(new ArrayWheelAdapter<String>(arrayL));
adapter.setVisibleItems(7);
adapter.setCurrentItem(1);
str = adapter.currentText();
return str;
}
public String[] getConvertedArray(ArrayList<String>array)
{
String[] strArray = new String[array.size()];
for(int i=0; i<array.size();i++)
{
strArray[i] = array.get(i);
}
return strArray;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File get contents PHP I have a small script where I am gathering the HTML of a URL. This works fine and it brings back the HTML. The problem is, this url is rendering some DIVs after the page has loaded so I can see those DIVs when I open it in browser but not when I use curl or file get contents. What would be the solution for this?
A: No. You have no reliable chance to run javascript throught php. However, you can sniff ajax requests in your debugger and take urls & get them too. You just need to create your own parser
A:
this url is rendering some DIVs
That doesn't make any semantic sense. A url is an address of some data - which may include code and references to other URLs. The URL doesn't "render" anything.
If you mean that the page referenced by the URL renders divs - that makes a bit more sense.
It may be that the server is supplying different content based on the request headers (e.g. user-agent or cookies). Or it may be that javascript invoked from the page is rendering additional content into the HTML.
To find out which, just disable javascript in your browser. If the divs are still rendered then the server is delivering different content based on the user agent - you just need to fake the user-agent in your request.
OTOH if the content is added via javascript, then it will be a big task to implement this using PHP.
A: you may have a possibility using some javascript interpreter with the downloaded page. It's possible to use Rhino shell on the command line (and you can execute this in php via system() or shell_exec().
It seems though that you may have a hard time parsing the html and feeding Rhino just the javascript in that page (I don't see any option to parse an html file), but sure there are other js interpreters and maybe one suits your needs: wikipedia page on JS engines
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Heroku - Rails 3 to 3.1 migration issues with PostgreSQL: relation "users" does not exist I have been following documents on how to move from Rails 3 to 3.1 and make it work on Heroku. I used the manual upgrade technique given here: http://webtempest.com/upgrade-rails-3-to-3-1/
I have made some progress slowly but it has been mostly painful to get it to work with Heroku. My application works fine locally with rails 3.1 at the moment. I should probably let you know that in development mode, I am using mysql (simply because of having the option to use sequel pro and I haven't quite figured out how to use postgres locally yet). Thing is, I have had no issues pushing my app to heroku while in rails 3.0 and using it there with postgres and locally with mysql ever. It has always worked fine. However, now that I have moved to 3.1, using heroku cedar stack, I am running in to the following issue while following heroku docs: http://devcenter.heroku.com/articles/rails31_heroku_cedar
Following is the error I keep bumping in to when trying to migrate or reset my application's db after pushing the code to heroku, and also when i restart the application.
Running rake db:reset attached to terminal... up, run.9
Couldn't drop hvifyyqdjs : #<ActiveRecord::StatementInvalid: PGError: ERROR: must be owner of database hvifyyqdjs
: DROP DATABASE IF EXISTS "hvifyyqdjs">
hvifyyqdjs already exists
rake aborted!
PGError: ERROR: relation "users" does not exist
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
Any ideas as to how to overcome this issue? I am using the devise plugin for the 'users' mentioned here. My research on the issue led me to earlier believe that my migration might have not created the users table properly, however my very first migration file does create the user table
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
# t.encryptable
# t.confirmable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
# t.token_authenticatable
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
def self.down
drop_table :users
end
end
when trying to restart the app on heroku, this what i see in the logs
2011-09-28T09:55:08+00:00 app[web.1]: => Booting WEBrick
2011-09-28T09:55:08+00:00 app[web.1]: => Rails 3.1.0 application starting in production on http://0.0.0.0:33603
2011-09-28T09:55:08+00:00 app[web.1]: => Call with -d to detach
2011-09-28T09:55:08+00:00 app[web.1]: => Ctrl-C to shutdown server
2011-09-28T09:55:08+00:00 app[web.1]: Exiting
2011-09-28T09:55:08+00:00 app[web.1]: /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:962:in `async_exec': PGError: ERROR: relation "users" does not exist (ActiveRecord::StatementInvalid)
2011-09-28T09:55:08+00:00 app[web.1]: : SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
2011-09-28T09:55:08+00:00 app[web.1]: FROM pg_attribute a LEFT JOIN pg_attrdef d
2011-09-28T09:55:08+00:00 app[web.1]: ON a.attrelid = d.adrelid AND a.attnum = d.adnum
2011-09-28T09:55:08+00:00 app[web.1]: WHERE a.attrelid = '"users"'::regclass
2011-09-28T09:55:08+00:00 app[web.1]: AND a.attnum > 0 AND NOT a.attisdropped
2011-09-28T09:55:08+00:00 app[web.1]: ORDER BY a.attnum
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:962:in `exec_no_cache'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:551:in `block in exec_query'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract_adapter.rb:244:in `block in log'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.1.0/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract_adapter.rb:239:in `log'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:550:in `exec_query'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:1061:in `column_definitions'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:740:in `columns'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `block (2 levels) in initialize'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:185:in `with_connection'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:92:in `block in initialize'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/base.rb:706:in `yield'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/base.rb:706:in `default'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/base.rb:706:in `columns'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/base.rb:722:in `column_names'
2011-09-28T09:55:08+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.0/lib/active_record/base
Any help, suggestions or hints will be very appreciated.
A: I was able to solve this by myself.
One of my initializer files was doing a find_or_create_by_id which worked fine while development, but since I was now deploying on a fresh new application, the absence of tables was the source of that error, and was also blocking the migrate command from running and creating the missing tables.
It had nothing to do with syntax of PostgreSQL.
A: Look at the first error message: "ERROR: must be owner of database hvifyyqdjs"
You (or your program) are not allowed to drop it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Any HTML5 localstorage wrapper? Any library to support
*
*CURD
*Get a list, skip, limit
*Filter by field
Or should we use this as NoSql database?
A: I'd use it as a NoSQL database personally, but I'm sure you could modify this to work with it on smallish scale applications:
http://code.google.com/p/trimpath/wiki/TrimQuery
A: Try CarboStorage:
http://carbogrid.com/index.php/storage/home
A: I recently was up against the same question, and ended up writing my own:
http://morgul.github.io/dustbin/
It's heavily influenced by Riak, completely unit-tested, and about as simple as I can make it. Works well for my use cases.
If there's enough demand, I've even got a proposal for adding Link support similar to Riak. It would not be hard; I just need someone who uses it to weigh in on the proposal.
A: I know this is an old post, but it was one of the first I came across in a google search for this type of thing. The one I wound up going with is called 'StoreJS'. You can find it here. It currently has 4,250 stars on GitHub, which is awesome.
https://github.com/marcuswestin/store.js/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kohana validation without message files Is there a way to use Kohana's (3+) validation class without using message files?
[EDIT]
Here is an example:
$post = Validate::factory($_POST);
$post
->rule('username', 'not_empty')
->rule('username', 'regex', array('/^[a-z_.]++$/iD'))
->rule('password', 'not_empty')
->rule('password', 'min_length', array('6'))
->rule('confirm', 'matches', array('password'))
->rule('use_ssl', 'not_empty');
The error message will be readed from message files, but I want to hardcode the error messages in source code. For example:
$post->rules->('username', 'not_empty', 'Please give your username');
A: You'd have to extend the Validation public function errors($file = NULL, $translate = TRUE) public function rules($field, array $rules) and public function rule($field, $rule, array $params = NULL) methods and implement with your own code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python subprocess dd and stdout I am using subprocess to create a random file from /dev/random using unix dd. Now, if i want the data output of dd to be written to a file instead of stdout. so here's the code am using,
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
global out_fd
out_fd.write("executing the time dd command\n")
cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random', 'bs=1M' ,'count=5']
a = subprocess.Popen(cmd_list,stdout=out_fd)
a.wait()
if __name__ == '__main__':
os_system_dd()
This doesn't print the dd output to the file and instead prints it in the stdout.
Is this a specific functionality of dd command? Or am i missing some thing about how subprocess works?
A: dd outputs its debugging information on stderr, not stdout:
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
out_fd.write("executing the time dd command\n")
cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random',
'bs=1M' ,'count=5']
a = subprocess.Popen(cmd_list,stderr=out_fd) # notice stderr
a.communicate()
if __name__ == '__main__':
os_system_dd()
A: The reason nothing gets written in the file is because its written to stderr. Redirect stderr and you will get the result.
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
global out_fd
out_fd.write("executing the time dd command\n")
cmd_list = ['date'] #Your list
a = subprocess.Popen(cmd_list,stdout=out_fd, stderr=out_fd)
a.wait()
if __name__ == '__main__':
os_system_dd()
Also, flush the buffer after writing "executing the time..."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: LINQ Join query problem I have this query that I tried to join 2 tables together, one which holds the product name, and product numbers, and take a product number, and go to the other where to find a Art_no which is like the product number.
ProductNamesList = (From ProductSeries In context.Products
From ProductRevisions In context.TestResults
Where ((ProductSeries.Product = CurrentProduct) And (ProductRevisions.Art_no.Contains(ProductSeries.Product_no)))
Order By ProductRevisions.Art_no
Select ProductRevisions.Art_no).Distinct.ToList
Hope anyone can help,
Thank you.
A: Check the post : SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)
you solution is divided into two queries as below
//first get the list of product which satisfy your condition
var ids = (from p in context.Products
Where p.Product = CurrentProduct
select p.Product_no).ToList();
//second filter the revision products by using contains
var myProducts = from p in context.TestResults
where ids.Contains(p.Art_no)
Order By p.Art_no
Select p.Art_no;
A: Assuming the following class structure:
public class Context
{
public IEnumerable<Product> Products { get; set; }
public IEnumerable<TestResult> TestResults { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TestResult
{
public int ArtNo { get; set; }
}
And an instance of context:
var context = new Context
{
Products = new List<Product>
{
new Product {Id = 1, Name = "P1"},
new Product {Id = 2, Name = "P2"},
},
TestResults = new List<TestResult>
{
new TestResult {ArtNo = 1},
new TestResult {ArtNo = 2}
}
};
var currentProduct = context.Products.ElementAt(0);
This should return what you expect:
var query = from product in context.Products
from testResult in context.TestResults
where product.Id == testResult.ArtNo
&& currentProduct == product
orderby testResult.ArtNo
select product.Name;
// Returns a list with one item "P1"
var productNames = query.Distinct().ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does NHibernate say my filter isn't configured? I'm trying to use a global filter in NHibernate, and as far as I can tell I'm doing exactly what all the tutorials do, but I'm getting an exception.
My .hbm.xml file contains the following:
...
<class name="NHibernateSandbox.Foo, NHibernateSandbox" table="Foo">
...
<property column="Content" type="String" name="Content" not-null="true" length="100" />
<property column="Deleted" type="Boolean" name="Deleted" not-null="true" />
<filter name="Foo_Nondeleted" condition="Deleted = false" />
</class>
Then I have a simple test class:
Configuration cfg = new Configuration();
cfg.Configure();
using (ISessionFactory sf = cfg.BuildSessionFactory()) {
using (ISession session = sf.OpenSession()) {
session.EnableFilter("Foo_Nondeleted");
IQuery query = session.CreateQuery("FROM NHibernateSandbox.Foo");
foreach (Foo foo in query.List<Foo>()) {
Console.WriteLine(foo.Content);
}
}
}
If I remove the EnableFilter line it works as expected: both deleted and undeleted rows are printed. However, with the EnableFilter line I get an NHibernateException
No such filter configured [Foo_Nondeleted]
at NHibernate.Impl.SessionFactoryImpl.GetFilterDefinition(String filterName)
at NHibernate.Impl.SessionImpl.EnableFilter(String filterName)
at NHibernateSandbox.Program.Main(String[] args)
If I configure log4net to be verbose then I see
INFO NHibernate.Cfg.HbmBinder - Mapping class: NHibernateSandbox.Foo -> Foo
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Id -> RID, type: Int32
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Content -> Content, type: String
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Deleted -> Deleted, type: Boolean
DEBUG NHibernate.Cfg.HbmBinder - Applying filter [Foo_Nondeleted] as [Deleted = false]
What's the missing step between it "applying filter" and the filter being "configured" and available to the session?
A: It's not enough to add a filter to the class: you have to define it as well. This comes down to adding
<filter-def name="Foo_Nondeleted"></filter-def>
to the .hbm.xml file. Note that there's a catch here: although tutorials show it before the classes, it has to be placed after them in the XML or you'll get an XmlSchemaValidationException.
There's another small change which needs to be made too: even though you might have query.substitutions set up to map false to 0, it isn't applied to the filter condition, so you'll have to change the filter to
<filter name="Foo_Nondeleted" condition="Deleted = 0" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: zend 1.11 doctrine2.1.1 - EntityNotFoundException entity was not found I'm having problems loading the 5th record from my collection ($arrRoleResources) of records, after I run this, which works fine:-
$em = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('doctrine');
$arrRoleResources = $em->getRepository("AJFIT\Entities\UserRoleResources")->findAll();
When I run through this :-
foreach($arrRoleResources as $roleResource) {
self::$_objAcl->allow($roleResource->getRoleFk()->getName(),$roleResource->getResourcesFk()->getModule() . '::' . $roleResource->getResourcesFk()->getController() . '::' . $roleResource->getResourcesFk()->getAction());
}
On the 5th iteration it changes one of the related records class from an entity to a proxy which is pressnt and correct, however after stepping through the proxy (AJFITEntityUserRoleResourcesProxy) when it gets to the load function:-
private function _load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
It throws the EntityNotFoundException.
When I step through the $this->_entityPersister->load() function with in BasicEntityPersister.php on line 581:-
$entities = $hydrator->hydrateAll($stmt, $this->_rsm, $hints);
$entities returns null, and i am unsure why.
Here is my configuration:-
Root
|-----application
|-----library
|-----AJFIT
| |-----Entities (namespaces = AJFIT\Entities)
| | |-----UserResources.php
| | |-----UserRoleResources.php
| | |-----UserRoles.php
| |-----Proxies (namespaces = AJFIT\Proxies) <-auto generated
| |-----AJFITEntitiesUserResources.php
| |-----AJFITEntitiesUserRoleResources.php
| |-----AJFITEntitiesUserRoles.php
|-----Doctrine
|-----Zend
|-----ZendX
My Application configuration
[production]
autoloadernamespaces[] = "AJFIT"
autoloadernamespaces[] = "Doctrine"
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 1
resources.frontController.baseurl = "/"
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views/"
; ------------------------------------------------------------------------------
; Doctrine Database Configuration
; ------------------------------------------------------------------------------
doctrine.conn.host = '127.0.0.1'
doctrine.conn.user = 'ajfit'
doctrine.conn.pass = '*****'
doctrine.conn.driv = 'pdo_mysql'
doctrine.conn.dbname = 'ajfit'
doctrine.path.entities = APPLICATION_PATH "../../library/AJFIT/Entities"
My Bootstrap:-
/**
* Register namespace Default_
* @return Zend_Application_Module_Autoloader
*/
protected function _initAutoload()
{
$autoloader = new \Doctrine\Common\ClassLoader('Zend');
$autoloader->setNamespaceSeparator('_');
$autoloader->register();
return $autoloader;
}
/**
* Initialize Doctrine
* @return Doctrine_Manager
*/
public function _initDoctrine() {
$this->bootstrap('autoload');
// include and register Doctrine's class loader
require_once(APPLICATION_PATH . '/../library/Doctrine/Common/ClassLoader.php');
$classLoader = new \Doctrine\Common\ClassLoader(
'Doctrine',
APPLICATION_PATH . '/../library/Doctrine'
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'Symfony',
APPLICATION_PATH . '/../library/Doctrine/Symfony'
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'AJFIT',
APPLICATION_PATH . '/../library/AJFIT/'
);
$classLoader->register();
// create the Doctrine configuration
$config = new \Doctrine\ORM\Configuration();
// setting the cache ( to ArrayCache. Take a look at
// the Doctrine manual for different options ! )
$cache = new \Doctrine\Common\Cache\ArrayCache;
//$cache = new \Doctrine\Common\Cache\ApcCache;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// choosing the driver for our database schema
// we'll use annotations
$driver = $config->newDefaultAnnotationDriver(
APPLICATION_PATH . '/../library/AJFIT/Entities'
);
//$driver = new Doctrine\ORM\Mapping\Driver\XmlDriver(
// APPLICATION_PATH . '/../library/AJFIT/Mappings/XML');
//$driver = new Doctrine\ORM\Mapping\Driver\YamlDriver(
// APPLICATION_PATH . '/../library/AJFIT/Mappings/YML');
$config->setMetadataDriverImpl($driver);
// set the proxy dir and set some options
$config->setProxyDir(APPLICATION_PATH . '/../library/AJFIT/Proxies');
$config->setAutoGenerateProxyClasses(true);
$config->setProxyNamespace('AJFIT\Proxies');
// now create the entity manager and use the connection
// settings we defined in our application.ini
$connectionSettings = $this->getOption('doctrine');
$conn = array(
'driver' => $connectionSettings['conn']['driv'],
'user' => $connectionSettings['conn']['user'],
'password' => $connectionSettings['conn']['pass'],
'dbname' => $connectionSettings['conn']['dbname'],
'host' => $connectionSettings['conn']['host']
);
$entityManager = \Doctrine\ORM\EntityManager::create($conn, $config);
// push the entity manager into our registry for later use
$registry = Zend_Registry::getInstance();
$registry->em = $entityManager;
return $entityManager;
}
Please can someone help as I have been working on this for a few weeks now and i don't seem to be getting anywhere with it.
Thank-you for your time
Andrew
A: It does not directly answer your question but if I was you I would use the 'Bisna' glue for ZF and Doctrine2: https://github.com/ralphschindler/NOLASnowball
For a good tutorial video: http://www.zendcasts.com/unit-testing-doctrine-2-entities/2011/02/
The title might sound confusing but the video explains very well how to intergrate ZF and Doctrine2.
This 'glue' worked always perfectly for me and I think it might be a solution to your problem as well.
A: Thanks for your help, i have already glued doctrine 2.1.2 and zend 1.11.11 with no issues, and i found out the reason that i was recieving this error was due to the associated entity being null in the database causing the correct error.
However I am having this strange issue with an assoiative entity being a proxy class and its methods always returning null. I hope someone can shed a little light on the subject because iuts driving me insane.
i am calling this code:-
$arrRoleResources = $em->getRepository("AJFIT\Entity\UserRoleResources")->findAll();
foreach($arrRoleResources as $roleResource) {
$name = $roleResource->getRoleFk()->getName();
}
UserRoleResources Entity:-
namespace AJFIT\Entity;
/**
* UserRoleResources
*
* @Table(name="user_role_resources")
* * @Entity(repositoryClass="AJFIT\Repository\UserRoleResources")
*/
class UserRoleResources
{
/**
* @var UserRoles
*
* @ManyToOne(targetEntity="UserRoles")
* @JoinColumn(name="role_fk", referencedColumnName="pk")
*
*/
private $roleFk;
/**
* Get roleFk
*
* @return UserRoles $roleFk
*/
public function getRoleFk()
{
return $this->roleFk;
}
}
UserRole Entity:-
namespace AJFIT\Entity;
/**
* UserRoles
*
* @Table(name="user_roles")
* * @Entity(repositoryClass="AJFIT\Repository\UserRoles")
*/
class UserRoles
{
/**
* @var string $name
*
* @Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var integer $pk
*
* @Column(name="pk", type="integer")
* @Id
* @GeneratedValue(strategy="IDENTITY")
*/
private $pk;
/**
* Get name
*
* @return string $name
*/
public function getName()
{
return $this->name;
}
}
I have followed the zf-boilerplate precompiled example, and i am able to post my config if required. Thanks
:-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a parameterized rdlc report with reportviewer in an MVC project? How can I create a parameterized RDLC report with reportviewer control used?
and how to do it with entity DataSource?
I need to display the report through ReportViewer control in my MVC3 application.
A: You will need to use a WebForms page instead of an MVC view if you are using the Report Viewer Control, you can create a web forms page in an MVC application just fine.
Once you have the WebForms page you can use entity data sources as well in the RDLC editor (but not before the web forms page is created). In fact, I have a .aspx page in one of my applications just because the RDLC designer requires it for me to see the entity options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change the name of "ReturnUrl" query string key in ASP.NET's forms authentication? When you use ASP.NET's Form Authentication, a query string key would be passed to login page, which is named "ReturnUrl".
For example, if you're not logged in already and you want to see a secure page like http://www.example.com/securepage.aspx, you would be redirected to:
http://www.example.com/login.aspx?ReturnUrl=securepage.aspx
(Or something like that, I'm not pretty sure about ReturnUrl value).
Now, Is there a way to change this ReturnUrl name, to something like path for example? Do we have a kind of configuration in web.config for that?
A: Add this key to the appSettings section of your web.config
<add key="aspnet:FormsAuthReturnUrlVar" value="path" />
A: Probably in the easy way you can't do this, because it's hardcoded constant inside of System.Web assembly:
internal static string GetReturnUrl(bool useDefaultIfAbsent)
{
FormsAuthentication.Initialize();
HttpContext current = HttpContext.Current;
string str = current.Request.QueryString["ReturnUrl"];
// ....
}
But probably you can use some Url rewriting.
Also, check this post on SO: rewrite url. asp.net c#
A: The FormsAuthentication class is sealed which means you cannot inherit and override from it. Also, it is hard coded to read the request["RETURNURL"] query string parameter.
Why would you want to?
A: I just want to provide reason why we need to change this parameter name (web form scenario):
I also need to change the "ReturnUrl" for mocking up authentication when creating plugin for umbraco.
umbraco is using membership api and their login.aspx is using "redir" instead of "ReturnUrl", in order to make my solution as small as possible and as independent as possible from umbraco, I need to mock up the workflow for authentication.
Since I cannot change this parameter name, well.... I'll have to readjust.
A: Of course you can change it. Just add a Global.asax to your project and change the Response.RedirectLocation property during the Application_EndRequest event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is it possible to wait on a task from a thread other than the parent thread? I need to wait on a task that I created in the production code from the test code. Is it possible to do that? I am using Nunit framework for testing.
A: You should be able to Task.Wait from any thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WPF Datagrid: Lazy Loading / Inifinite scroll I fill the Datagrid with 250 rows. When the user scrolls down using the scrollbar (below 75% for example), I want to fetch the next 250 rows from the database, and so on. The idea is that the grid could have millions of results and we don't want to load them all, until the user requests them. Is there an existing mechanism for this?
EDIT: Because there seem to be a lot of confusion: I'm not looking for the standard data virtualization solutions, I already use them. But they all require you to specify the number of 'virtual rows' in advance, and that query is to costly for me. The reason why they require it is because it's makes it so much easier to calculate the current page/offset/etc when you know the total items in the grid. But it is a very costly sql-query to calculate that amount, so I want to migrate to another solution where I can skip the COUNT() query.
A: So looks like Virtualization property of DataGrid wouldn't help you because it requires a full data set to be in the ItemsSource.
So to have in place a data lazy loading (See an article Data Virtualization) You can handle ScrollViewer.ScrollChanged event and apply a classical server-side paging approach. Basically you have to define and calculate such sings like Page Size, Page Number, Sort Order in this way you can request from a data base a required data set and show it on UI. Each time when Current Page Number or Sort Order is changing you need to request a data and update ItemsSource of the grid, also perhaps you need to restore Scroll Position as well but I'm not sure in this.
*
*Calculate number of visible items
*Do a data request to database usign parametrized query with parameters like PageNumber, PagiSize
*Update DataGrid ItemsSource by a just loaded data items
I believe a main challenge would be to calculate a value of Page Size, Current Page Number. I believe Logical Scrolling mode would help you in this.
A: Set DataGrid's EnableRowVirtualization property to true
Rows will therefore be loaded when user scrolls, so only the visible rows will actually be loaded
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Save belongs_to ID in a form, without using a hidden field? I am trying to work out the best way to save a belongs_to record ID, whilst creating a new child record. I am currently using a hidden field to retain the parent's ID.
Can you think of a better way to accomplish this save of the parent's ID (without using a hidden field)?
Here'a a snippet of my routes...
resources :kids
resources :parents do
resources :kids
end
Here's my parent model...
class Parent < ActiveRecord::Base
has_many :kids
accepts_nested_attributes_for :kids
end
Here's my kid model...
class Kid < ActiveRecord::Base
belongs_to :parent, :autosave => true
end
Here's my view's form when creating a new kid...
<%= form_for(@kid) do |f| %>
%= f.hidden_field :parent_id, :value => @parent.id %>
<%= f.label :title, 'Title' %>
<%= f.submit %>
<% end %>
Which then gets passed to the create (POST) method...
def create
@kid = Kid.new(params[:kid])
@parent = Parent.find(@kid.parent_id)
@kid.save
# etc...
end
A: If you drop the first line of your routes example, to just
resources :parents do
resources :kids
end
Now you don't have the ambiguity of calling the KidsController without a parent. Your route match behaves like
/parents/:parent_id/kids
Now, in your KidsController, you can do
def create
@parent = Parent.find(params[:parent_id])
@parent.kids.create( params[:kid] )
#...
end
The new kid gets its parent auto assigned when you create it via the has_many collection
A: Yes Nested resources is one of the good way but in your case you can also use "field_for".
A: If you don't want to pass it in as a hidden field, I'd recommend using nested resources, you could keep the parent_id in the URL and have parents/1/kids as your path. Then, in the KidsController, you'll need to load your parent resource and associate it with the Kid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Floating point error in representation? when i make this multiplication
0.94 * 8700
the output is
8177.999999999999
but it should have been
8178
i'm using java , but i don't think this error is related to a particular Programming language
now my question is ... why this happened ?? and what other numbers (just as an example) cause the same error?
A: The specific reason in your case is that the real number 0.94 cannot be represented exactly in a double precision floating point. When you type 0.94, the actual number stored is 0.939999999999999946709294817992486059665679931640625.
A: It isn't an error. IEEE floats can't represent decimal numbers exactly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL: Problems with hosts I have a MySQL server running on my Windows machine, and I wanted to add users capable of connecting from any host to it. In order to do so I used the statement
CREATE USER 'user_name'@'%' IDENTIFIED BY 'user_pw'
but when I try to connect locally with this new user, it fails. Right now I solved the problem by calling CREATE USER twice, the first using '%' as host and the second using 'localhost', but I'd like to know if there's another solution or some option I have to change on the server
A: Taken from here:
After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts:
mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
-> WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
-> WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';
Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.
It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 5.4.4, “Access Control, Stage 1: Connection Verification”.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i get id/ generate id of dynamically generated elements in html using jquery? Hi i have a student profile form where student can fill their details.
Student can add school, add high school and add college dynamically by clicking add school, add high school and add college anchor tag.
Code for this form is as below
<script type="text/javascript">
$(document).ready(function () {
$('.studentprofileupdateBody a').click(function () {
console.log('ok');
var $tr = $(this).closest('tr').prev()
var clone = $tr.clone();
$tr.after(clone);
});
});
</script>
<form method="post" action="">
<table width="100%">
<tr>
<td>
<div id="Education">
<table class="Studentprofile" id="tblEducation">
<tr>
<td colspan="2"><br/> Education Details</td>
</tr>
<tr id="schoolRow" name="schoolRow">
<td class="studentprofileupdateHead" >
<label for="schools">Schools:</label>
</td>
<td class="studentprofileupdateBody" id="schools">
<input type="text" id="s1" name="s1" title="S1"></input>
<select name="selSYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add Schools</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr id="highschoolRow" name="highschoolRow">
<td class="studentprofileupdateHead" >
<label for="highschool">High School:</label>
</td>
<td class="studentprofileupdateBody" id="highschool">
<input type="text" id="hs1" name="hs11" title="HS1" />
<select name="selHSYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>>
<br><br/>
<hr class="profileSubSection"/>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add High Schools</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr id="collegeRow" name="collegeRow">
<td class="studentprofileupdateHead" >
<label for="college">College:</label>
</td>
<td class="studentprofileupdateBody" id="college">
<input type="text" id="co1" name="co1" title="CO1"/>
<select name="selColYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>
<br><br/>
<hr class="profileSubSection"/>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add College</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<input type="submit" id="saveStudentEducationInfo" name="saveStudentEducationInfo" title="Save Education Info" value="Save Details" />
<input type="submit" id="cancelStudentEducationInfo" name="cancelStudentEducationInfo" title="Cancel Education Info" value="Cancel" />
</td>
</tr>
<tr>
<td colspan="2"><br/><br/></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
It works perfect and add any no of elements dynamically but when i see the page source of this page i get to know that its not generating new elements id.
It looks like this..
Generated New elements but by viewing source code of this page it gives,
<form method="post" action="">
<table width="100%">
<tr>
<td>
<div id="Education">
<table class="Studentprofile" id="tblEducation">
<tr>
<td colspan="2"><br/> Education Details</td>
</tr>
<tr id="schoolRow" name="schoolRow">
<td class="studentprofileupdateHead" >
<label for="schools">Schools:</label>
</td>
<td class="studentprofileupdateBody" id="schools">
<input type="text" id="s1" name="s1" title="S1"></input>
<select name="selSYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add Schools</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr id="highschoolRow" name="highschoolRow">
<td class="studentprofileupdateHead" >
<label for="highschool">High School:</label>
</td>
<td class="studentprofileupdateBody" id="highschool">
<input type="text" id="hs1" name="hs11" title="HS1" />
<select name="selHSYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>>
<br><br/>
<hr class="profileSubSection"/>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add High Schools</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr id="collegeRow" name="collegeRow">
<td class="studentprofileupdateHead" >
<label for="college">College:</label>
</td>
<td class="studentprofileupdateBody" id="college">
<input type="text" id="co1" name="co1" title="CO1"/>
<select name="selColYear">
<option value="0">-Select-</option>
<option value="1">2010</option>
<option value="2">2009</option>
<option value="3">2008</option>
<option value="4">2007</option>
<option value="5">2006</option>
<option value="6">2005</option>
<option value="7">2004</option>
<option value="8">2001</option>
<option value="8">2000</option>
<//select>
<br><br/>
<hr class="profileSubSection"/>
</td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<a href="#">Add College</a>
</td>
</tr>
<tr>
<td colspan="2"><br/><hr class="profileUpdate"/><br/></td>
</tr>
<tr>
<td class="studentprofileupdateHead" >
</td>
<td class="studentprofileupdateBody">
<input type="submit" id="saveStudentEducationInfo" name="saveStudentEducationInfo" title="Save Education Info" value="Save Details" />
<input type="submit" id="cancelStudentEducationInfo" name="cancelStudentEducationInfo" title="Cancel Education Info" value="Cancel" />
</td>
</tr>
<tr>
<td colspan="2"><br/><br/></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
I want my code to generate new id for each element to distinctly identify each element by its id.
How can i get id for each element?
A: You are using .clone method, add thats copy everything...
You can modify the id where are using that methor, something like this:
$(document).ready(function () {
$('.studentprofileupdateBody a').click(function () {
console.log('ok');
var $tr = $(this).closest('tr').prev();
var clone = $tr.clone().attr("id","new-id");
$tr.after(clone);
});
});
EDIT: To have dynamic id for each row('input' and 'tr'), you can do this:
$(document).ready(function () {
var dynamicId, inputName, numberEachType;
$('.studentprofileupdateBody a').click(function () {
console.log('ok');
var $tr = $(this).closest('tr').prev();
numberEachType = $('table#tblEducation tr[name="'+$tr.attr('name')+'"]').length;
dynamicId = $tr.attr('name') + numberEachType;
var clone = $tr.clone().attr('id',dynamicId); //dynamic ID at <tr>
inputName = clone.find('input').attr('name');
dynamicId = inputName.substring(0,inputName.length-1) + (numberEachType+1);
clone.find('input').attr('id',dynamicId).attr('name',dynamicId).attr('title',dynamicId.toUpperCase()); //dynamic ID, Name and title at <input>
$tr.after(clone);
});
});
Try an example here http://jsfiddle.net/expertCode/NT4Zr/ and see the source code, if it's this what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reading Font Colour Information From a PDF I am working on a piece of software that analyses PDF files and generates HTML based on them. There are a number of things out there that already do this so I know it is possible, I have to write my own for business reasons.
I have managed to get all the text information, positions, fonts out of the PDF but I am struggling to read out the colour of the text. I am currently using PDFMiner to analyse the PDF but am beginning to think I will need to write my own PDFReader, even so, I can't figure out where in the document the Colour information for text is even kept! I have even read the PDF spec but cannot find the information I need.
I have scoured google, with no joy.
Thanks in advance!
A: The colour for text and other filled graphics is set using one of the g, rg or k operators in the content stream object in the PDF file, as described in section 4.5.7 Color Operators in the PDF reference manual.
The example G.3 Simple Graphics Example in the reference manual shows these operators being used to stroke and fill some shapes (but not text).
http://www.adobe.com/devnet/pdf/pdf_reference.html
When parsing a PDF file yourself you start by reading the trailer
at the end of the file which contains the file offset of the
cross reference table. This table contains the file offset of
each object in the PDF file. The objects are in a tree structure with references
to other objects. One of the objects will be
the content stream. This is described in sections 3.4 File Structure
and 3.6 Document Structure in the PDF reference manual.
It is possible to parse the PDF file yourself but this is
quite a lot of work. The content
stream may be compressed, contain references to other objects,
contain comments, etc. and you must handle all of these cases.
The PDFMiner software is already reading the content stream. Perhaps it
would be easier to extend PDFMiner to report the colour
of the text too?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: AjaxControlToolkit AnimationExtender - show animation on FormView Insert/Update In my application, I have a FormView which allows Insert's and Update's. I want to show a message which dissappears after about 2-3 seconds whenever they insert or update. I figured the AnimationExtender from the AjaxControlToolkit would be the best way of doing this, but I can't figure out how to get that animation to fire when a FormView is updated/inserted. Any ideas?
A: Have you tried calling the animation in the ItemInserted or ItemUpdated events for the FormView? That sounds like it would do the trick for you. They fire every time an Update or Insert occurs from that control.
Alternately, you could just set the TargetControlID of your AnimationExntender to the id of your Update / Insert button (the one's on your FormView with CommandName set to "Insert" or "Update"), then just specify your desired animation in the OnClick event:
<ajaxToolkit:AnimationExtender ID="myAnimExtender"
runat="server" TargetControlID="updateBtn">
<Animations>
<OnClick> ... </OnClick>
</Animations>
</ajaxToolkit:AnimationExtender>
Note that this technique requires you to have two AnimationExtenders, one for the Delete button and one for the Update button.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Load Testing of a web page or mySQL database I have a page, and at a time 1000 of entries to this form has to be made. For Ex: a scenario like the following- number of users accessing or entering data into a single web page from different locations.
so this scenario has to be generated to test the load. Manually entering is tedious, so is there any tool for entering such datas.
A: You can find some tools for this in wikipedia:
http://en.wikipedia.org/wiki/Load_testing#Software_load_testing
I know some people using JMeter for this with success.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apply mercurial bundle file on different changeset TLDR: I have an HG bundle with parent X, but revision X does not exist in my repo. However, I am sure that the files of revision Y are identical to revision X. How do I apply the bundle?
Background:
I use hgsubversion to interact with an SVN repo.
There were some changes I did not want to commit. hgsubversion does not support partial pushes.
I used to workaround by manually creating temporary exports/patch files, or manually restoring .orig files (result of hg revert).
In this case I committed the changes I did not want to push, then used hg strip, then pushed, then tried to use hg unbundle .hg/strip-backup/file.
Problem: hgsubversion replaces the original changeset with a new one it imports from SVN after it's committed it. Result: the changeset ID changes. This is a problem because now hg unbundle no longer works, as it relies on the parent changeset being there (but it's been stripped).
Ironically, hgsubversion itself uses strip and thus has a backup file I can use to strip the new rev, add the stripped old revision, then apply the bundle with my revisions, export the patch, strip both, and restore the SVN revision. But this sounds... extremely painful and stupid. Is there nothing better I can do?
(hg transplant doesn't seem to like the bundle without having the parent in the repo, either)
A: It's effectively impossible to use a bundle without the bundle's precise parent changesets. Bundles consist of compact binary deltas that can only be applied to the precise binary source. There is no 'context' available that would allow Mercurial to guess how to apply them to other revisions the way patch does. In core Mercurial, this is never an issue because changesets are never removed, but extensions like hgsubversion and mq break the rules.
(If you can recover the stripped changesets from a backup bundle in .hg/strip-backup, you can then rebase your changes and strip again.)
A: Background: After hitting an issue with hgsubversion pushing only 1 revision successfully, I got lazy in my commits (partial commits are possible if you update to the latest revision you want to push), and ended up starting to commit everything. So I killed the push and for the first time it failed to keep my later revisions.
I tried recover, but that was not able to find the parent commit. What worked for me was restoring the ...-backup.hg file (there was a ...-temp.hg file in strip-backup too).
The strange thing (which is why I'm answering this) is that it only gave me a warning about the parent not being there (I have no idea why)...
warning: ignoring unknown working parent d5663567bc4b!
adding changesets
adding manifests
adding file changes
added 21 changesets with 1255 changes to 941 files
(run 'hg update' to get a working copy)
BTW, I'm running Mercurial version 2.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Saving audio files in document's folder of iPhone and later delete it when uploaded to the server? I have a situation where I will be recording audio files and save it into the documents folder of the app until the user uploads it to the server. The audio recorder will record the sound and it will save the file in the documents folder as he comes out of the audio recording screen. Any suggestions?
Thanks
A: Path to the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Saving the data (an NSData) to the documents directory:
BOOL status = [NSDictionary writeToFile:filePath atomically:YES];
Deleting the file after the upload the the server:
BOOL status = [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compiling mDNSResponder for Linux? I've been trying to compile the open source Bonjour framework developed by Apple for Linux. The problem I have is that when I run make with the option os=linux I get the following compile error:
struct sockaddr has no member named 'sa_len'
I've checked the struct sockddr and it indeed has no member named sa_len... So I'm confused as to why the framework is thinking that it should do!
Could anyone please give me some advice as to how I should be compiling mDNSResponder for Linux? Many thanks.
A: Looking in mDNSUNP.h one can see that if sa_len does not exist (such as on Linux), a macro NOT_HAVE_SA_LEN should be defined. If it's not defined in your case, try adding -DNOT_HAVE_SA_LEN to your compilation flags.
A: The Linux implementation of sockaddr doesn't have sa_len as a member, but the FreeBSD version does. Apple's implementation is based off of the FreeBSD version (parts of OS X pull from FreeBSD and NetBSD), hence why you're receiving that error. You can use an #ifdef to workaround it or add the compilation flag, as previously suggested.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I have the same mapping value with different param in a different Spring controller? Is there any way to accomplish something like this:
I have a form used for navigation :
<form action="mapping.do">
<input type="submit" value="menuOption01" />
<input type="submit" value="menuOption02" />
</form>
The PageController class is too big and has too many dependancies, I need to add another menu option but don't want to add to the complexity. I'd like to have a method in another controller which handles the new menu option.
Trying this gives me a Spring configutation error (There is already handler mapped):
@Controller
@SessionAttributes(types = { Entity.class })
class PageController {
@RequestMapping(params = "menuOption01", value = "mapping.do")
public String viewPage(@ModelAttribute final Entity entity) {
...
return "view";
}
... // another 5000 lines of code
}
@Controller
class OtherController {
@RequestMapping(params = "menuOption02", value = "mapping.do")
public String viewOtherPage(@ModelAttribute final Entity entity) {
...
return "otherview";
}
}
A: I faced a similar situation so we made the following default handler for these types of methods:
@RequestMapping(method = RequestMethod.POST, params = SIDE_TAB, value = "sideMenuController.xhtml")
public ModelAndView changeSelectedTab(@RequestParam(SIDE_TAB) String sideTab) {
return new ModelAndView("redirect:/location/" + Utils.toCamelCase(sideTab) + ".xhtml");
}
Our pages then had the following:
<input type='submit' name='side-tab' value='$value' />
This of course meant that we had to have a naming standard for the files themselves, but that was quite easy to ensure happened (i.e. "Event History" would go to eventHistory.xhtml, "Create New Entity" would go to "createNewEntity.xhtml", etc....)
A: Not directly, but:
*
*You can include that param in the url: value=/mapping/parameter/ and /mapping/otherparameter. (The .do extension is a bit obsolete btw)
*Use an if clause - pass the two params with @RequestParam("param", required=false) String param and use if (param != null) viewPage();
*You can have one method that takes HttpServletRequest and checks whether a parameter with a given name exists (using request.getParameter("foo") != null)
A: You can use parameter per method mapping. See my question and answer:
*
*@RequestMapping with "params" on same URL in different classes cause "IllegalStateException: Cannot map handler" in JUnit with SpringJUnit4ClassRunner
*https://stackoverflow.com/a/14563228/173149
Just use these classes:
<bean name="handlerMapping"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean name="handlerAdapter"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do i split this array into two? I have this array.
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
[isAlphaLower] =>
[isLength] =>
)
[email] => Array
(
[isEmail] => 1
)
[pPhone] => Array
(
[isPhone] =>
)
)
i want to split the array into two.
1. array with all boolean value true
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
)
[email] => Array
(
[isEmail] => 1
)
)
2. array with all boolean value false
Array
(
[name] => Array
(
[isAlphaLower] =>
[isLength] =>
)
[pPhone] => Array
(
[isPhone] =>
)
)
How do i do it?
thank you..
A: *
*initialize the two new arrays
*foreach the input array
*foreach the inner array of each input array entry
*according to the value set the one or the other of the two new arrays
*done.
Example:
$arrayTrue = $arrayFalse = arrray(); # 1
foreach($arrayInput as $baseKey => $inner) # 2
foreach($inner as $key => $value) # 3
if ($value) $arrayTrue[$basekey][$key] = $value; # 4
else $arrayFalse[$basekey][$key] = $value;
A: function is_true($var) {
return $var;
}
function is_false($var) {
return !$var;
}
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a, 'is_true');
$result_false[$k] = array_filter($a, 'is_false');
};
or
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a);
$result_false[$k] = array_filter($a, function ($x) { return !$x; } );
};
A: As your array is a 2 level array, you will need to use 2 loops.
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
if ($secondLevelValue)
$trueValues[$key][$key2] = $secondLevelValue;
else
$falseValues[$key][$key2] = $secondLevelValue;
}
}
A 3 level array would be:
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
foreach($secondLevelValue AS $key3=>$thirdLevelValue) {
if ($thirdLevelValue)
$trueValues[$key][$key2][$key3] = $thirdLevelValue;
else
$falseValues[$key][$key2][$key3] = $thirdLevelValue;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cuda segmentation fault I am programming with cuda in C. I got a segmentation fault with the code lines following:
int width = 0;
int height = 0;
// load input image
unsigned char * image_input = loadFile(&width, &height, "test.bmp");
// allocate memory for output
unsigned char * image_output = (unsigned char *) malloc(width*height*sizeof(unsigned char));
// set the size of the input and out array 2D
int size = width*height*sizeof(int);
// Allocate space on the GPU for input and output
char* GPU_input = 0;
char* GPU_output = 0;
cudaMalloc(&GPU_input, size);
cudaMalloc(&GPU_output, size);
// Copy the input data to the GPU (host to device)
cudaMemcpy(GPU_input, image_input, size, cudaMemcpyHostToDevice); //segmentation fault here
Any idea?
Thanks in advance.
A: *
*Size is sizeof(int) *H*W. (in bytes)
*Image_input is H*W. (in bytes)
You are addressing image_input beyond its size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What feature is missing in the current Platform as a Service? I have a project which is to make a "Platform as a Service" environment like Heroku, GAE or dotCloud to name a few.
One of the recurring questions I ask is "What feature is missing in the current platforms ?"
Currently most platforms allow developers to deploy their applications (PHP / Python / RoR / JAVA / ...) and manage them by a SDK, a console or an IDE plugin.
A few allow some features like :
- online IDE,
- custom domains,
- management of addons,
- logs system,
- cron tasks,
- collaborative aspect,
- ...
According to you what is your favorite feature in the current PaaS or, if it does't exist, what would you see in this type of service ?
Thank you for your explanations and your help.
Nico (French developper - hence my spelling mistakes ^^)
A: One of the main problems still not solved in cloud is the security. Every application should have data associated with that. With cloud where to store data? is it secure? can the owners of the system prepare it when some problem happens? ..
Another part is auto scaling. Can the users deploy their application and platform takes care of auto scaling load balancing etc ..
Versioning can the platform support different versions at once.
A: I think the main feature that is missing in all PaaS platforms is that they are scaling by duplication rather than parallelization. In order to scale, common platforms duplicate a worker, a service or an application and then re-aggregate this by deploying a (virtual) load balancer in front of it. Thus, the units of scale are relatively inelastic blocks (a block could also be a VM).
The ideal way of scaling should be smaller units though e.g.. threads, processes. This way scaling would leave this legacy approach towards a real elastic paradigm.
By the way: this way also the multicore-challenge could be addressed. When you have a system with 100s of cores, then probably the sole way for an application to scale is by thread or process that can be distributed over the available cores. Not by duplicating and deploying legacy load balancers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Accessing FB Graph API using Ruby 1.8 and Rails I'm adding Facebook functionality on to a site running Ruby 1.8.6 and rails 1.2.3.
Are there any gems that will let me use facebook's graph api with these versions?
A: Check out Koala - https://github.com/arsduo/koala/wiki Really a solid gem. Wait, Rails 1.2.3? Did I read it right?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Firefox, PHP Headers and application/octet-stream We have a page that outputs a file using PHP headers, so when you visit the page the download prompts up.
Randomly, the page will return a file application/octet-stream, other times it will return the correct thing.
It works prefectly in Chrome, IE, etc.
This only happens in Firefox and it is completely random.
Basically, it outputs as a application/octet-stream instead of the correct one.
After some more digging, I found the following:
http://support.mozilla.com/en-US/questions/800957
http://support.mozilla.com/en-US/questions/746116
http://support.mozilla.com/en-US/questions/699834
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I use asm function with a c - string variable instead of a string literal as an argument? I did something like this :
char command [] = "Some assmebly code";
asm volatile(command);
It didnt work. Specifically, I get the following error :
Expected string literal before command.
So, can I only use string literals with C inline assembly ? I really want to be able to use string variables like above. How can I achieve this effect ?
A: As far as I know asm code fragment are inlined during compilation phase, not run-time. Which means you can't do what you are doing.
As pmg suggested, you could do it by calling external commands, but it would mean user would need to have all the tools installed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I hide my password in my C# Connection string? I have the following connection string:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID=sa;Password=password
(.net webservice)
This can obviously be viewed simply by opening up the app.config file and looking at the configuration settings.
What I need is a way to make a hacker unable to see the password. But at the same time, leave it customisable so that it can be changed when deployed on another database.
A: First of all, don't use the "SA" account. It leaves your database wide open if someone gets the password. Use a custom account which only is allowed to do CRUD operations on a specific database.
The only way to get web.config is to hack your server. And if they have done that, you're screwed anyway.
A: Probably easiest to encrypt the connection strings within the web.config or app.config
See How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI
A: I Suggest en/decrypting the connection string. Therefore the connection string has to be set manually.
For encryption take a look at:
http://dotnet-snippets.de/dns/encrypt-and-decrypt-strings-SID205.aspx
For Custom Settings take a look at:
http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
Replace the Encrypted with the correct one at runtime:
public static void SetAppSettingValue(string Key, string Value)
{
System.Configuration.Configuration config == ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings[Key].Value = Value;
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
A: You have a number of options - the ones that I am aware of (in order of preference):
*
*Use integrated (SSPI) security where you don't need to include a password in the config file
*Encrypt the connection string (see Encrypting Configuration Information Using Protected Configuration)
*Store the username and password separately and use string formatting to construct the full connection string,
So for example the connection string might look like this:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}
I'd go for option 1, if thats not possible then option 2. I've mentioned option 3 for completeness.
Have you read Protecting Connection Information (ADO.NET)?
A: You could encrypt the connection string - then when you access the connection string, decrypt it. This isn't fool proof though as you're then stuck with the problem of where to store the key to decrypt the connection string!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: A question about Handlers in Android If I've got it right a handler works like a queue. So my simple question is if I first postDelayed and after that do I regular post. Will the second post run after the first delayed post?
handler.postDelayed(someMethod(), 10000);
handler.post(someOtherMethod());
Will the someOtherMethod() run after someMethod()
A: No it won't. The second one will be performed immediately when all pending handler requests (so on the UI thread) are done. The first will be appended after 10 seconds.
Hint: The handler takes a Runnable, so it looks like that:
handler.post(new Runnable {
public void run() {
doSomething();
}
}
Update based on comment:
The handler invokes the posted runnable on the thread on which new Handler() was called.
A: No, 2nd post will run as soon as possible (before 1st).
A: No, handler posts are asynchronous. what handler.post() does it that it adds the runnable to the message queue. handler.postDelayed() adds the runnable to the message queue immediately , but the timer will be set to delayed ms , after which the runnable will be executed.
so all post does is , to add the runnable to the message queue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to watermark some vector data in an invisible way? I have a some vector data that has been manually created, it is just a list of x,y values. The coordinate of the points is not perfectly accurate - it can be off by a few pixels and it won't make any perceivable difference.
So now I am looking for some way to watermark this data, so that if someone steal the vector data, I can prove that it's indeed been stolen. I'm looking for some method reliable enough that even if someone take my data and shift all the points by a some small amount, I can still prove that it's been stolen.
Is there any way to do that? I know it exists for bitmap data but how about vector data?
PS: the vector graphic itself is rather random - it cannot be copyrighted.
A: Is the set of points all you can work with? If, for example, you were dealing with SVG, you could export the file with a certain type of XML formatting, a <!-- generated by thingummy --> comment at the top, IDs generated according to such-and-such a pattern, extra attributes specifically yours, a particular style of applying translations, etc. Just like you can work out from a JPEG what is likely to have been used to create it, you can tell a lot about what produced an SVG file by observation.
On the vectors themselves, you could do something like consider them as an ordered sequence and apply offsets given by the values of two pseudo-random sequences, each starting from a known seed, for X and Y translation, in a certain range (such as [-1, 1]). Even if some points are modified, you should be able to build up an argument from how things match the sequence. How to distinguish precisely what has been shifted could do with a bit more consideration, too; if you were simply doing int(x) + random(-1, 1), then if someone just rounded all values your evidence would be lost. A better way of dealing with this would be to, while still rendering at the same screen size, multiply everything by some constant like 953 (an arbitrary near-1000 prime) and then adjust your values by something in that range (viz, [0, 952]). This base-953 system would be superior to a base-10 system because it's much (much much) harder to see what's happening. If the person changes the scaling, it would require a bit more analysis of values, but it should still be quite possible. I've got a gut feeling that that's where picking a prime number could be a bit helpful, but I haven't thought about it terribly much. If in danger or in doubt in such matters, pick a prime number for the sake of it... you may find out later there are benefits to it!
Combine a number of different techniques for best results, of course.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to efficiently prune a list based on "is-subset" condition? Let's suppose I am given Dictionary<int, List<int>> and I want to prune it using the following condition
*
*an item should be removed from the dictionary if there exists an itemLarger != item in the dictionary such that item.Value.Union(new[] { item.Key }) is a subset of itemLarger.Value.Union(new[] { itemLarger.Key })
That is, each item in the dictionary will be represented by a list of numbers obtained by appending the item's key to the item's value and I want to get rid of those items which are represented by a subset of some other item's representation.
Example:
var testResult = new Dictionary<int, List<int>>
{
{ 2, new[] { 3, 4 }},
{ 3, new[] { 2, 4 }},
{ 1, new[] { 2, 3, 4 }},
{ 4, new[] { 2, 3 }}
};
In this case, the only element left in the list would be {1, {2, 3, 4}}
I can't seem to find some elegant way to do it, since
*
*GroupBy does not allow me to specify which element in particular should be used as the key when I have two that should be groupped
*Distinct does not allow me to specify, in case two elements are not distinct, which of them should be kept in the list
Of course it is doable in a trivial way. I wonder if there is some nice one.
Thank you for any ideas.
A: I don't think this will be much different from the "trivial" way you meant, but here's a LINQ solution:
var sets = testResult
.Select(x => new { Key = x.Key, Set = new HashSet<int>(x.Value.Concat(new[] { x.Key })) })
.ToList();
var res = sets.Where(s => sets.Any(x => x.Set.IsSupersetOf(s.Set) && x.Key != s.Key));
var keysToRemove = res.Select(x => x.Key);
A: In my solution I check for each element x in testResult if this element is subset of any other element in testResult. If it isn't, this element pass 'where' filter in linq expression. Two last lines are conversion of result from list representation to dictionary representation.
var listResult =
(from x in testResult
where (from y in testResult
where !x.Value.Except(y.Value).Any() && x.Key != y.Key
select y).Count() == 0
select x).ToList();
var dictionaryResult = new Dictionary<int, List<int>>();
listResult.ForEach(x => dictionaryResult.Add(x.Key, x.Value));
Edit:
We could write it even shorter:
testResult = testResult.Where(x =>
(from y in testResult
where !x.Value.Except(y.Value).Any() && x.Key != y.Key
select y).Count() == 0).ToDictionary(x => x.Key, x => x.Value);
A: This might not be the most effective way but it's short and kind of readable.
var test = new Dictionary<int, List<int>>
{
{ 2, new List<int> { 3, 4 }},
{ 3, new List<int> { 2, 4 }},
{ 1, new List<int> { 2, 3, 4 }},
{ 4, new List<int> { 2, 3 }}
};
var res = test.Where(n => !test.Any(m => m.Key!=n.Key && n.Value.Intersect(m.Value).Count()==n.Value.Count) );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to avoid users adding a user stored procedure name like sp_% Someone told me that DMF management policy and condition can do this. Does anybody know how to implement this.
A: Yes, you can do this through Policy Based Management. You create a Condition for a procedure Facet with the parameter @Name to be NOT LIKE 'sp_%'. Then you create a Policy for that Condition and you can enforce this on demand or on a schedule.
A: *
*Open SQL Management Studio
*Go to "management" -> Conditions -> Create new condition
*Enter a name for the condition.
*Select Facet "Stored Procedure"
*Enter in the column "Field" @name
*Enter in the column "Operator" NOT LIKE
*Enter in the column "Value" 'sp[_]%'
*Click on OK to save
*Create a policy. Go to "management" -> Policy -> Create new Policy
*Enter a name for the Policy
*Select the name of the condition in the dropdown menu "check condition"
*Set "Evaluation Mode" to 'On change:Prevent'
*Enable the policy
*Click on OK to save and enable the policy
*Test the policy by entering a new query
CREATE PROCEDURE sp_test
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SET NOCOUNT ON;
SELECT FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName
AND EndDate IS NULL;
GO
This result in :
Policy 'StoredProcNamingPolicy' has been violated by > > 'SQLSERVER:\SQL\DB01\DEFAULT\Databases\MyDB\StoredProcedures\dbo.sp_test'.
This transaction will be rolled back.
Policy condition: '@Name NOT LIKE 'sp[_]%''
Policy description: ''
Additional help: '' : ''
Statement: 'CREATE PROCEDURE sp_test
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SET NOCOUNT ON;
SELECT FirstName, LastNam...'.
Msg 3609, Level 16, State 1, Procedure sp_syspolicy_dispatch_event, Line 65
The transaction ended in the trigger. The batch has been aborted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I get a reference to the polygon clicked? (google maps api v3) I've set up some polygons, drew them on the map just fine. I also managed to fire console.log when they were clicked. However, how would I go on about figuring out which polygon was actually clicked?
As you can see in my sample code here I store each object within the collection "lots", however - clicking them only gives me the lat-long of the click. I figured I might need to loop through my polygons and check if the point was clicked is intersecting them and thus figure out which polygon it is... is there an easier solution?
var lot = new google.maps.Polygon({
paths: me.area,
strokeColor: 'black',
strokeOpacity: 0.35,
strokeWeight: 1,
fillColor: fillcol,
fillOpacity: 0.35
});
lot.setMap(map);
var obj = {
'id':me.id,
'rented':me.rented,
'area':lot
};
google.maps.event.addListener(lot, 'click', function(event) {
console.log(event);
});
lots.push(lot);
A: If I can step in a little late with a different solution, I was having the same problem and discovered that you can define custom properties on a polygon.
My example (which creates a state on a map of the U.S.)
poly = new google.maps.Polygon({
map_state_id: map_state_id,
paths: pts,
fillColor: colour,
fillOpacity: 0.66,
strokeWeight: 1,
clickable:true
});
In this case "map_state_id" is the custom property. I have defined it to be the ID of the state (1 for Alabama, 2 for Alaska, etc.)
Then when the particular state is clicked later, this "map_state_id" can be passed into the event function.
google.maps.event.addListener(poly, 'click', function()
{
var map_state_id = this.map_state_id; //retrieve correct state_id
$.ajax(
{
type: "POST",
url: "http://www...get_state_info.php",
data: {state_id : map_state_id},
dataType: "html",
success: function(data)
{
$("#state_info").html(data); //display some info
}
});
});
I found this particular concept at http://dominoc925.blogspot.com/2011/12/add-your-own-property-field-to-google.html
A: Why don't assign to each polygon some id property when you create them and later just use this.myID? Truly speaking, you can hang all information you need on that polygon object.
var lot = new google.maps.Polygon({
paths: me.area,
strokeColor: 'black',
strokeOpacity: 0.35,
strokeWeight: 1,
fillColor: fillcol,
fillOpacity: 0.35
});
lot.setMap(map);
var obj = {
'id':me.id,
'rented':me.rented,
'area':lot
};
lot.objInfo = obj;
google.maps.event.addListener(lot, 'click', function(event) {
console.log(this.objInfo);
});
lots.push(lot);
It would be more effective than path comparison in a loop, or am i missing something? :)
A: Turned out getPath() works like a charm. I did not realize I actually got the polygon reference passed on the click event, to match this with my stored "lots" I simply loop through my stored lots and compare this.getPath to other.getPath, if they match I know which lot was clicked and can now show info related to this particular object.
Here's a code sample:
(where parking is an array of my parking area objects which themselves have arrays containing parking lot objects)
google.maps.event.addListener(lot, 'click', function(event) {
var myPath = this.getPath();
for(var i = 0; i < parking.length; i++){
for(var j = 0; j < parking[i].lots.length; j++){
var lot = parking[i].lots[j];
var otherPath = lot.poly.getPath();
if(otherPath == myPath){
console.log(lot);
break;
}
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: PHP regular expression repetition problem I have the following string:
{slider id="1"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
I would like to parse it by regular expression, but I'm stuck.
preg_match_all('/{slider\s+id="([0-9]+)"\s*}(\s*{slide\s*title="(.*?)"\s*}\s*{content}(.*?){\/content}\s*{caption}(.*?){\/caption}\s*{\/slide}\s*)*{\/slider}/sm', $body, $sliders);
The result is:
Array
(
[0] => Array
(
[0] => {slider id="1"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
)
[1] => Array
(
[0] => 1
)
[2] => Array
(
[0] => {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide}
)
[3] => Array
(
[0] => title2
)
[4] => Array
(
[0] => content2
)
[5] => Array
(
[0] => caption2
)
)
I think the problem is around here: {/slide}\s*)*{/slider} Where the second * is, but I don't know what features need to use to get the right result.
I would like to get this result in the array:
1
title1
content1
caption1
2
title2
content2
caption2
UPDATE1:
The regular expression must work with multiple slider instances in the string, like:
$body = '
{slider id="1"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
{slider id="2"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
{slider id="3"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
';
A: How is this?
Updated answer follows, in light of OP's comments:
$body = '
{slider id="1"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
{slider id="2"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
{slider id="3"} {slide title="title1"} {content} content1{/content} {caption}caption1 {/caption} {/slide} {slide title="title2"} {content} content2{/content} {caption} caption2 {/caption} {/slide} {/slider}
';
preg_match_all('/{slide\s+title="(.*?)"\s*}\s*{content}(.*?){\/content}\s*{caption}(.*?){\/caption}\s*{\/slide}\s*/sm', $body, $sliders, PREG_SET_ORDER);
$new_array = array();
for ($i = 0; $i < count($sliders); $i++) {
for ($j = 1; $j < count($sliders[$i]); $j++) {
$new_array[] = $sliders[$i][$j];
}
}
echo '<pre>'.print_r($new_array,1).'</pre>';
The above produces the following output:
Array
(
[0] => title1
[1] => content1
[2] => caption1
[3] => title2
[4] => content2
[5] => caption2
[6] => title1
[7] => content1
[8] => caption1
[9] => title2
[10] => content2
[11] => caption2
[12] => title1
[13] => content1
[14] => caption1
[15] => title2
[16] => content2
[17] => caption2
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: adding new item in indexed property of struts here is what i want to do:
I have an actionForm with an indexed property(a list of districts), I have managed to show and bind all items to form the list districts.
I want to have a jsp page that allow user to add and delete item in that list. The problem is that struts use for example districts[0], districts[1] to bind each item in the list, when i want new item to be added or deleted, does this mean i need to append new 'input' tag with name='districts[last_index]' at the end of the list using javascript for addition and remove input tags for the corresponding index for deletion? is there alternative for this?
A: Yes. This is the way it works. I have tried managing parameters like this and has worked fine. And, for the deletion, you need not re-index the items. You just need to manage the last_index. For your information:
If the list contains objects with nested property, you need to implement this. Otherwise, you can just get the items in the list with the listname specified.
E.g.:
For List<Integer> integerInputs;, &integerInputs=1&integerInputs=230&integerInputs=332 will work.
For
class MyObj {
String name;
int id;
.
.
Getters and Setters
.
.
}
List<MyObj> myObjList;
The url to populate the list would be something like &myObjList[0].id=12&myObjList[0].name=testName1&myObjList[1].id=122&myObjList[1].name=testNameOnly
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento admin form search/reset filter redirects to dashboard In a large number of our grid forms in our current Magento backend clicking the "Search" or "Reset Filter" buttons will redirect to the admin user start page. This happens in related products, sales orders and any of those style of forms except for the products list in Catalog >> Manage Products
A: Which browser it happens in? If it has happened in IE9 then you could upgrade JS Prototype framework, which Magento used, at least to 1.7.
A: add:
public function gridAction(){
$this->loadLayout();
$this->renderLayout();
}
to your controller
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: bulk rename of files to lowercase in git I have an entire git repo where I'd like to rename all the files and direcories to lowercase.
Running on Win7, I've added igorecase = false to the gitconfig and renamed a few files through eclipse. The resulting commit now has the two files, one all lowercase and one with upper and lowecase.
Removing the 'undesired' file would dump the version history which is not ideal...
So what is potential method to achieve my goal - thinking only option is batch/shell (not sure how to do recursive directory stuff in there but hopefully someone will be kind ;) )
Any tips recieved with massive thanks and hugs.
A: When I've had to change case of files in a git repo I just use two renames:
git mv aNiceClass.inc aniceclass.inc_
git mv aniceclass.inc_ aniceclass.inc
Git then happily records the name change:
# Changes to be committed:
#
# renamed: aNiceClass.inc -> aniceclass.inc
Trying to do the rename directly throws this error:
fatal: destination exists, source=aNiceClass.inc, destination=aniceclass.inc
Here's an example shell script which will lowercase the name of any file below the current directory which has an inc or txt file extension:
#! /bin/bash
find -E . -regex '.*(inc|txt)$' | while read f
do
lc=$(echo ${f} | tr A-Z a-z)
git mv $f ${lc}_
git mv ${lc}_ $lc
done
That could also be mashed in an ugly little one-liner:
find -E . -regex '.*(inc|txt)$' | while read f; do lc=$(echo ${f} | tr A-Z a-z); git mv $f ${lc}_; git mv ${lc}_ $lc; done
A: Since the title or tags doesn't mention anything about OS, this works on macOS. It does a git mv to lowercase on all files in a folder. If you need the force flag just add it in after git mv.
for f in *; do git mv "$f" "`echo $f | tr "[:upper:]" "[:lower:]"`"; done
A: For starter, core.ignorecase is false by default.
And your commit should have the two files listed, but one for removal, and one for addition.
Upon commit, Git will detect that one has been renamed into the other
(since Git is at its core a content provider).
The history will be preserved (even though you might need a git log --follow -- yourNewFile in order to get its history)
Note: git 2.0.1 authorizes now a simple git mv a.txt A.txt: see "Git: Changing capitalization of filenames".
No more need for a script like the one below.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: use gsub in R to cut the character out between two slashes I have a file name captured by R like the following:
"0097_abcdef/0097_0/0097_0_04_bed.dbf"
I need to pick up the term between the two slashes / (i.e. 0097_0), but I have tried gsub(".*/","",dbf.files[1]), but it gives me "0097_0_04_bed.dbf", which is not quite what I want.
Can anyone help? Thanks.
A: you can try using -
.*/(.*)/.*
and use the first group e.g. \1
> x = "0097_abcdef/0097_0/0097_0_04_bed.dbf"
> sub(".*/(.*)/.*","\\1",x)
[1] "0097_0"
A: A different approach is to use the file path manipulation functions. I my opinion, it is a bit clearer than a regexpr - and it handles Windows paths correctly as well:
# On a Linux path
x <- "0097_abcdef/0097_0/0097_0_04_bed.dbf"
basename( dirname(x) )
# [1] "0097_0"
# On a Windows path
y <- "c:\\0097_abcdef\\0097_0\\0097_0_04_bed.dbf"
basename( dirname(y) )
# [1] "0097_0"
..They are vectorized so you can give them a vector of paths.
For completeness, there is also file.path to stitch the parts together again.
A: You can easily use strsplit instead. For example,
R> x = "0097_abcdef/0097_0/0097_0_04_bed.dbf"
R> strsplit(x, "/")
[[1]]
[1] "0097_abcdef" "0097_0" "0097_0_04_bed.dbf"
R> strsplit(x, "/")[[1]][2]
[1] "0097_0"
A: You can use read.table:
tc <- textConnection(dbf.files)
y <- read.table(tc,sep="/",as.is=TRUE)[2]
close(tc)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Objective C: Catch event when an audio is finish to play i'm new in Objective C, i'm developing an app that play sound on touch event of an uibutton.
When i touch the button, it change is image and audio starts to playing. When audio is finish to play, i want to put the original image of uibutton. How can i do that? How can i catch the event of the audio that is finish?
i'm using that code:
- (SystemSoundID) createSoundID: (NSString*)name
{
NSString *path = [NSString stringWithFormat: @"%@/%@",
[[NSBundle mainBundle] resourcePath], name];
NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
return soundID;
}
In
viewDidLoad
i call
freq = [self createSoundID: @"freq.wav"];
and in function that is called on button's touch i use:
AudioServicesPlaySystemSound(freq);
How can i do? Thank you!
A: Not sure if it's possible with the AudioService API but you can use AVAudioPlayer instead and assign a delegate that implements the AVAudioPlayerDelegate protocol and does something when audioPlayerDidFinishPlaying:successfully: is called.
Remember to add the AVFoundation framework.
Example:
In your interface definition:
#import <AVFoundation/AVFoundation.h>
...
@inteface SomeViewController : UIViewController <AVAudioPlayerDelegate>
...
@propety(nonatomic, retain) AVAudioPlayer *player;
In your implementation:
@synthesize player;
...
// in some viewDidLoad or init method
self.player = [[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:NULL] autorelease];
self.player.delegate = self;
...
- (void)pressButton:(id)sender {
// set play image
[self.player stop];
self.player.currentTime = 0;
[self.player play];
}
...
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
// set finish image
}
...
# in some dealloc or viewDidUnload method
self.player = nil;
A: It is possible with the AudioService API, you want to use AudioServicesAddSystemSoundCompletion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I force draw after setContentView call? in my activity I run code that takes a while to execute, but does not change the UI.
It seems that Android waits for all the code in onCreate to be executed to draw the UI.
Is there any way to force the drawing before executing the long code or I must execute my long lasting code in a thread?
Thanks
A: You should always create Thread for time taking process. Also in some of your scenarios i.e. on low-end device you will face infamous ANR dialog
A: If you're only concerned that your UI is drawn delayed because of the long runing code you could try this:
runOnUIThread(new Runnable {
public void run() {
// do setup here
}
}
But if your code is performing for a long time you should accept this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL request with composite primary key I have to get information from two databases. The one is an ORACLE and the other is a DB2. In my program (C#) I get in the first step the base informations of my objects from the ORACLE database. In the second step I want to add the information which are saved in the DB2. The table in the DB2 has composite primary key and I'm not sure which is the best way to request or if there is an alternative that I don't see at the moment.
For example: COLUMN1 and COLUMN2 are the composite primary key.
Variant 1:
SELECT *
FROM (SELECT COLUMN1, COLUNN2, COLUMN3, ..., COLUMN1||'_'||COLUMN2 AS ID
FROM TABLE1) AS TEMP
WHERE ID='2011_123456'
OR ID='2011_987654'
Here I think the disadvantage is that for each row in the table the string concatenation is build and also the execution speed is comparatively slow because the primary key columns are indexed and the new one is not.
Variant 2:
SELECT COLUMN1, COLUMN2, COLUMN3, ..., COLUMN1||'_'||COLUMN2 AS ID
FROM TABLE1
WHERE (COLUMN1='2011' AND COLUMN2='123456')
OR (COLUMN1='2011' AND COLUMN2='987654')
This one is really fast but anytime I get an exception SQL0954C (Not enough storage is available in the application heap to process the statement).
Variant 3:
SELECT COLUMN1, COLUMN2, COLUMN3, ..., COLUMN1||'_'||COLUMN2 AS ID
FROM TABLE1
WHERE COLUMN1 IN ('2011')
AND COLUMN2 IN ('123456','987654')
This one is also slow in comparison to variant 2.
Some more numbers: TABLE1 has at the moment approx. 600k rows
I tried the variants and got the following execution times:
For 100 requested objects:
Variant 1: 3900ms
Variant 2: 218ms
For 400 requested objects:
Variant 1: 10983ms
Variant 2: 266ms
For 500 requested objects:
Variant 1: 12796ms
Variant 2: exception SQL0954C
Variant 3: 7061ms
Only looking on the times I would prefer variant 2 but there is the problem with the exception.
The databases are not under my control and I have only SELECT rights. What do you think is the best for this use case? Are there any other possibilities that I don't see?
Regards,
pkoeppe
A: Could you do a modification to variant 2 that
*
*defined a cursor
*bulk collected 100 rows (for example) into a pl/sql table
*do your processing
*fetch the next 100 rows
For example see http://oracletoday.blogspot.com/2005/11/bulk-collect_15.html
I had a problem very similar to this with Oracle and Informix.
A: Both variant 2 and 3 are sane. 1 is not sane.
As the computed column ID in 1 is not in any index the DB will be forced to do at least a full index scan. In 2 and 3 the DB can use indexes on both column1 and column2 to filter the result.
To find out whether 2 or 3 are best you need to study the execution plans for those queries.
One more note about indexes. Relevant indexes will be much more important than the difference between 2 and 3. Even if you only have select rights you can maybe suggest a composite index on (column1,column2) to the DBA if there are no such indexes already.
Edit
Another common approach when you have many values in WHERE COL IN (...) is to create a temp table (if you have permission) with all the values and join with that temp table instead. Sometimes you also need to create an index on the temp table to make it perform well.
In some DBMS:s you can use table valued parameters instead of temp tables, but I can not find anything like that for DB2.
A: SQL0954C can be resolved by tweaking your system's configuration. Have you explored that avenue yet? Find out more.
A: For variant 3, change
SELECT COLUMN1, COLUMN2, COLUMN3, ..., COLUMN1||'_'||COLUMN2 AS ID
FROM TABLE1
WHERE COLUMN1 IN ('2011')
AND COLUMN2 IN ('123456','987654')
To:
SELECT COLUMN1, COLUMN2, COLUMN3, ..., COLUMN1||'_'||COLUMN2 AS ID
FROM TABLE1
WHERE COLUMN1 ='2011'
AND COLUMN2 IN ('123456','987654')
If you're only searching for one value for COLUMN1 there's no reason to use IN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert to an array I have a variable $code which contains the following data. I want the contents of $feeds_importer to an array. How can I do this?
$feeds_importer = new stdClass;
$feeds_importer->disabled = FALSE;
/* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'feed';
$feeds_importer->config = array(
'name' => 'Feed',
'description' => 'Import RSS or Atom feeds, create nodes from feed items.',
'fetcher' => array(
'plugin_key' => 'FeedsHTTPFetcher',
'config' => array(
'auto_detect_feeds' => FALSE,
'use_pubsubhubbub' => FALSE,
'designated_hub' => '',
),
),
'parser' => array(
'plugin_key' => 'FeedsSyndicationParser',
'config' => array(),
),
'processor' => array(
'plugin_key' => 'FeedsNodeProcessor',
'config' => array(
'content_type' => 'feed_item',
'update_existing' => 0,
'expire' => '-1',
'mappings' => array(
array(
'source' => 'title',
'target' => 'title',
'unique' => FALSE,
),
array(
'source' => 'description',
'target' => 'body',
'unique' => FALSE,
),
array(
'source' => 'timestamp',
'target' => 'created',
'unique' => FALSE,
),
array(
'source' => 'url',
'target' => 'url',
'unique' => TRUE,
),
array(
'source' => 'guid',
'target' => 'guid',
'unique' => TRUE,
),
),
'input_format' => 0,
'author' => 0,
),
),
'content_type' => 'feed',
'update' => 0,
'import_period' => '1800',
'expire_period' => 3600,
'import_on_create' => 1,
);
A:
i want the contents of feeds_importer to an array how can i do this?
$array = (array) $feeds_importer;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swing BoxLayout problem with JComboBox without using setXXXSize here's an SSCCE:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BoxLayoutTest extends JFrame {
public BoxLayoutTest(){
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBackground(Color.red);
this.add(main);
JPanel northPanel = new JPanel();
JPanel middle = new JPanel();
middle.setLayout(new BoxLayout(middle, BoxLayout.X_AXIS));
middle.add(new JButton("FOO"));
middle.add(Box.createHorizontalGlue());
JPanel aPanel = new JPanel();
aPanel.setBackground(Color.black);
JComboBox b = new JComboBox();
//b.setPreferredSize(new Dimension(100,16)); //uncomment this to see the layout I would like to achieve
//b.setMaximumSize(new Dimension(100,16));
//middle.add(b); //uncomment this line
middle.setBackground(Color.green);
northPanel.setBackground(Color.blue);
main.add(northPanel);
main.add(middle);
main.add(Box.createVerticalGlue());
this.setSize(800,600);
this.setResizable(true);
this.setVisible(true);
}
public static void main(String[] args) {
new BoxLayoutTest();
}
}
I'm trying to refactor some classes I wrote some time ago, when I didn't know that using setXXXSize methods on components is wrong.
Using a resizable frame ,the result I want to achieve is the following:
*
*The northPanel should stay on top and change it's size accordingly to the frame size modifications (seems to work fine)
*The green panel where I put the JButton should keep the maximum dimension of the JButton and stay just below the blue panel above (this works fine if I only put JButtons inside that panel).
The problem arise if I put a JComboBox inside the green panel (try to uncomment the line in the SSCCE). I guess JComboBox hasn't a maximum size specified, so it stretches with the frame. In the previous wrong version of my code I was using setxxxSize methods on the JComboBox to limit it's dimension(try to uncomment the line on setXXXSize methods to see it).
My question are:
*
*Is it possible to achieve the same result using BoxLayout without invoking setXXXSize() methods?
*If yes, how?
*Is there any other LayoutManager that can I use to get that effect?
Please put me in the right direction
A: JComboBox is misbehaving (the same as JTextField) in reporting an unbounded max height: should never show more than a single line. Remedy is the same: subclass and return a reasonable height
JComboBox b = new JComboBox() {
/**
* @inherited <p>
*/
@Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
just for fun, here's a snippet using MigLayout (which is my personal favorite currently :-)
// two panels as placeholders
JPanel northPanel = new JPanel();
northPanel.setBackground(Color.YELLOW);
JPanel southPanel = new JPanel();
southPanel.setBackground(Color.YELLOW);
// layout with two content columns
LC layoutContraints = new LC().wrapAfter(2)
.debug(1000);
AC columnContraints = new AC()
// first column pref, followed by greedy gap
.size("pref").gap("push")
// second
.size("pref");
// three rows, top/bottom growing, middle pref
AC rowContraints = new AC()
.grow().gap().size("pref").gap().grow();
MigLayout layout = new MigLayout(layoutContraints, columnContraints,
rowContraints);
JPanel main = new JPanel(layout);
main.setBackground(Color.WHITE);
// add top spanning columns and growing
main.add(northPanel, "spanx, grow");
main.add(new JButton("FOO"));
// well-behaved combo: max height == pref height
JComboBox combo = new JComboBox() {
@Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
// set a prototype to keep it from constantly adjusting
combo.setPrototypeDisplayValue("somethingaslongasIwant");
main.add(combo);
// add top spanning columns and growing
main.add(southPanel, "spanx, grow");
A: I have always seen using the layout managers in the jdk are not easy. They are either too simple and inflexible or the gridbaglayout is just too much trouble. Instead I started using the jgoodies form layout and never looked back since.. Have a look at it. Its very simple and easy to use. Here's a link:
http://www.jgoodies.com/freeware/forms/
Make sure you go through the white paper.
And now, we also have google providing us a WYSISWG editor for the formlayout as a plugin for eclipse. This just makes life a lot lot easier.
http://code.google.com/javadevtools/wbpro/palettes/swing_palette.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MySQL time overlapping I have a database to manage my schedule
the database looks like:
CREATE TABLE activities(
name VARCHAR(255),
startTime INT(11),
endTime INT(11)
);
Now I'd like to detect overlaps in activities.
so lets say i have the following variables:
$start=time();
$end=time()+3600;
now i want to query the database to get ALL activities that overlap with these times.
Anyone has an idea how to do this?
Thank you!
p.s. I realize similiar questions have already been asked but i couldn't find the answer for MySQL with a table similiar to this one.
A: use something like
SELECT * FROM activities WHERE
(.$start. BETWEEN startTime AND endTime) OR
(.$end. BETWEEN startTime AND endTime) OR
(startTime < .$start. AND endTime > .$end.);
A: I guess you'd want something like:
mysql_query( "SELECT * FROM `activities` WHERE `startTime`<".$start." AND `endTime`>".$end);
Just be careful to properly index your tables, otherwise that's gonna be one heck of a slow query.
A: Use the query below.
"SELECT *
FROM `activities`
WHERE `endTime`>".$start." AND `startTime`<".$end
The solution become quite obvious when you draw your problem down.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Incorrect Stored Procedure Syntax I am using the below stored procedure to upload files into a db where each file has a correspondence table but there are times when the table not exist in that case i want to add the file name into a table called NewTables.I can not get the stored proc syntax working can someone help me.I believe the mistake is in the first part where i check if the table exist
ALTER proc [dbo].[UploadCSVFiles]
@FilePath varchar(100) ,
@FileName varchar(100),
@TableName varchar(250)
AS
BEGIN
DECLARE @SqlStmt nvarchar(max)
DECLARE @ErrorCode int
SET @SqlStmt='Truncate table dbo.[' + @TableName +']'
EXEC(@SqlStmt);
set @SqlStmt =N'
IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].['+@TableName +N']'') AND type in (N''U''))
BEGIN
INSERT INTO dbo.NewTables ('+@TableName+N','+@FileName+N') Values('+@TableName+N','+@FileName+N')
END
ELSE
BEGIN
INSERT INTO '+@TableName+N'
select *
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir='+@FilePath+N'''
,''select * from "'+@FileName+N'"'')
END
'
EXEC(@SqlStmt);
Thanks
Rao
Thanks fpop and Christine, I have made the suggestions you made but still I get an error
Msg 4701, Level 16, State 1, Line 1
Cannot find the object "Customer" because it does not exist or you do not have permissions.
it seems the If statement does not insert the new table
here is the final version
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[UploadFiles_2]
@FilePath varchar(100) ,
@FileName varchar(100),
@TableName varchar(250)
AS
BEGIN
DECLARE @SqlStmt nvarchar(max)
DECLARE @ErrorCode int
SET @SqlStmt='Truncate table dbo.[' + @TableName +']'
EXEC sp_executesql @SqlStmt;
set @SqlStmt =N'
IF ( NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].['+@TableName +N']'') AND type in (N''U''))
BEGIN
INSERT INTO dbo.NewTables (TableName,FileName) Values('''+@TableName+N''','''+@FileName+N''')
END
ELSE
BEGIN
INSERT INTO '+@TableName+N'
select *
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir='+@FilePath+N'''
,''select * from "'+@FileName+N'"'')
END'
EXEC sp_executesql @SqlStmt;
END
A: Hint: You can always add PRINT @SQLSTMT to see the code your procedure has generated.
There are two error in the script, both in line:
INSERT INTO dbo.NewTables ('+@TableName+N','+@FileName+N') Values('+@TableName+N','+@FileName+N')
First error: NewTables table must have 2 columns to keep table name and file name. Let's call them COL_TBL, COL_FILE
Second error: You have to add quotes in Values part of statement
Here is how it should look like:
INSERT INTO dbo.NewTables (COL_TBL, COL_FILE) Values('''+@TableName+N''','''+@FileName+N''')
btw, You didn't post code entirely, there is an END at the end missing. Please, next time copy the whole code so others can reproduce the error.
EDIT: Please consider following: using sp_executesql instead of EXEC, to avoid sql injection bugs do not concatenate parameters into dynamic sql and finally check if table exists before truncating it
A: Try this
IF (NOT EXISTS (SELECT * FROM sys.objects WHERE [type] LIKE 'U' AND name LIKE 'mytable'))
SELECT 'not found';
ELSE
SELECT 'found';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Object Debugger says website is inacessible - but it isn't On this page: http://megascope.dk/Level7Marathon facebook comments were added by a friend. Commenting works great, everything looks fine.
He asked me why he gets no moderation-options on the page, even though he is added as a moderator in fb:admins as usual , so I checked it out in object debugger.
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fmegascope.dk%2FLevel7Marathon
Even though the page is completely visible, there are no access restrictions whatsoever - object debugger returns this error:
"The page at http://invalid.invalid/ could not be reached."
I am guessing the two problems are related.
Does anybody know what causes this - and how we can fix it?
A: It fixed itself after some days like many other odd facebook bugs. Something like that seems to happen every time I deal with integrating some facebook social plugin into a website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Terrible Apache Bench results on Custom CMS Please note: This is not a complain about a shoddy CMS.
Just toying with Apache Bench and got terrible results with our custom CMS, more exactly i got:
Requests per second: 0.37 [#/sec] (mean)
When i run another test with a plain php file i got:
Requests per second: 4786.07 [#/sec] (mean)
Another test with a previous version of the CMS:
Requests per second: 6068.66 [#/sec] (mean)
The website(s) are working fine, no problems detected, Google's Webmaster Tools reports our sites as faster than 80% of the pages which is fine, i think.
The test was:
ab -t 30 -c 10 http://example.com/
Maybe some kind of Apache problem? Bad .htaccess config, or similar?
Update:
Just ran a simple test with sockets and the results are similar. Page loads very, very slowly. If i ran my script with another website everything is fine.
Also, there's a small hint about a chunk length problem. (Bad Apache Headers, or line endings?)
The site is gzipped, and when verbose logging turned on, i see these lines in the response:
LOG: Response code = 200
LOG: header received:
HTTP/1.1 200 OK
Date: Tue, 04 Oct 2011 13:10:49 GMT
Server: Apache
Set-Cookie: PHPSESSID=ibnfoqir9fee2koirfl5mhm633; path=/
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Cache-Control: post-check=0, pre-check=0
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
2ef6
Always at the same place, in the middle of the HTML-source, then <!DOCTYPE HTML> again.
Please, help.
Update #2:
Just checked my HTTP headers with Rex Swain's HTTP Viewer and got these results:
HTTP/1.1·200·OK(CR)(LF)
Date:·Wed,·05·Oct·2011·08:33:51·GMT(CR)(LF)
Server:·Apache(CR)(LF)
Set-Cookie:·PHPSESSID=n88g3qcvv9p6irm1fo0qfse8m2;·path=/(CR)(LF)
Expires:·Sat,·26·Jul·1997·05:00:00·GMT(CR)(LF)
Cache-Control:·no-store,·no-cache,·must-revalidate(CR)(LF)
Pragma:·no-cache(CR)(LF)
Cache-Control:·post-check=0,·pre-check=0(CR)(LF)
Vary:·Accept-Encoding(CR)(LF)
Connection:·close(CR)(LF)
Transfer-Encoding:·chunked(CR)(LF)
Content-Type:·text/html;·charset=UTF-8(CR)(LF)
(CR)(LF)
Do you notice anything unusual?
A: If it works well with ordinary web browsers (as you mentioned in the comments) the CMS handle the requests from Apache Benchmark differently.
A quick checklist:
*
*AFAIK Apache Benchmark just send simple requests without any cookie handling, so try to set -C with a valid cookie (copy the values from a web browser).
*Try to send exactly the same headers to the CMS as the web browser sends. Save a dump of a valid request with netcat, HttpFox or a packet sniffer and set the missing headers with -H.
*Profile the CMS on the server while you're sending to it a request with Apache Benchmark. Maybe you found the bottleneck. Two poor man's error_log calls with a timestamp in the first and the last line of the index.php (or the tested script's entry point) could show how fast is the PHP script and help to calculate the overhead of the Apache HTTP Server and network.
*If you run socket tests and browser tests from different machines it's could be a DNS issue (turn off HostnameLookups in Apache). Try to run them from the same machine.
*Try ab -k ... or ab -H "Connection: close" ....
I guess the CMS does some costly initialization when it initializes the session and it's happens when it processes the first request. Since Apache Benchmark does not send the cookies back the CMS it creates a new session for every request and it's the cause of the slow answers.
A second guess is that the CMS handle the incoming http headers differently and the headers which was sent (or the lack of them) by Apache Benchmark trigger some costly/slow processing. It looks more appropriate since the report of the Google's Webmaster Tools.
Apache Benchmark sends HTTP 1.0 request, for example:
GET / HTTP/1.0
Host: localhost:9100
User-Agent: ApacheBench/2.3
Accept: */*
It looks to me that your server does not send any http header about Keep-Alive settings but it assumes that the client uses keep-alive when the client uses HTTP 1.0. It's not an RFC compliant behaviour:
From RFC 2616, 19.6.2 Compatibility with HTTP/1.0 Persistent Connections:
Some clients and servers might wish to be compatible with some
previous implementations of persistent connections in HTTP/1.0
clients and servers. Persistent connections in HTTP/1.0 are
explicitly negotiated as they are not the default behavior.
By default Apache Benchmark doesn't use keep-alive so it waits when the response arrives for the closing of the socket. The server closes it after 15 seconds idle. Downloading the main page with wget also takes 15 seconds. Wget also uses HTTP 1.0 in the request.
I think it's a bug in the PHP code of the CMS since ab works well on the same server with a plain php file. Anyway, you can workaround it with using keep-alive connections (-k):
ab -k -t 30 -c 10 http://example.com/
or with explicitly disabling persistent connections:
ab -H "Connection: close" -t 30 -c 10 http://example.com/
but it's still a server side issue and your original ab commands is right.
Please note that this bug probably affects only HTTP 1.0 clients (like Apache Benchmark, wget) and clients with regular browsers will not notice it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to get click event of table row/ table item? I have a simple table layout in the .xml file. I am adding components to it at run-time.
Following is my code:
public class Home extends Activity{
TextView tv1; int i;TableRow tbrow;
String [] names = {"First Name","Last Name", "Title","Company","Phone"};
int [] images = { R.drawable.icon,R.drawable.icon,R.drawable.star2,R.drawable.icon,R.drawable.icon}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableLayout ll=(TableLayout) findViewById(R.id.tableLayout1);
TableRow trow=new TableRow(this);
ImageView Image1=new ImageView(this);
ImageView Image2=new ImageView(this);
ImageView Image3=new ImageView(this);
ImageView Image4=new ImageView(this);
tv1=new TextView(this);
trow.setClickable(true);
Image1.setImageResource(R.drawable.blank);
Image2.setImageResource(R.drawable.star2);
Image3.setImageResource(R.drawable.blank);
Image4.setImageResource(R.drawable.blank);
tv1.setText("Brochures");
trow.addView(Image1);
trow.addView(tv1);
trow.addView(Image2);
trow.addView(Image3);
trow.addView(Image4);
trow.setId(0);
ll.addView(trow);
for(i=1;i<5;i++){
tbrow=new TableRow(this);
ImageView img1=new ImageView(this);
tv1=new TextView(this);
CheckBox chk=new CheckBox(this);
ImageView img2=new ImageView(this);
ImageView img3=new ImageView(this);
img1.setImageResource(R.drawable.pdf);
img2.setImageResource(R.drawable.blank);
img3.setImageResource(R.drawable.blank);
tv1.setText(""+names[i]);
tbrow.addView(img1);
tbrow.addView(tv1);
tbrow.addView(chk);
tbrow.addView(img2);
tbrow.addView(img3);
tbrow.setId(i);
Log.e("TAG", "ID: "+tbrow.getId());
tv1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(Home.this, ""+tbrow.getId(),
Toast.LENGTH_SHORT).show();
Log.e("TAG", " clicked ID: "+tbrow.getId());
}
});
ll.addView(tbrow);
}
}
}
Whenever I click on any of the rows, the onClick() event of the last row is triggered. Instead of text view, I also tried to trigger the onClick() event for table row, but in vain.
I want to know which row is clicked. getID(), setID() won't work.
Please help.
A: Change the line
tbrow=new TableRow(this);
to
final TableRow tbrow = new TableRow(this);
and it will work as you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Use of "$or" condition is not working I am developing a search portal, so I need to find the searched text on more than one field.
I am trying to use the advanced query of MongoDB in PHP.
My code is:
$mongo = new MongoDBCONN();
$jobCollection = $mongo->select('jobs', $mongo);
$advanceQuery=array('orgId' => '21')
$query_q=array('$or'=>array(
array("jobTitle"=>new MongoRegex("/$search/i")),
array("jobLocationCity"=>new MongoRegex("/$search/i")),
array('jobLocationCountry'=>new MongoRegex("/$search/i"))
));
$advanceQuery=array_merge($advanceQuery,$query_q);
$jobCollection->find($advanceQuery);
It returns NULL every time, whereas MongoRegex is working fine, because when I use it to search on only one field it works.
$search is post as input text.
A: I found the answer on my own, actually this was a version problem. I was using 1.4.4, but after update to 1.7.4 it is working. On the mongo website I found that the "or" operator was included only from version 1.7.x onwards.
A: $regexObj = new MongoRegex("/$search_term/i");
$where = array(
'$or' => array(
array("Name" => $regexObj),
array("image.caption.text" => $regexObj),
array("image.user.username" => $regexObj)
)
);
$cursor = $collection->find($where);
// Parsing the results
while ($cursor->hasNext())
{
$obj = $cursor->getNext();
$profile_image = $obj['image']['user']['profile_picture'];
}
A: If you need to combine the regex with another operator, you need to use the $regex clause. That one is missing in your code example. Please read again about how to query with regulars expressions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CRUD using Hibernate but without any entities Is is possible to do this? I know Hibernate is an ORM tool which maps objects to tables in the database. So we need to have the entities to do CRUD on the corresponding tables.
But in our application entities will be dynamic i.e. Admin User can create person , location forms dynamically and then the tables will also be generated dynamically in the database.
Can we do this using hibernate or we will have to use simple JDBC for this? We dont want to use JDBC as we want our application to run on different databases like Mysql, mssql and oracle.
Please help.
A: It is not possible and I can't even imagine how should this work. To be honest, the whole design of your application seems suspicious, but never mind.
Hibernate is about objects - if you don't know the table structure beforehand, you can't create objects mapping to those tables and you can't use them. You can use maps (column -> value) instead, but this approach is not supported by Hibernate.
So you do have to fall back to JDBC (but crying out loud, use abstractions like MyBatis or JdbcTemplate) since Hibernate does not support such approach.
A: Using Hibernate without entities is possible. See here:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/persistent-classes.html#persistent-classes-dynamicmodels
A: Relational databases are not well adapted for this use case. You may be better off
with some key-value store / nosql soltuion
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jquery slide an element up and down on click I am trying to slide an element down when another is click and if that link is then clicked again, slide the element back up, is there a cleaner way of doing it than this?
$("#dropdown, #dropdown span, #dropdown dt a").click(function(event) {
$("#dropdown dd").slideDown(defaults.speed);
$("#dropdown").addClass('drop_down_open');
event.preventDefault();
});
$(".drop_down_open, .drop_down_open span, .drop_down_open dt a").click(function(event) {
console.log("hello");
$("#dropdown dd").slideUp(defaults.speed);
event.preventDefault();
});
A: $("#anElement").click(function(e) {
var theItem = $("#dropdown dd");
if (theItem.css("display") == none) {
theItem.slideDown(defaults.speed);
}
else {
theItem.slideUp(defaults.speed);
}
e.preventDefault();
});
Modify according to your specific needs.
A: Is this what you wanted. http://jqueryui.com/demos/accordion/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: value from SELECT command is object I am doing a project in google app engine. Python is used in the back end. I have a datastore table "Data" with following attributes,
class Data(db.Model):
url = db.StringProperty
code = db.StringProperty
turl = db.StringProperty
I used following lines of code to get all values from the table,
x = Data.all()
x = db.GqlQuery("SELECT * FROM Data")
ourl = x.fetch(10)
When i print it using the following code,
for p in ourl:
print "%s %s, %s " % (p.url, p.code, p.turl)
i got 10 times the following message,
<class 'google.appengine.ext.db.StringProperty'> <class 'google.appengine.ext.db.StringProperty'>, <class 'google.appengine.ext.db.StringProperty'>
I cannot get the real values of url,code and turl. What to do with this code??
A: In your class Data you forgot parenthesis to create instances of property.
class Data(db.Model):
url = db.StringProperty()
code = db.StringProperty()
turl = db.StringProperty()
Currently your simply copy the class db.StringProperty in your attributes defined in your class Data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Add Views to specific point on a WebView I have an image of a map that I have placed inside a WebView to enable zoom and scrolling. This works fine.
I know the latitude/longitude of the top-left and bottom-right corners so I can calculate positions on the map.
The problem is that I want to place a series of clickable points on the map at specific positions. I have got some success with setting the view padding and then using webview.addView(pointView). The problem with this is that the padded area is made clickable as well, sometimes overriding other points. Setting a layout margin does not seem to work at all (clickable view is placed at top-left corner).
Anyone know how to solve this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mobile Optomisation - make header text full width of page? Im mobile optimising my site with media queries and making it into a 1 column layout. I want the header text at the top to be the full width available while staying on one line.
I guess I could make multiple media queries for different screen widths, each making the text a different size. However is there a smarter and quicker way of doing this?
Thanks
A: Hmm, this should be tricky. I understand you are referring to text. Depending on the font used in your layouts and the font used by the user-agent, the width of your text may vary from browser to browser.
This also means whenever you change the content of your header, you will have to change the scaling of your font.
Maybe it would be better to use a graphic instead and scale it via width=100%
Otherwise your solution will probably involve some javascript… pretty nasty for a mobile site. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ToolStripButton disappear from PropertyGrid when user log-in to Windows I have a problem and scenario is the following:
I've created user control with one component PropertyGrid. To this PropertyGrid I added button (Heximal Mode) to the PropertyGrid's ToolStrip. Everything is fine and works great!
But when this control is shown in form and user press "Windows->Switch User" and logging again with same User Name my button (Heximal Mode) disappear. Also the fourth button which was manually hid appears...
I don't know what happen. Probably windows reload its component on user log-in?
Windows 7 (x64/x86)
public partial class CompProperty : UserControl
{
private System.Windows.Forms.ToolStripButton _tsbMode = null;
public CompProperty()
{
InitializeComponent();
createAdditionalButtons();
}
private void createAdditionalButtons()
{
foreach ( Control control in propertyGrid.Controls )
{
ToolStrip toolStrip = control as ToolStrip;
if ( toolStrip != null )
{
toolStrip.Items[4].Visible = false;
_tsbMode = new System.Windows.Forms.ToolStripButton();
_tsbMode.CheckOnClick = true;
_tsbMode.Checked = true;
_tsbMode.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
_tsbMode.Image = Resources.img_edit;
_tsbMode.ImageTransparentColor = System.Drawing.Color.Magenta;
_tsbMode.Name = "tsbMode";
_tsbMode.Size = new System.Drawing.Size( 23, 22 );
_tsbMode.Text = "Heximal Mode";
_tsbMode.ToolTipText = "Heximal Mode";
toolStrip.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
_tsbMode} );
break;
}
}
}
}
A: Yes, this is by design. The PropertyGrid class rebuilds the toolbar when the SystemEvents.UserPreferencesChange event fires. Which is indeed likely to fire on a desktop switch. You could patch it like this:
using System;
using System.Windows.Forms;
class MyPropertyGrid : PropertyGrid {
protected override void OnSystemColorsChanged(EventArgs e) {
// Do nothing
}
}
Not ideal of course. Cold hard fact is that this simply isn't supported.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MS SQL rollup percentage column I am using rollup to sum a table containing fields company, sales, cost and margin. This gives me the summarized columns, but I need to show a summarized percentage of the margin as a percentage of sales for each company summary.
This is my current statement:
SELECT coalesce(CAST(Company AS VARCHAR(30)), 'Grand Total:') AS Company,
SUM(Sales) AS 'TOTSALES',
SUM(CostVal) AS 'TOTCOST',
SUM(MarginVal) AS 'TOTMAR'
FROM DailySalesSum
GROUP BY Company WITH ROLLUP;
A: SELECT coalesce(CAST(Company AS VARCHAR(30)), 'Grand Total:') AS Company,
SUM(Sales) AS 'TOTSALES',
SUM(CostVal) AS 'TOTCOST',
SUM(MarginVal) AS 'TOTMAR',
100.0 * SUM(MarginVal) / SUM(Sales) AS 'MARGINPERCENT'
FROM DailySalesSum
GROUP BY Company WITH ROLLUP;
Do as Martin says and add it as an extra field to your statement as shown above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: getting href onclick I am developing an extension for Mozilla Firefox. A main function is to get the URL that the user is visiting and process it later. I tried the following Javascript code:
window.onload = function(){
alert(document.referrer);
}
That didnt work so I tried to inject an onclick event to every link using this:
window.onload = function(){
var links = document.links;
for(var i=0;i<links.length;++i){
links[i].onclick = show_href();
}
}
function show_href(){
alert(this.href);
}
But that also doesnt work. Any other approach?
A: In the second approach, the problem could be the for loop.
window.onload = function(){
var links = document.links,
max,
i;
for(var i=0, max = links.length; i < max; i += 1) {
(function() {
var link = links[i];
link.onclick = function() {
alert(this.href);
}
})();
}
};
A: var anchors = document.getElementsByTagName('a');
for(var i=0,l=anchors.length;i<l;i++)
if(anchors[i].hasAttribute('href'))
anchors[i].onclick = function(){
alert(anchors[i].getAttribute('href'));
}
A: Try this:
<a href="#xxx">linktextx</a>
<a href="#yyy">linktexty</a>
<a href="#zzz">linktextz</a>
<script>
window.onload = function() {
var links = document.links;
for(var i=0;i<links.length;i++){
links[i].onclick = function(){alert(this.href)};
}
}
</script>
See: http://jsfiddle.net/uXmWj/ for working demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL - search a date-time period that doesn't exists in the table records Need an expert opinion here:
I am trying to implement a scenario in one of our project which displays the graph based on user input and one of the input is date-time range. Let me describe with an example.
Consider an example where there are records having start-date-time = 2011-09-28 9:30 and end-date-time = 2011-09-28 11:30. Let's say an user is trying to view a graph for date-time-range of 2011-09-28 10:00 to 2011-09-28 11:00 - now the system should show a graph since the data is available for the given period (since 10 - 11 is within 9.30 - 11.30).
How can I implement this scenario and how do I search for such inputs?
Note:
There might be too many rows for a particular date/date-time
Thanks.
A: You could use:
SELECT * FROM your_table tb
WHERE
( user_start_time <= tb.start_date_time AND
user_end_time >= tb.start_date_time
) OR (
user_start_time <= tb.end_date_time AND
user_end_time >= tb.end_date_time
) OR (
user_start_time >= tb.start_date_time AND
user_end_time <= tb.end_date_time
)
A: It kind of depends on whether you need to ensure that the entire date range entered by the user is covered by a graph in your table. If you need this then you'll have to ensure that both the user start time and user end time are between the values in the database. Hence:
select * from graph_table t
where @user_start_time between t.graph_range_start and t.graph_range_end
and @user_end_time between t.graph_range_start and t.graph_range_end
limit 1;
You'll have to decide how to cater for multiple rows coming back (I've just used LIMIT 1 here).
If you want to bring back any graphs that cover either the user start time or user end time then change the 'and' in the query to an 'or', Hence:
select * from graph_table t
where (@user_start_time between t.graph_range_start and t.graph_range_end)
or (@user_end_time between t.graph_range_start and t.graph_range_end)
limit 1;
Again, you'll have to decide how you want to handle multiple results here.
A: Try this :
SELECT * FROM TableName
WHERE (@StartDate >= start-date-time AND @StartDate <= end-date-time)
OR
(@EndDate >= start-date-time AND @EndDate <= end-date-time)
A: SELECT * FROM your_table tb
WHERE NOT (
tb.start_date_time > user_end_time
AND
tb.end_date_time < user_start_time
)
Try this.
Contains the following scenarios and returns results:
condition (searched interval):
user_start_time = 2011-09-28 9:30 and user_end_time = 2011-09-28 11:30
*
*tb.start_date_time = 2011-09-28 08:30 and tb.end_date_time =
2011-09-28 12:30
*tb.start_date_time = 2011-09-28 10:30 and tb.end_date_time =
2011-09-28 11:00
*tb.start_date_time = 2011-09-28 10:30 and tb.end_date_time =
2011-09-28 12:30
*tb.start_date_time = 2011-09-28 08:30 and tb.end_date_time =
2011-09-28 10:30
Exceptions:
*
*tb.start_date_time = 2011-09-28 07:30 and tb.end_date_time =
2011-09-28 08:30
*tb.start_date_time = 2011-09-28 12:30 and tb.end_date_time =
2011-09-28 13:30
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detecting the timeframe of accelerometer detected motion How does one detect the amount of time the device has detected motion on the accelerometer?
If I wanted to detect continuous motion detection on the device such as 10 seconds of motion. How is this done? When I use the accelerometer delegate method, it keeps being called and is difficult to handle the time calculation.
A: As commented, accelerometer delivers acceleration values and not speed - so you will have to integrate over incoming values. Bu bevare of:
- earth gravity is always there
- there is a lot of noise (accelerometer chips built in phones are really cheap, crappy and
sell for 10$ a bucket)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java get resource InvalidJarIndexException I have a class names test.java and another file "log4j.properties" in the same folder but following call
getClass().getResource("log4j.properties")
fails with
ms
Trace:
sun.misc.InvalidJarIndexException: Invalid index
at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
at sun.misc.URLClassPath$JarLoader.findResource(Unknown Source)
at sun.misc.URLClassPath.findResource(Unknown Source)
at java.net.URLClassLoader$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at java.lang.Class.getResource(Unknown Source)
But getClass().getClassLoader().getResource("log4j.properties") works. What can be the reason?
A: The InvalidJarIndexException is normally caused by a corrupt INDEX.LIST file in the JAR. So check the JAR for any problems. See http://littletechsecrets.wordpress.com/2008/12/01/why-does-invalidjarindexexception-occur/
The different results you describe are probably related to Class.getResource() resolving a path relative to the classes package, and ClassLoader.getResource() resolving a path relative to the root. So getClass().getResource("/log4j.properties") might fix your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implement a noise filter algorithm for recorded audio in iPhone I am developing an application like TomCat. I have recorded audio with a funny voice and playing it with Audio Queue Services. I have changed the settings of AVAudioRecorder, But while i am playing there is some noise or distortions.
NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
[settings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[settings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[settings setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
[settings setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[settings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[settings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:self.audioPath] settings:settings error:nil];
self.recorder = [self.recorder retain];
[self.recorder prepareToRecord];
[self.recorder record];
I know how to covert the decibels to amplitude, or use LowPassFilter Blocks if the frequencies are too high. The HighPassFilter blocks if the frequencies are too low. How do I implement this in Objective-C?
//convert decibels to amp
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (0.05 * [audioMonitor peakPowerForChannel:0]));
double audioMonitorResults;
audioMonitorResults= ALPHA * peakPowerForChannel + (1.0 - ALPHA) *audioMonitorResults;
A: Your question is not clear. In case you are looking to ensure you adhere to the Nyquist sampling criteria, your filter needs to be implemented BEFORE the ADC i.e., in hardware if your sampling frequency is close to the spectrum you intend to record.
If you do have an appropriate LPF and still hear funny noises, I suggest to you that your input audio levels are too high. This is again a hardware issue; bring down your input volume.
Another source of noise might be that your record does not really consists of one continuous sample block without interruptions. Alternatively, this could be a playback issue also.
Lots of things can go wrong that lead to "noise or distortions"...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.