text stringlengths 8 267k | meta dict |
|---|---|
Q: Why doesn't mxml support component constructors? Why doesn't the Flex framework's mxml language support a constructor for components or accept constructor arguments for components? It's as far as I know not possible to declare an ActionScript object in mxml if it takes constructor arguments. I'm curious about the reason. Is it a design choice by Adobe or related to how declarative languages work? For example, why not allow:
<myNameSpace:MyComponent constructor="{argArray}"/>
A: You can read IMXMLObject help API for more information about your question. They're not telling exactly why an mxml doesn't support constructors, but it says that you must control your mxml component throught its lifecycle events: preinitialize, initialize and creationComplete.
I suppose that's a design decision, considering that an mxml gets translated directly to AS3 code (you can compile your application adding keep-generated-actionscript=true and see what it produces).
A: Even if a class is defined in MXML, it is possible to implement a constructor via instantiating an instance variable as follows. This will get called before various events like "preinitialize" or "creationComplete" are dispatched.
<myNameSpace:MyComponent>
<fx:Script>
<![CDATA[
private var ignored:* = myInstanceConstructor();
private function myInstanceConstructor():* {
// Do something - called once per instance
return null;
}
]]>
</fx:Script>
</myNameSpace:MyComponent>
Moreover, class variables can be initialized in a similar way as follows.
<myNameSpace:MyComponent>
<fx:Script>
<![CDATA[
private static var ignored:* = myClassConstructor();
private static function myClassConstructor():* {
// Do something - called once per class
return null;
}
]]>
</fx:Script>
</myNameSpace:MyComponent>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why does the live click function work automatically when it should only happen upon click? I have a button that the user clicks(.next_1).
<a id="next_btn" class="next_1" href="#">Next</a>
After the user clicks the button, it should change the class to next_2. When the user clicks the button again, it should change it to next_3.
$('.next_1').click(function() {
$('#next_btn').removeClass('next_1').addClass('next_2');
});
$('.next_2').live('click', function() {
$('#next_btn').removeClass('next_2').addClass('next_3');
});
Currently, when the user clicks the button, it changes the class directly to next_3 when it should change it to next_2. Why does the live click function work automatically when it should only happen upon click?
A: .live() in this case is the same as adding another click handler. I suggest instead using the .toggle() function.
http://api.jquery.com/toggle-event/
$('#next_btn').toggle(function() {
$('#next_btn').removeClass('next_1').addClass('next_2');
}, function() {
$('#next_btn').removeClass('next_2').addClass('next_3');
}, function() {
$('#next_btn').removeClass('next_3').addClass('next_1'); // loops back to start
});
A: If you want to stay with two separate event handlers for other reasons, I would suggest stopping the propagation of the click event and changing both to .live(). Basically, if you're going to be changing things that affect the selectors and you want those changes to be reflected in the event handlers, you either have to unbind and reset the event handlers on the new selectors or use .live():
$('.next_1').live('click', function() {
$('#next_btn').removeClass('next_1').addClass('next_2');
return(false);
});
$('.next_2').live('click', function() {
$('#next_btn').removeClass('next_2').addClass('next_3');
return(false);
});
I think the issue is that you don't stop event propagation on the first click so that click continues to bubble up to the top level. Eventually, it gets to jQuery's .live() handler and now that you've changed the class to "next_2", it matches the .live() handler and the click gets processed again. If you stop event propagation on the first click handler, then it won't get to the .live() handler when it had already been handled.
Plus, I think you're going to have to unbind the first click handler. It's bound to the specific DOM object, not to a class so it will still be handling the events even after you have changed the class name. Or, it might work to make them both .live() handlers.
If it were me, I wouldn't use two separate event handlers for one object. Just bind one event handler and add conditional logic to it based on the state.
A: $('#next_btn').click(function(){
if( $(this).hasClass('.next_2') ){
$(this).removeClass('next_2').addClass('next_3');
}else if( $(this).hasClass('.next_1') ){
$(this).removeClass('next_1').addClass('next_2');
}
});
A: In the interest of variety, here's another way to do it that can easily go to as many next_n levels as you want with no more code:
$('#next_btn').click(function() {
var $this = $(this);
var num = $this.data("index") || 1; // get current state
if (num < 3) { // only go up to next_3
$this.removeClass('next_' + num); // remove previous class
++num; // go up one
$this.addClass('next_' + num); // add the new class
$this.data("index", num); // store new current state
}
});
And a jsFiddle that shows it: http://jsfiddle.net/jfriend00/jpdjY/
or a more compact form:
$('#next_btn').click(function() {
var num = $(this).data("index") || 1; // get current state
if (num < 3) { // only go up to next_3
$(this).removeClass('next_' + num++).addClass('next_' + num).data("index", num);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I change the django-registration e-mail template "site" name? The current setup ends up substituting example.com into the below code from the template. I want it to point to localhost:8000
Without hard coding this, where and how can I change the template so that the site is linked to my localhost?
Thank you for registering an account at {{ site.domain }}.
To activate your registration, please visit the following page:
http://{{ site.domain }}{% url registration_activate activation_key %}
This page will expire in {{ expiration_days }} day{{ expiration_days|pluralize }}.
If you didn't register this account you can simply delete this email and we won't bother you again.
A: The site object in the template comes from the Django Site model. When you do a syncdb, it defaults automatically to example.com
If you login to Django's admin interface, you will find "Sites". Inside it, you will be able to change example.com to whatever you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Characters get trimmed when sending values from one page to another in asp.net I am sending some values from one page to another in asp.net using javascript. I have declared JS in parent page and the values are being sent to child page and fetched in code behind page using Request.Querystring. Look to my previous question here
To give you a detailed look, See below example
chStatusReport.Attributes.Add("onclick", "javascript:return Navigate( '" + varTrimmed+ "' );");
JS to open a child page is under
<script type="text/javascript" language="javascript">
function Navigate(status) {
window.open("ChildPage.aspx?status=" + status)
return false;
}
</script>
Code fetching the value pass from parent to child page.
if (Request.QueryString.Count!=0)
{ svar1= Request.QueryString["status"];
}
Values that are being passed are like 1 )Tom & Peter 2 ) Laurence & Hardy
The values that i get are 1 ) Tom 2) Laurence
Why the remaining text get trimmed?
A: Are you actually passing Tom & Peter? I.e., ChildPage.aspx?status=Tom & Peter?
If you are, then the query string will have:
QueryString["Status"] with Tom and QueryString["Peter"].
The & is a delmiter between value pairs in the query string.
You'll need to URL Encode the URI. Take a look at JavaScript encodeURIComponent.
A: You can't use & directly in querystring.
You have to either encode or change & to another unicode manually and translate it back.
Here is a link for explanation.
http://www.kamath.com/codelibrary/cl006_url.asp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery live not working with Jqtransform select while adding dynamic controls I have a functionality where we are adding a dynamic row while clicking a addrow button in a table.
My problem is that I have to alert a message while changing my select list in the new row but its not working when we use Jquery live click. But its working for all other select boxes which are not dynamically added while using Jquery bind click. Can anybody give me a help to resolve this?
In my project we are using Jqtransform for formatting html controls.
What i have done so far is
$('div.jqTransformSelectWrapper ul li a').live('click',function() {
alert('message');}
});
A: I have resolved this by modyfying the Jqtransform.js file by triggering the change event of the select list by doing the following. Actually its a bug regarding the Jqtransform.js
If you got to this post of mine you probably know what jqtransform is, and you are probably struggling with a dropdownlist's change event.
Reason why it is not working is due to the fact that jqtransform creates a dropdownlist using an unordered lists, then it hides your dropdownlist.
The fix is actually quite simple.
open your jquery.jqtransform.js file and find the following line:
/* Fire the onchange event */
if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) {
$select[0].selectedIndex = $(this).attr('index');
$select[0].onchange();
}
now simply add the following below that line:
/* Fire the change event */
if ($select[0].selectedIndex != $(this).attr('index')) {
$select[0].selectedIndex = $(this).attr('index');
$($select[0]).trigger('change');
}
A: Use jQuery delegate() instead. It's better than live for many reasons. Please use console.log() instead of alert() for debugging too!
$('div.jqTransformSelectWrapper ul li').delegate('a', 'click',function() {
console.log('message');}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "deferencing pointer to Incomplete type" error in c I have two structures like this
CODE EDITED:
typedef struct
{
int threadId;
void *stack;
}gtthread_t;
typedef struct
{
gtthread_t *th;
struct list *next;
}list;
In my code, i have used the structures like:
list *temp;
gtthread_t thread;
if(temp->next->th->threadId != thread.threadId && temp->next!=NULL) //error generated here
{
//do something
}
The error is also occuring here:
free(temp->next->th->stack);
What am i doing wrong here? I have a node in temp->next (it is not NULL).
Any help will be appreciated
A: typedef struct
{
gtthread_t *th;
list *next;
}list;
When the parser is at line 3, it has no idea what list means. Try
typedef struct list
{
gtthread_t *th;
struct list *next;
}list;
instead.
A: Just rewrite the list like this;
struct list
{
gtthread_t *th;
struct list *next;
};
typedef struct list list;
A: This structure also needs to be created: temp->next->th->threadId
i.e.
temp = (list *)malloc(sizeof(list));
temp->next = (list *)malloc(sizeof(list));
temp->next->th = (gtthread_t *)malloc(sizeof(gtthread_t));
temp->next->th->threadId = <some value>
temp->next->th->stack = <some value>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: update a part of field using matching id from another table I have table with following data
(here key field comprises of site__marker)
id userid key value
1 1 site_1_name http://example1.com
2 1 site_1_user user1
3 1 site_2_name http://example2.com
4 2 site_1_name http://example3.com
5 2 site_1_user user2
and I have site mapping table
oldsiteid newsiteid
1 120
2 152
Now I need to update first table in way that only values updates in key field
should match oldsiteid in second table, and should get updated by newsiteid
Output should be like
id userid key value
1 1 site_120_name http://example1.com
2 1 site_120_user user1
3 1 site_152_name http://example2.com
4 2 site_120_name http://example3.com
5 2 site_120_user user2
How to achieve this?
A: You will have to translate this REXX in SQL, the functions are staight forward:
old = 'user_1_ddd'
n = "333"
new = substr(a,1,index(a,"_")) || n || substr(a,index(a,"_") + index(substr(a, index(a,"_")+1) ,"_"))
results in user_333_ddd
substr is the same in both
for index, use Find_in_set
for || use concat
A: I do not have MySQL but this should work:
UPDATE TargetTable
SET key = CONCAT
(
SUBSTRING_INDEX(key,'_',1)
,'_'
, (SELECT newsiteid FROM MappingTable WHERE MappingTable.oldsiteid = SUBSTRING_INDEX(SUBSTRING_INDEX(TargetTable.key,'_',-2), '_', 1 ))
,'_'
,SUBSTRING_INDEX(key,'_',-1)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I find out which button was clicked? I've got my buttons working right, and I'm a listener to each button like this:
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
I need some way to find the button in the array.
A: In order to get label, try this.
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};
A: ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).
A: try this
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
A: private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
l1.setText("");//name of level what you want
t1.setText(null);//text field what you want
t2.setText(null);//text field what you want
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: SVN GIT respository server Our entire code is stored in a SVN respository on a remote server. However, my team here is in favor of using GIT local server by cloning svn repository using git-svn. The problem I face is how do I make sure that my local team members are able to clone the git-svn local repository and each "push" to local git-svn repository is published to SVN repository. I think I can run a cron job to rebase the git-svn repository with SVN repository every 20 or 30 min.
A: You can also add post-receive hook to commit pushed changes to svn.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multivalued attributes in Relational databases? How well an idea are multi-valued attributes in a relational database when they are to be referred extensively?
Let me give you an example to show what I mean. Suppose I have the following table:
UserID Attribute1
User1 a,b,c
User2 x,y,z
User3 a,x,y
User4 c,b,z
[a,b,c,x,y,z are to be strings]
There is another user User5 to whom I have to make some suggestions about other users based on whether his Attribute1 matches any one of other 4 users or not.
[In graph databases, the task could have been much easier as I could have created multiple nodes from the respective users using the same relationship.]
Now, this table is just a micro-level abstraction of what an actual database will look like. The number of rows in a table may run into hundreds of thousands, if not millions. Also, the multiple values may actually be a lot more than 3. Apart from this, the database can be under heavy load, and in that situation, there may be some issues.
So, are multi-valued attributes helpful in such cases? Or is there any better way of doing the same? One obvious way I can think of is to store it as:
UserID Attribute1
User1 a
User1 b
User1 c
User2 x
User2 y
User2 z
User3 a
User3 x
User3 y
User4 c
User4 b
User4 z
Any faster way of dealing such situations in databases? Or are there any built-in features of modern-day databases to exploit?
A: Having multiple values in a field is only useful if the data is dead weight in the database, i.e. if you only read the field out of the database and process it afterwards.
As soon as you want to use the values in the field in a query, you will take a huge performance hit from having to parse the value to compare it. If you put the values in separate records as in your second example, so that you can add an index on it, it's not unrealistic that the query will be 10 000 times faster.
Having a million records in a table is not a problem. We have some tables that have over 100 million records in them.
A: Apart from what the others have said regarding normalization, I'd like to answer to the "Or any inbuilt feature of modern-day databses to exploit?" part of your question:
PostgreSQL has a pretty nifty extension called hstore which does exactly that and in a highly optimized manner.
The hstore data type is essentially a key/value pair, where you can store anything. In your example something like this:
INSERT INTO user_attributes
(user_id, , attributes)
VALUES
(1, ('att1 => x, att2 => y'));
Will insert the keys att1 and att2 into the column attributes. This can be indexed to make lookups fast.
You can query the data using this syntax:
SELECT *
FROM user_attributes
WHERE attributes @> ('att1 => "Some Value"')
This will return all rows that have a key named att1 and where that is mapped to the value "Some Value". The above statement will use an existing index on the column, so the lookup is nearly as fast as with a "real" column. The above statement takes ~2ms on my laptop to find a row in a table with 100.000 rows.
You can also query for rows that have a specific attribute defined regardless of the value:
SELECT user_id,
(attributes -> 'att1')
FROM user_attributes
WHERE attributes ? 'att1'
will find all rows where att1 is defined and will output the value for those.
A: For a n-n table you could normalize it to 3 tables (in a transactional model) users - user_attribute - attributes where the user_attribute table consists out of the primary key of users and attributes.. Keys are usually indexed and therefore quite fast for read ops
EDIT AFTER QUESTION
Users
int Id PrimaryKey
string name
User_Attribute
UserId PrimaryKey (FK to Users.Id)
AttributeId PrimaryKey (FK to Attributes.Id)
Attributes
int Id PrimaryKey
Value
this would result in a table holding only the users, a table holding only the attributes and a table holding which user is holding what
for instance
Users User_Attribute Attrubutes
id Name UserId AttributeId Id Value
1 User1 1 1 1 Att1
2 User2 1 2 2 Att2
2 1 3 Att3
2 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: django MEDIA_ROOT if i am setting up apache (PRODUCTION) to serve static files(js,css,jpg,pdf,mp4),should i set the variable MEDIA_ROOT in settings.py.
I mean anyways any thing matching /media/ will be served by apache not django.So what exactly is then the use of MEDIA_ROOT.In such an enviornment is there any purpose of MEDIA_URL except as a shortcut to /media/.Similarly whats the purpose of ADMIN_MEDIA_PREFIX other than as a shortcut.
A: Here
I got the answer to my question(as mentioned in my comment).I is was reviewing my stalkoverflow profile and I saw this question unanswered and unclosed.So have pasted the link as an answer once again.
A: Yes, because you need to tell Django where to the browser can find those files that are being served by Apache.
A: difference is MEDIA_ROOT indicates where you should put your static files, and MEDIA_URL is the relative path where those are being served.
in a production environement, MEDIA_* paths are (commonly, but it's not strict to follow) used to store application related static files (css, imgs and javascripts). For user uploaded content, it's good practice (but again, it's not a rule) to save them inside the STATIC path, so you can move/delete/dostuff with them without compromising your app
so basically, to answer your question (didn't see any question mark in your post, btw) MEDIA_ROOT is the absolute path on the server where the static files have to be stored.
Here you can find something about MEDIA_ROOT and MEDIA_URL
Here something about static files management with django
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iOS: Create PDF from UIView I am trying to create a PDF from a UIView which may contain images, labels, etc.
I have checked the reference ( GeneratingPDF) and I am also aware of the renderInContext: method, which can be used to draw the UIView's content onto the PDF context.
I used renderInContext: to create a PDF. However, the images and the text lost their fidelity. i.e. The images were not selectable individually & the text could not be selected/copied, etc. in the resulting PDF. It was as good/bad as the PDF created from a snapshot of the UIView.
My question is, do I have to draw the texts & images individually to achieve what I want (using CGContextShowTextAtPoint & CGContextDrawImage)?
If yes, then how do I go about scanning the UIView for texts & images? Assume that I receive the UIView from outside & am not aware of its contents.
A: I've had a moderate amount of luck just walking my view hierarchy, and calling -drawRect: myself. There's a bit of set up that you've got do before each, like translating the ctm and clearing the text matrix, but when you've done that for each view, you can do this:
UIGraphicsPushContext(ctx);
[self drawRect:self.frame];
UIGraphicsPopContext();
The PDF it generates is vector based -- not just a flat bitmap, so it scales nicely and you can select the text in a viewer/browser. This only works on plain vanilla custom drawing and very simple stuff like UILabels. I doubt it would work with more complex UIKit objects (I'm thinking table views and scroll views). Also, you would need extra work for UIImageViews (which I'm guessing set the contents property of the layer with a CGImageRef), and if you've got other layer based attributes and transforms -- even more work.
Hopefully Apple will give us a better solution than maintaining parallel draw code!
A: You do indeed have to draw the texts/images individually into a CGContextRef (look at CGPDFContextCreateWithURL) using functions like CGContextShowTextAtPoint. While you could theoretically scan your UIView for images/labels, it would be better if you just draw the layout from scratch. You must have some way to know what elements should be in the UIView. Although the code will be very different, logically you should approach it the same way you would if you were going to draw the UIView programmatically instead of loading it from a nib.
If you really want to scan your UIView, you could do something like this:
for(UIView *subview in parentView.subviews) {
if([subview isKindOfClass:[UIImageView class]]) {
...
} else if([subview isKindOfClass:[UITextView class]]) {
...
} else if([subview isKindOfClass:[UILabel class]]) {
...
}
}
A: try,
{
//read the pdf file
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("iPhoneAppProgrammingGuide.pdf"), NULL, NULL);
PDFfile = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL)
CGPDFPageRef page = CGPDFDocumentGetPage(PDFfile,currentpage);
context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(context,self.bounds);
CGContextTranslateCTM(context, -1.0, [self bounds].size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFArtBox, [self bounds], 0, true));
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
//CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(page, kCGPDFMediaBox),
CGContextGetClipBoundingBox(context));
// CGContextConcatCTM(context, transform);
UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width, self.bounds.size.height));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compute (set) difference between arrays in PHP? I going to implement ACL (Access control list) in my php website.
In my system user have sum a of roles and permission.
Main algorithm is as follows:
permissions = (permissions_by_role + permission_for_user) - user_banned_permission
so I have three arrays and get those values from database.
For the first part I use this
$permissions = array_unique(array_merge($permission_by_role, $permission_by_user));
How can I remove my banned permission from permission array?
Now I have these two arrays:
$permissions and $permission_banned_for_user[]
A: sounds like a perfect use-case for array_diff:
$permissions = array_diff($permissions, $permission_banned_for_user);
A: What you need is array_diff() - Compares array1 against array2 and returns the difference.
$allowed = array('view', 'create', 'edit', 'delete', 'add');
$banned = array('add', 'delete');
$result = array_diff($allowed, $banned);
print_r($result); //Array ( [0] => view [1] => create [2] => edit )
A: If I am understanding the situation correctly you can do this easily by using the array_diff() function. Have a look here: http://www.php.net/manual/en/function.array-diff.php
This will take 2 arrays and return all elements that are in array 1 and not in array 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Conditional loading content based on category id magento for product page I want to conditionally load content based on category id in product page but can't get it to work. I know I can do this by calling a custom attribute but this is not what I have in mind because the content is specifically for a particular category so I don't want to enter it repeatedly in each product for the given category.
Basically I was looking for something like this:
<?php if ($_catid = $this->getCategoryid('3')):?>
display content for category id 3 (content is entered directly in the view.phtml file)
<?php else: ?>
content for other cateogegory
<?php endif; ?>
Your guidance is greatly appreciate!
Update for the correct code (thanks ahadley):
<?php $category = Mage::getModel('catalog/layer')->getCurrentCategory();?>
<?php if($category->getId()==3): ?>
<h3>Show content for Category ID3</h3>
<?php else: ?>
<h3>Show content for other categories</h3>
<p>consectetuer adipiscing elit. </p>
<?php endif; ?>
A: You could use something like the following to load the category:
<?php $category = Mage::getModel('catalog/layer')->getCurrentCategory();?>
Then you could get information such as:
<?php echo $category->getName();?>
A: You can do something like this in your product/view.phtml template:
<?php if (Mage::registry('current_category') == 3): ?>
// display content for category with the ID 3
<?php else: ?>
// content for other categories
<?php endif; ?>
A: This is final code, and working fine.
<?php if (Mage::registry('current_category') && Mage::registry('current_category')->getId() == 290) { ?>
<?php
$categoryIds = $_product->getCategoryIds();
$m = Mage::getModel('catalog/category')
->load($categoryIds[0])
->getParentCategory();
echo $m->getName();
?>
<?php } else ?>
<?php if (Mage::registry('current_category') && Mage::registry('current_category')->getId() == 202) { ?>
<?php
$categoryIds = $_product->getCategoryIds();
$m = Mage::getModel('catalog/category')
->load($categoryIds[2])
->getParentCategory();
echo $m->getName();
?>
<?php } else { ?>
<?php
$categoryIds = $_product->getCategoryIds();
$m = Mage::getModel('catalog/category')
->load($categoryIds[1])
->getParentCategory();
echo $m->getName();
?>
<?php } ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: netbeans: How to put some title in the title bar I developed a small desktop application in Net Beans. When i run my application there appears no title in the Windows Title bar. Is there anyway through which i specify some title which later on will appear in Windows title bar? Following is my Main method
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyJFrame().setVisible(true);
}
});
}
A:
You can see title property in properties window (Bottom right side). You can set title upon clicking that property.
If you are unable to find property window, just click on Design tab and then on blank JFrame GUI.
A: You can set the title bar at JFrame initialization time like this
JFrame frame = new JFrame("My Title");
or you can create public method for your custom class like
public void setTitle(String title){
frame.setTitle(title); // for this you have declare the frame object as global for this class only
}
and use like this way
MyJFrame myframe = new MyJFrame();
myframe.setTitle("my new title");
myframe.setVisible(true);
A: myTopLevelContainer = new myTopLevelContainer("myTitlaLabel");
or
myTopLevelContainer.setTitle("myTitlaLabel");
A: From the NetBeans Wiki:
To give your application a title, right click on the JFrame and open its properties dialog box. Click the properties tab.
Under the Properties tab, find and modify the title field. NetBeans will do the rest.
A: Okay, this worked for me ...
public yourGUIname() {
initComponents();
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("your image here")));
this.setTitle("your title here"); // that is the code you looking for
}
so what I did was put the above code in the generated public method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: is it possible to mock transient fields in tests? I have a class that contains a transient field. But the other part of the class is serializable.
In the tests I mock the field and the class and use the mocked class object in a deep copy function which looks like below:
try {
final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
objectOut = new ObjectOutputStream(bytesOut);
// serialize and pass the object
objectOut.writeObject(original);
objectOut.flush();
final ByteArrayInputStream bytesIn =
new ByteArrayInputStream(bytesOut.toByteArray());
objectIn = new ObjectInputStream(bytesIn);
@SuppressWarnings("unchecked")
final T clone = (T) objectIn.readObject();
// return the new object
return clone;
}
catch () {...}
the writeObject(original) method is supposed to write all non-transient and non-static fields. But I've got an error saying java.io.NotSerializableException for the mock transient field. I wonder if the transient field cannot be recognised in the tests? I use mockito as my framework.
A: What do you mean by "I mock the field and the class" ?
I just whipped up a quick test based on this dummy class:
public class DummyClass implements Serializable {
private static final long serialVersionUID = -4991860764538033995L;
transient private ChildClass child;
...
}
ChildClass is just an empty (non-Serializable) class. The test looks like this:
...
DummyClass dc = new DummyClass();
ChildClass mockChild = mock(ChildClass.class);
dc.setChild(mockChild);
copier.copy(dc);
... and that doesn't throw any NotSerializableException.
What are you trying to test? The deep-copier or the class that is passed to it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unit Testing Logs in WP7 application testing I m using Silverlight Unit Test framework for testing my application. The unit testing framework gets executed successfully and displays the result in the phone application page.
I would like to get the results stored in a log file inside the device itself instead of displaying it on the phone application page on the device. Please find the image below which shows the results displayed for an application
http://www.jeff.wilcox.name/wp-content/uploads/2010/03/SilverlightUnitTestFrameworkforWindowsPhone1_thumb.jpg
Please suggest if there is any way to do it.
Thanks,
Mugu
A: As far as I know the results are not stored in a log, but you can get access to the results.
From within the unit test's MainPage.xaml.cs you can hook into the TestHarness's TestHarnessCompleted event to get details about the completed test run. You can then format your output as required, and save to IsolatedStorage or/and transfer off the device.
//inside MainPageLoad()
var unitTestSettings = UnitTestSystem.CreateDefaultSettings();
unitTestSettings.TestHarness.TestHarnessCompleted += TestRunCompletedCallback;
var testPage = UnitTestSystem.CreateTestPage(unitTestSettings) as IMobileTestPage;
void TestRunCompletedCallback(object sender, TestHarnessCompletedEventArgs e) {
var testHarness = sender as UnitTestHarness;
foreach (var result in testHarness.Results) {
switch (result.Result) {
case TestOutcome.Passed:
case TestOutcome.Completed:
break;
default:
// must be a failure of some kind
// perform some outputting
break;
}
}
}
I think I read somewhere that there may be ways of transferring files programmatically from IsolatedStorage onto your desktop. I instead format the test results to a String and then use NLog to send that output to a listening service running on my desktop/buildserver. The full source NLog download provides a Visual Studio sample project for creating and running this sevice.
Cheers,
Al.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting the X and Y position of the mouse when it is clicked on the image in JLabel I have a Image displayed inside JLabel using ImageIcon feature.
The JLabel is contained inside a JPanel.
When image is clicked, I want to get the mouse position relative to the image.
I am trying to solve this problem by adding mouse listener to the JLabel which contains the
image.
Apparently, even if I set the size of JLabel with the width and height of the image, it seems that JLabel automatically stretches out to the size of JPanel.
So when below code runs, if the size of image is smaller than the JPanel, getting X and Y position returns the unwanted value.
Is there a way that I can specifically limit the size of the JLabel so that getting X position and Y position of the mouse will work fine?
Or better way to get a mouse position relative to the image? (which would be better)
ImageIcon icon = new ImageIcon(image);
JLabel imageLabel = new JLabel(icon);
imageLabel.setSize(image.getWidth(null), image.getHeight(null));
imageLabel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(imageLabel, e.getX()+" "+e.getY());
}
});
imageLabel.validate();
panel.add(imageLabel);
panel.validate();
A: It is all about the layout.
See this example for the above image.
It would seem this use-case requires a GridBagLayout or BoxLayout.
A: Your probably seeing problems because the Layout manager is controlling the size of your label, not the setSize() call.
I'd probably create my a JPanel derived class (instead of a JLabel) that implements paintComponent by drawing the image. Then i'd override getPreferredSize() and getMaximumSize() of the JPanel to return the dimensions of the image.
Using the label will cause troubles because there's going to be padding, offsets and such.
A: it seems that JLabel automatically stretches out to the size of JPanel.
problem is here
imageLabel.setSize(image.getWidth(null), image.getHeight(null));
if is there only one JLabel, then
myPanel.setLayout(new BorderLayout());//JPanel has by default FlowLayout
myPanel.add(myLabel, BorderLayout.CENTER)
if is there more that one JLabel with Image/IconImage and should be better look for GridLayout
EDIT
in all cases (for reall picture) before anything
1) you have to determine picture ratio 3:2, 4:3 16:10 ..., determine CropRatio then you have to :
*
*setPreferredSize(new Dimension(x/cropRatio, y/cropRatio)) for JLabel
*by using paintComponent g2d.fillRect(0, 0, x/cropRatio, y/cropRatio);
2) put JLabel to the JScrollPane, but then will be hold original amout of pixels
A: Your probably seeing problems because the Layout manager is controlling the size of your label, not the setSize() call.
I'd probably create my a JPanel derived class (instead of a JLabel) that implements paintComponent by drawing the image. Then i'd override getPreferredSize() and getMaximumSize() of the JPanel to return the dimensions of the image.
Using the label will cause troubles because there's going to be padding and such.
But in the end, what's causing our label to expand is the layout manager. Most like the easiest way to do what you want is to make sure your layout manager isn't expanding the label, by picking a layout manager that keeps the component at it's preferred size.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 3.1 recommended practice for managing library javascripts I'm curious what is the recommend approach for organizing and using library javascripts (things like Backbone, Underscore, Modernizr, etc.) in Rails. I've noticed a number of different practices so it seems to get a bit confusing.
There are a number of gems that provide the ability to bundle things like Modernizr, Backbone, Underscore, etc. Is this a preferred approach for cases where a gem exists?
For cases where a gem doesn't exist would it make sense to use the /public folder or the /app/assets/javascripts and go via the pipeline?
A: Just to add something (the answer of @DevinM is wonderful), here are my thoughts about using JavaScript in Rails:
*
*If there is a Gem that bundles a JavaScript library (like jquery-rails) I would stick to that:
*
*Keeps the library away from your code.
*Adds the libraries automatically to rails (or at least explains how to do that).
*Helps you to update the library automatically through bundle update if you want to.
*If there is no integration by a Gem, keep it under vendor/assets as described:
*
*Ensures that the library is known as external.
*Document the need to that library somewhere (e.g. in your application.js file)
*Your own libraries in lib/assets as described.
*application.js or the controller dependent *.js files in your app/assets/javascripts folder.
*Use application.js mostly for wiring, that means how to integrate the other libraries into your application. Explain there what the code means: used library, reference to documentation, meaning of configuration.
My experience is that after some time, you don't remember what the reason for a library was, so some house-keeping helps you stay healthy.
A: I would take a look at the Rails Guide for this question.
Assets can be placed inside an application in one of three locations:
app/assets, lib/assets or vendor/assets.
app/assets is for assets that are owned by the application, such as
custom images, JavaScript files or stylesheets.
lib/assets is for your own libraries’ code that doesn’t really fit
into the scope of the application or those libraries which are shared
across applications.
vendor/assets is for assets that are owned by outside entities, such
as code for JavaScript plugins.
What I would do is place all the JS files that you dont maintain is vendor/assets, if this folder is missing you can just create it. And as far as using gems for your assets thats usually fine for larger frameworks and libraries like jQuery however I would shy away from them for stuff like Backbone.js and others just to keep the gemfile clean and reduce some bloat you might see with that.
If you need any clarification let me know and good luck with your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python how to check if variable exist and its length, in one if statement? Here's my situation:
if var:
if len(var) == 5:
do something...
else:
do the same thing...
To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check its length... Any idea?
I would like something like this:
if var and len(var) == 5:
do something...
A: The code as you've written it in the question executes the statements in two cases:
*
*var evaluates to true and has a length of 5
*var evaluates to false (e.g. it's None or False)
You can combine those into one conditional as follows:
if not var or len(var) == 5:
...
The conditional that some other answers are suggesting, var and len(var) == 5, only evaluates to True in the first case, not the second. I will say, though, that the two cases you've chosen are kind of an unusual combination. Are you sure you didn't intend to execute the statements only if the variable has a non-false value and has a length of 5?
Additionally, as 6502 wrote in a comment, functions are intended for exactly this case, namely making reusable code blocks. So another easy solution would be
def f():
....
if var:
if var.length == 5:
f()
else:
f()
A: Did you try that? It works:
if var and len(var) == 5:
....
The and operator doesn't evaluate the RHS if the LHS is false. Try this:
>>> False and 1/0
False
>>> True and 1/0
ZeroDivisionError: division by zero
A: Well, exceptions seem to be perfectly fine here.
try:
if len(var) == 5:
do_something()
except TypeError:
pass
You're saying that var can be null, therefore a TypeError exception would be thrown. If, however, in fact var can be non-existant at all, you should catch for NameError exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Blackberry swipe left/right gesture
Possible Duplicate:
How may I use touch gestures to scroll through a series of pictures?
I want to display array of images one after another by using swipe left or swipe right gesture.Can anybody give me some idea as how to this.A simple example will be really useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Images in HTML table row This has been driving me mad and it's probably the silliest mistake ever!
Basically all I want is each picture to have a small box underneath with their name.
I want 4 pictures, all in a row.
Unfortunately this is what happens in IE:
I'm so sorry that this looks extremely messy! Any help MUCH appreciated!
<table style="background-color:#FFFFFF" width="100%" border-collapse:collapse>
{section name=signups_loop loop=$signups max=4}
<a href='{$url->url_create("profile",$signups[signups_loop]->user_info.user_username)}'><img src='{$signups[signups_loop]->user_photo("./images/nophoto.gif")}' width='169' height='172' border='0' vertical-align=bottom></a>
{cycle name="startrow" values="<tr>,,,,"}
<td width=201>
<div style="background-color:#809DFF; height: 25px; width: 169px; margin-top: -15px>
<font size="1" face="Tahoma" color="black"><b><div id="feat3">
<a href='{$url->url_create("profile",$signups[signups_loop]->user_info.user_username)}'><font color="white" face="Tahoma">{$signups[signups_loop]->user_displayname|truncate:15:"...":true}</font></a></b><br></font></font></div>
</td>
{cycle name="endrow" values=",,,,</tr>"}
{/section}</table>
A: You can try placing the relevant text with the image, inside a container - with a floating left value.
e.g. (bare in mind I did not test this, but hopefully it helps)
<table style="background-color:#FFFFFF" width="100%" border-collapse:collapse>
<tr>
<td>
{section name=signups_loop loop=$signups max=4}
<div class="imageItemWithTextContainer" style="width:169px; float:left; "> <!-- CONTAINER START -->
<a href='{$url->url_create("profile",$signups[signups_loop]->user_info.user_username)}'><img src='{$signups[signups_loop]->user_photo("./images/nophoto.gif")}' width='169' height='172' border='0' vertical-align=bottom></a>
<div style="background-color:#809DFF; height: 25px; width: 169px; margin-top: -15px>
<font size="1" face="Tahoma" color="black"><b><div id="feat3">
<a href='{$url->url_create("profile",$signups[signups_loop]->user_info.user_username)}'><font color="white" face="Tahoma">{$signups[signups_loop]->user_displayname|truncate:15:"...":true}</font></a></b><br></font></font></div>
</div> <!-- CONTAINER END -->
{/section}
</td>
</tr>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Explain this type-mismatch in lazy evaluation Trying to grok this comment, I wrote the following code:
def breakfast : AnyRef = {
class Chicken (e: =>Egg) {
lazy val offspring = e
}
class Egg (c: =>Chicken) {
lazy val mother = c
}
lazy val (egg: Egg, chicken: Chicken) = (new Egg(chicken),
new Chicken(egg))
egg
}
And it works and it does exactly what you'd hope it'd do. What I don't get is, why is the : AnyRef necessary? If it's not included, the compiler (the 2.8 compiler at least) dies a horrible death:
error: type mismatch; found : Egg(in lazy value scala_repl_value)
where type Egg(in lazy value scala_repl_value) <: java.lang.Object
with ScalaObject{lazy def mother: Chicken} required: (some
other)Egg(in lazy value scala_repl_value) forSome { type (some
other)Egg(in lazy value scala_repl_value) <: java.lang.Object with
ScalaObject{lazy def mother: Chicken}; type Chicken <:
java.lang.Object with ScalaObject{lazy def offspring: (some
other)Egg(in lazy value scala_repl_value)} } object
RequestResult$line16$object {
Can somebody explain what's going on here?
A: You define classes Chicken and Egg in scope of breakfast function, so they are not seen outside i.e. nobody except breakfast don't know these classes. In Scala 2.9 this snippet actually works, and breakfast function's return value is defined as
def breakfast: Egg forSome { type Egg <: java.lang.object with scalaobject{lazy val mother: chicken}; type chicken <
When classes defined outside of function everything works as expected
class Chicken(e: => Egg) {
lazy val offspring = e
}
class Egg(c: => Chicken) {
lazy val mother = c
}
def breakfast: Egg = {
lazy val (egg: Egg, chicken: Chicken) =
(new Egg(chicken), new Chicken(egg))
egg
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to stop jquery fadeIn from scrolling the page I am using jquery fadeIn like this
imgTag = '<img src="../../../images/leadGenAdPreview.jpg" alt=""/>';
$('#previewImg').hide();
$('#previewImg').html(imgTag).fadeIn(1000);
What this does is, it scrolls up the page all the way up. The section which I want to fadeIn is quite a bit down on page. And I would best prefer page not to scroll at all. How can this be achieved ?
This is the entire snippet
$('#previewImg').hide();
$('#previewImg').html(imgTag).fadeTo(1000,100);
var currentlySelected = $('.inFoo-tabs-select');
$(currentlySelected).removeClass('inFoo-tabs-select'); $(obj).attr('class',$(obj).attr('class')+' inFoo-tabs-select');
goToScroll('infooterDemo');
Because my target element is some way down the page, i was using scroll function. once i click on target element, fadeIn, and scroll down to it, next time I click on it, I dont want it to scroll back up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to show toast in Runnable class on Java, Android? I have a class implements Runnable interface, and I need show Toast from this class. How can I do that?
A: You can make use of handlers to display a Toast. Because few things in Android must be done from UI thread only. Try this,
Do this in your onCreate(),
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progressDialog.cancel();
if (msg.what == 0) {
Toast.makeText(Catering.this,"Hi toast",Toast.LENGTH_LONG).show();
}
}};
And now your thread,
final Thread Fetcher = new Thread(new Runnable() {
public void run() {
handler.sendEmptyMessage(0);
});
Fetcher.start();
A: The issue isn't whether or not it implements Runnable. The issue is that it has to be run by the main display thread, and will need access to the Activity's context. If you paste your code, we can help you fix it.
A: I think you are getting error because you are creating and showing Toast from a NON-GUI thread. You can only write to the display from the GUI thread. Post your code for us to help you further.
A: I think you want to do as like:
current class:
take a contex's object and pass contex.this to implemented class's constructor.
in that constructor you should write:
this.context1 = context;
at the toast showing you should pass context1.
i think this will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Images in App looks Blurry I have developed an application in Android,and followed all design guideline in it.
But when i run app on Device images looks blurry(less sharper).
Can anyone tell me what actually the problem is?
Or
What are the guidelines followed by Graphic Designer while designing the graphics for Android application?
A: You can try 9-patch image which is nothing but a stretchable bitmap image.Check following links for more details
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
http://developer.android.com/guide/developing/tools/draw9patch.html
A: This is most likely your interpretation of what Android is doing behind the scenes to scale the images to look *right on whatever screen you're looking at them on.
Try manually setting the layout_width and layout_height to the actual dimensions of the images with px (rather than dip) and see if that makes it look sharp. If so, you'll want to create different versions for different resolutions.
You don't want to leave them set to their pixel widths, just do it to see if that's what's causing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to generate xcode project using qmake with QT using
qmake -spec macx-xcode
can only generate older version test.pbproj and can not open in xcode 4
How to generate test.xcodeproj
A: It's a bug, but if you go here to the bug reports you'll find some notes on what people did to fix it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can i change clisp's current directory once started? In ghci, i can use "cd" to change its current directory as below:
$cat ~/.ghci
:def hoogle \str -> return $ ":! hoogle --count=15 \"" ++ str ++ "\""
:cd /media/E/work
:load Money
Then once started, ghci will change its current directory. Can i do the same thing in clisp ? Maybe need to modify ~/.clisprc ... ?
Sincerely!
A: It is VERY easy :
>cat ~/.clisprc.lisp
;;; The following lines added by ql:add-to-init-file:
#-quicklisp
(let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname))))
(when (probe-file quicklisp-init)
(load quicklisp-init)))
;(pushnew "/media/E/lisp/" asdf:*central-registry* :test #'equal)
(cd "/media/E/www/qachina/db/doc/money")
(load "money")
The cd function works great !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: define ostream operator << to sum two struct i have following code to sum two struct elements
#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
struct USC{
int dollars;
int cents;
USC operator+(const USC o){
USC temp={0,0};
temp.cents=cents+o.cents;
temp.dollars=dollars+o.dollars;
if (temp.cents>=100){
temp.dollars+=1;
temp.cents-=100;
}
return temp;
}
}; /* <-- make sure that semicolon is there */
ostream& operator<<(ostream &output, const USCurrency &o) {
output<<o.dollars<<" "<<o.cents<<endl;
return output;
}
int main(){
USC a={2,50};
USC b={1,75};
USC c=a+b;
cout<<c<<endl;
return 0;
}
but here is a list of errors
1>------ Build started: Project: struct, Configuration: Debug Win32 ------
1> struct.cpp
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2143: syntax error : missing ';' before '&'
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2872: 'ostream' : ambiguous symbol
1> could be 'c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23) : USC ostream'
1> or 'c:\program files\microsoft visual studio 10.0\vc\include\iosfwd(636) : std::ostream'
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2872: 'ostream' : ambiguous symbol
1> could be 'c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23) : USC ostream'
1> or 'c:\program files\microsoft visual studio 10.0\vc\include\iosfwd(636) : std::ostream'
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2065: 'output' : undeclared identifier
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2059: syntax error : 'const'
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2143: syntax error : missing ';' before '{'
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2447: '{' : missing function header (old-style formal list?)
1>c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(34): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'USC' (or there is no acceptable conversion)
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(726): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(764): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(811): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(937): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const signed char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(944): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,signed char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(951): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const unsigned char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(958): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,unsigned char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(968): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>,USC>(std::basic_ostream<_Elem,_Traits> &&,_Ty)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ty=USC
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(1085): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const std::error_code &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(186): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::basic_ostream<_Elem,_Traits> &(__cdecl *)(std::basic_ostream<_Elem,_Traits> &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(192): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::basic_ios<_Elem,_Traits> &(__cdecl *)(std::basic_ios<_Elem,_Traits> &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(199): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::ios_base &(__cdecl *)(std::ios_base &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(206): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::_Bool)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(226): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(short)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(260): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(unsigned short)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(280): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(int)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(305): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(unsigned int)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(325): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(long)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(345): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(unsigned long)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(366): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(__int64)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(386): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(unsigned __int64)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(407): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(float)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(427): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(double)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(447): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(long double)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(467): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(const void *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(487): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::basic_streambuf<_Elem,_Traits> *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> while trying to match the argument list '(std::ostream, USC)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
please guys help me what is wrong?
A: You need a semicolon after the struct definition (after the curly brace on line 22)
I edited the post to show where it goes
A: The compiler said it to you:
c:\users\datuashvili\documents\visual studio 2010\projects\struct\struct\struct.cpp(23): error C2143: syntax error : missing ';' before '&'
In general, when you have compilation errors, start from the first one... (-`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Determine if a number being dialed is in the contact list Im trying to write my first android app. Coming from a winmobile phone, there was an option to block my outgoing caller id, not so with android.
Ive got a small app started that will add *67 to outgoing calls the problem is it adds *67 to every call, I dont want to add this to people in my contact list so they can see that its me thats calling. I just want to block my caller Id to unknown numbers
this is all the code so far and its working in the emulator, the basics came from http://androidcookbook.com/Recipe.seam?recipeId=1151
public class OutgoingCallInterceptor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String originalNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String myNumber = originalNumber;
String msg3 = "Caller Id Already Blocked " + myNumber;
String msg4 = "Blocking Caller Id " + myNumber;
if(myNumber.contains("*67") == true)
{
Toast.makeText(context, msg3, Toast.LENGTH_LONG).show();
this.setResultData(originalNumber);
} else {
Toast.makeText(context, msg4, Toast.LENGTH_LONG).show();
this.setResultData("*67" + originalNumber);
final String newNumber = this.getResultData();
String msg = "Caller Id Blocked - Old number " + originalNumber + ", new number " + newNumber;
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}}
Can someone point me in the right direction here? Im not sure how to check the number im dialing against the contact list
A: what are you asking is that you want to fetch the call log details.You can do so:
Uri UriCalls = Uri.parse("content://call_log/calls");
Cursor cursor = getContentResolver().query(UriCalls, null, null, null, null);
refer this doc for more clearity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default keyring password Im a newbie to Linux, and now using CentOS 6. I am using the MySQL workbench here, and whenever i try to add a new connection, it asks me the default keyring password. I really dont know, from where is this password set, i didnt set it before.
Can any one tell me how to solve this problem?
Thanks
A: This may be related to the gnome-keyring daemon.
http://dev.mysql.com/doc/workbench/en/wb-manage-db-connections-vault.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP pass array element by reference I have two arrays, one indexed and one associative. What my question boils down to is, how can I pass the associative array's reference to the edit class. This way when there are more books and movies, I can loop through, clean all the isbn's and not touch movie. The problem I'm having is passing the reference inside the for loop.
$i = new intro();
class intro{
public function __construct(){
$index = array(array("book", "regex"), array("movie", "regex"));
$assoc = array(array("book"=>"freeBSD", "isbn"=>"01-2345-6789"),
array("movie"=>"batman", "date"=>"10-10-1995");
for($x = 0; $x < count($index); $x++){
if($index[$x]["book"] == key($assoc)){
edit::modify(current($assoc)); //I WANT TO PASS THE REFERENCE NOT VALUE
} //current(&$assoc) DOES NOT WORK
next($assoc);
}
}
}
class edit{
public function modify(&$isbn){
$pattern = "/[^0-9]*/";
$isbn = preg_replace($pattern, "", $isbn);
}
}
A: Posting it here as reference since this was solved in the comments
doing &$assoc[key($assoc)] will solve the problem.
for($x = 0; $x < count($index); $x++){
if($index[$x]["book"] == key($assoc)){
edit::modify(&$assoc[key($assoc)]);
}
next($assoc);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why is [Char]-based input so much slower than the [Char]-based output in Haskell? It is a common knowledge that one does not use [Char] to read large amounts of data in Haskell. One uses ByteStrings to do the job.
The usual explanation for this is that Chars are large and lists add their overhead.
However, this does not seem to cause any problems with the output.
For example the following program:
main = interact $ const $ unwords $ map show $ replicate 500000 38000000
takes just 131 ms to run on my computer, while the following one:
import Data.List
sum' :: [Int] -> Int
sum' = foldl' (+) 0
main = interact $ show . sum' . map read . words
takes 3.38 seconds if fed the output of the first program as an input!
What is the reason for such a disparity between the input and output performance using Strings?
A: I don't think that this issue necessarily has to do with I/O. Rather, it demonstrates that the Read instance for Int is pretty inefficient.
First, consider the following program which just processes a lazy list. It takes 4.1s on my machine (compiled with -O2):
main = print $ sum' $ map read $ words
$ unwords $ map show $ replicate 500000 38000000
Replacing the read function with length drops the time down to 0.48s:
main = print $ sum' $ map length $ words
$ unwords $ map show $ replicate 500000 38000000
Furthermore, replacing the read function with a handwritten version results in a time of 0.52s:
main = print $ sum' $ map myread $ words
$ unwords $ map show $ replicate 500000 38000000
myread :: String -> Int
myread = loop 0
where
loop n [] = n
loop n (d:ds) = let d' = fromEnum d - fromEnum '0' :: Int
n' = 10 * n + d'
in loop n' ds
My guess as to why read is so inefficient is that its implementation uses the Text.ParserCombinators.ReadP module, which may not be the fastest choice for the simple case of reading a single integer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to close WPF window (dialog box) when Enter key is pressed? I have a WPF window which opens as a modal dialog.
On dialog, I have OK & Cancel buttons with IsDefault & IsCancel properties set to True for them respectively. Both the buttons have Click event handlers which close the dialog box.
Here is the relevant XAML:
<StackPanel Orientation="Horizontal" Grid.Row="1" Height="45" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="190">
<Button Content="OK"
Height="25" Margin="10,10,10,10" Width="75" Name="btnOK" TabIndex="1600" IsDefault="True" Click="btnOK_Click"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
<Button Content="Cancel"
Height="25" Margin="10,10,10,10" Width="75" Name="btnCancel" TabIndex="1700" IsCancel="True"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="btnCancel_Click" />
</StackPanel>
Here is the code behind:
private void btnOK_Click(object sender, RoutedEventArgs e)
{
// My some business logic is here
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
When I press Esc button on the keyboard (even when focus is not on the Cancel button), the dialog box gets closed as expected. However, when I press Enter key when focus is NOT on the OK button, nothing happens.
I have a DataGrid on the dialog. I want to close the dialog when I select any row in the data grid and press enter.
How to make this thing happen?
Some additional information: I have a text box on the dialog. And it has the event handler for the Keyboard.PreviewKeyDown event. When I am in the text box and I press enter, the dialog box should not be closed. But I can remove this handler. Important thing is to get above question resolved.
private void tbxSearchString_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.Search(); // Does some searching
}
}
A: Your code is working fine for me. it close dialog when I press enter. You can write e.Handled = true; line after your search functionality in tbxSearchString_PreviewKeyDown event. So it will not close dialog.
<Grid>
<TextBox Name="tbxSearchString" HorizontalAlignment="Left" Width="100" Height="30" Grid.Row="0" PreviewKeyDown="tt_PreviewKeyDown"></TextBox>
<StackPanel Orientation="Horizontal" Grid.Row="1" Height="45" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="190">
<Button Content="OK"
Height="25" Margin="10,10,10,10" Width="75" Name="btnOK" TabIndex="1600" IsDefault="True" Click="btnOK_Click"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
<Button Content="Cancel"
Height="25" Margin="10,10,10,10" Width="75" Name="btnCancel" TabIndex="1700" IsCancel="True"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="btnCancel_Click" />
</StackPanel>
</Grid>
Code behind
private void btnOK_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void tbxSearchString_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.Search();
e.Handled = true;
}
}
A: there is no built-in way to close the dialog window in wpf. what you have to do, is to set the DialogResult for your default button. so all you need is the following:
xaml
<Button Content="OK"
Height="25" Margin="10,10,10,10" Width="75" Name="btnOK" TabIndex="1600" IsDefault="True" Click="btnOK_Click"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
codebehind:
private void btnOK_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
A: You shouldn't be calling Close() or handling PreviewKeyDown yourself.
The proper way to do this is to have Ok/Cancel buttons, and use Button.IsDefault, Button.IsCancel, and Window.DialogResult. If the 'enter' press is unhandled in your textbox, the keypress will propagate to the Window and the default button will be pressed.
MyForm.xaml:
<Button x:Name="btnOk" Content="Ok" Click="btnOk_Click" IsDefault="True"/>
<Button x:Name="btnCancel" Content="Cancel" Click="btnCancel_Click" IsCancel="True"/>
MyForm.xaml.cs:
private void btnOk_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
Now hitting enter or escape on any textbox in the form will close the form (with the proper result)
A: Just set the AcceptButton member to the button property name.
AcceptButton = btnOK; // button used when ENTER is pressed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Does TFS branching have a child parent relation? When doing branches in tfs, does it matter if you are branching A to B or from B to A? The thing is that we have branch A and branch B, and now branch A has got messed up and we would like to recreate it from branch B by branching a new branch from B. As far as I know when you do a branch you get a relationship between the branches, but you don't get a "parent-child" relation, is that correct?
Is my question clear?
A: At the point where a new branch is constructed, it gets equal to what you chosen to branch out from. The tricky point about TFS-merging (as opposed, for example to the P4 intergration, or ClearCase merges) is that at any given point merging A-->B & B-->A will not generate the equal amount of merge candidates.
Let's say branch A generates branch B:
------->A
\
\
-----> B
Let's say you make changes in A:
------->A-->A'
\
\
-----> B
If you try to merge A' --> B you will get as merge candidates all your changesets/source files that were changed from A-->A'.
But if you try to merge B --> A' you will get no merge candidates at all.
This behavior is regardless of fact that A is 'parent'.
If your 'A' is messed and cannot be rectifed with regular merge from B-->A, you have the following options:
*
*Destroy A and generate a fresh copy of B in a new branch C
*Rollback changes from A, until it reaches 'stable'
*Perform a baseless merge
from B-->A and force B-state on A
(Possible slightly off-topic, but an excellent read nevertheless - and valuable for my grasping of the TFS-way: This article by R.Banks)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What are the pros and cons of performing calculations in sql vs. in your application shopkeeper table has following fields:
id (bigint),amount (numeric(19,2)),createddate (timestamp)
Let's say, I have the above table. I want to get the records for yesterday and
generate a report by having the amount printed to cents.
One way of doing is to perform calculations in my java application and execute a simple query
Date previousDate ;// $1 calculate in application
Date todayDate;// $2 calculate in application
select amount where createddate between $1 and $2
and then loop through the records and convert amount to cents in my java application and generate the report
Another way is like performing calculations in sql query itself:
select cast(amount * 100 as int) as "Cents"
from shopkeeper where createddate between date_trunc('day', now()) - interval '1 day' and date_trunc('day', now())
and then loop through the records and generate the report
In one way , all my processing is done in java application and a simple query is fired.
In other case all the conversions and calculations is done in Sql query.
The above use case is just an example, in a real scenario a table can have many columns that require processing of the similar kind.
Can you please tell me which approach is better in terms of performance and other aspects and why?
A: In this case you are probably slightly better off doing the calculation in SQL as the database engine is likely to have a more efficient decimal arithmetic routines than Java.
Generally though for row level calculations there is not much difference.
Where it does make a difference is:
*
*Aggregate calculations like SUM(), AVG(),MIN(), MAX() here the database engine will be an order of magnitude faster than a Java implementation.
*Anywhere the calculation is used to filter rows. Filtering at the DB is much more efficient than reading a row and then discarding it.
A: It depends on a lot of factors - but most crucially:
*
*complexity of calculations (prefer doing complex crunching on an app-server, since that scales out; rather than a db server, which scales up)
*volume of data (if you need to access/aggregate a lot of data, doing it at the db server will save bandwidth, and disk io if the aggregates can be done inside indexes)
*convenience (sql is not the best language for complex work - especially not great for procedural work, but very good for set-based work; lousy error-handling, though)
As always, if you do bring the data back to the app-server, minimising the columns and rows will be to your advantage. Making sure the query is tuned and appropriately indexed will help either scenario.
Re your note:
and then loop through the records
Looping through records is almost always the wrong thing to do in sql - writing a set-based operation is preferred.
As a general rule, I prefer to keep the database's job to a minimum "store this data, fetch this data" - however, there are always examples of scenarios where an elegant query at the server can save a lot of bandwidth.
Also consider: if this is computationally expensive, can it be cached somewhere?
If you want an accurate "which is better"; code it both ways and compare it (noting that a first draft of either is likely not 100% tuned). But factor in typical usage to that: if, in reality, it is being called 5 times (separately) at once, then simulate that: don't compare just a single "1 of these vs 1 of those".
A: In general do things in SQL if there are chances that also other modules or component in same or other projects will need to get those results. an atomic operation done server side is also better because you just need to invoke the stored proc from any db management tool to get final values without further processing.
In some cases this does not apply but when it does it makes sense. also in general the db box has the best hardware and performances.
A: There's no black / white with respect to what parts of data access logic should be performed in SQL and what parts should be performed in your application. I like Mark Gravell's wording, distinguishing between
*
*complex calculations
*data-intensive calculations
The power and expressivity of SQL is heavily underestimated. Since the introduction of window functions, a lot of non-strictly set-oriented calculations can be performed very easily and elegantly in the database.
Three rules of thumb should always be followed, regardless of the overall application architecture:
*
*keep the amount of data transferred between database and application slim (in favour of calculating stuff in the DB)
*keep the amount of data loaded from the disk by the database slim (in favour of letting the database optimise statements to avoid unnecessary data access)
*don't push the database to its CPU limits with complex, concurrent calculations (in favour of pulling data into application memory and performing calculations there)
In my experience, with a decent DBA and some decent knowledge about your decent database, you won't run into your DBs CPU limits very soon.
Some further reading where these things are explained:
*
*10 Common Mistakes Java Developers Make When Writing SQL
*10 More Common Mistakes Java Developers Make When Writing SQL
A: As far as PostgreSQL is concerned, you can do much on the server, quite efficiently. An RDBMS naturally excels at sorting, aggregating, casting, and formatting data to begin with. (I would claim that Postgres does a particularly great job.) The RDBMS can work with original data types from original storage. After processing, typically (much) less data has to be transferred.
Clients typically need (much) more data than is used / displayed eventually to perform the mentioned operations. They typically talk to the server using the "text" protocol, casting back and forth adds cost. Much work has to be duplicated. It's no a level playing field.
For procedural needs you can choose from a variety of server-side script languages: tcl, python, perl and many more. Mostly, PL/pgSQL is used, though.
Let me use a metaphor: if you want to buy a golden necklace in Paris, the goldsmith could sit in Cape Town or Paris, that is a matter of skill and taste. But you would never ship tons of gold ore from South Africa to France for that. The ore is processed at the mining site (or at least in the general area), only the gold gets shipped. The same should be true for apps and databases.
Worst case scenario would be to repeatedly go to the server for every single row of a larger set. (That would be like shipping one ton of ore a time.)
Second in line, if you send a cascade of queries, each depending on the one before, while all of it could be done in one query or procedure on the server. (That's like shipping the gold, and each of the jewels with a separate ship, sequentially.)
Going back and forth between app and server is relatively expensive. For server and client. Try to cut down on that, and you will win - ergo: use server side procedures and / or sophisticated SQL where necessary.
We just finished a project where we packed almost all complex queries into Postgres functions. The app hands over parameters and gets the datasets it needs. Fast, clean, simple (for the app developer), I/O reduced to a minimum ... a shiny necklace with a low carbon footprint.
A: Whether to perform calculations at the front end or at the backend is very much decided if we can determine our goal in the business implementation. At time java code might perform better than a sql code both well written or it might be vice-versa. But still if confused you can try to determine first -
*
*If you can achieve something straightforward via database sql then better go for it as db will perform much better and do computations there and then with the result fetch. However if the actual computation requires too much calculation from here and there stuff then you can go with the application code. Why? Because scenario's like looping in most cases are not best handled by sql wherease front end languages are better designed for these things.
*In case similar calculation is required from many places then obviously placing the calculation code at the db end will be better to keep things at the same place.
*If there are lots of calculations to be done to attain the final result via many different queries then also go for db end as you can place the same code in a stored procedure to perform better than retrieving results from backend and then computing them at the front end.
There are many other aspects which you can think before you decide where to place the code. One perception is totally wrong - Everything can be done best in Java (app code) and/or everything is best to be done by the db (sql code).
A: If you are writing on top of ORM or writing casual low-performance applications, use whatever pattern simplifies the application. If you are writing a high performance application and thinking carefully about scale, you will win by moving processing to data. I strongly advocate moving the processing to the data.
Let's think about this in two steps: (1) OLTP (small number of record) transactions. (2) OLAP (long scans of many records).
In the OLTP case, if you want to be fast (10k - 100k transactions per second), you must remove latch, lock and dead lock contention from the database. This means that you need to eliminate long stalls in transactions: round trips from client to DB to move processing to the client are one such long stall. You can't have long lived transactions (to make read/update atomic) and have very high throughput.
Re: horizontal scaling. Modern databases scale horizontally. Those systems implement HA and fault tolerance already. Leverage that and try to simplify your application space.
Let's look at OLAP -- in this case it should be obvious that dragging possibly terrabytes of data back to the application is a horrible idea. These systems are built specifically to operate extremely efficiently against compressed, pre-organized columnar data. Modern OLAP systems also scale horizontally and have sophisticated query planners that disperse work horizontally (internally moving processing to data).
A: I don't believe the performance differences can be reasoned about without specific examples and benchmarks, but I have another take:
Which can you maintain better? For example, you might want to switch your front-end from Java to Flash, or HTML5, or C++, or something else. A vast number of programs have gone through such a change, or even exist in more than one language to begin with, because they need to work on multiple devices.
Even if you have a proper middle layer (from the example given, it seems like that's not the case), that layer might change and JBoss might become Ruby/Rails.
On the other hand, it is unlikely that you will replace the SQL-backend with something that's not a relational DB with SQL and even if you do, you will have to rewrite the front-end from scratch anyway, so the point is moot.
My idea is that if you do calculations in the DB, it will be much easier to write a second front-end or middle-layer later, because you don't have to re-implement everything. In practise however, I think "where can I do this with code that people will understand" is the most important factor.
A: Form a performance point of view: This is a very simple arithmetic operation which almost certainly can be performed much faster than actually fetching the data from the disks that underly the database. Also, calculating the values in the where clause is likely to be very fast on any runtime. In summary, the bottleneck should be disk IO, not the computation of the values.
As per readability, I think if you use an ORM you should do it in your app server environment, because the ORM will let you work with the underlying data very easily, using set based operations. If you are going to write raw SQL anyway, there's nothing wrong with doing the computation there, Your SQL would also look a little nicer and easier to read if formatted properly.
A: Crucially, "performance" isn't defined.
The one that matters to me the most is developer time.
Write the SQL query. If it's too slow or the DB becomes a bottleneck, then reconsider. By that time, you'll be able to benchmark the two approaches and make your decision based on real data relevant to your setup (hardware and whatever stack you're on).
A: To simplify how to answer this would be to look at load balancing. You want to put the load where you have the most capacity (if it makes any sense). In most systems it is the SQL server that quickly becomes a bottleneck so the probably answer is that you don't want SQL doing one ounce of work more than it has to.
Also in most architectures it is the SQL server(s) that make up the core of the system and outside systems that get added on.
But the math above is so trivial that unless you are pushing your system to the limit the best place to put it is where you want to put it. If the math were not trivial such as calculating sin/cos/tan for say a distance calculation then the effort might become non-trivial and require careful planning and testing.
A: The other answers to this question are interesting. Surprisingly, no one has answered your question. You are wondering:
*
*Is it better to cast to Cents in the query? I don’t think the cast
to cents adds anything in your query.
*Is it better to use now() in the query? I would prefer to pass dates into the query instead of calculating them in the query.
More info:
For question one you want to be sure that aggregating the fractions
works without rounding errors. I think numeric 19,2 is reasonable
for money and in the second case the integers are OK. Using a float for money is wrong for this reason.
For question two, I like to have full control as a programmer of what
date is considered “now”. It can be hard to write automatic unit
tests when using functions like now(). Also, when you have a longer
transaction script it can be good to set a variable equal to now() and use the variable so
that all of the logic uses the exact same value.
A: Let me take a real example to address this question
I needed to calculate a weighted moving average on my ohlc data, I have about 134000 candles with a symbol for each to do so
*
*Option 1 Do it in Python/Node etc etc
*Option 2 Do it in SQL itself!
Which one is better?
*
*If I had to do this in Python, essentially, I would have to fetch all stored records at the worst, case, perform the computation and save everything back which in my opinion is a huge wastage of IO
*Weighted moving average changes everytime you get a new candle meaning I would be doing massive amounts of IO at regular intervals which is not a
good opinion in my sign
*In SQL, all I have to do is probably write a trigger that computes and stores everything so only need to fetch the final WMA values for each pair every now and then and that is so much more efficient
Requirements
*
*If I had to calculate WMA for every candle and store it, I would do it on Python
*But since I only need the last value, SQL is much faster than Python
To give you some encouragement, this is the Python version to do a weighted moving average
WMA done through code
import psycopg2
import psycopg2.extras
from talib import func
import timeit
import numpy as np
with psycopg2.connect('dbname=xyz user=xyz') as conn:
with conn.cursor() as cur:
t0 = timeit.default_timer()
cur.execute('select distinct symbol from ohlc_900 order by symbol')
for symbol in cur.fetchall():
cur.execute('select c from ohlc_900 where symbol = %s order by ts', symbol)
ohlc = np.array(cur.fetchall(), dtype = ([('c', 'f8')]))
wma = func.WMA(ohlc['c'], 10)
# print(*symbol, wma[-1])
print(timeit.default_timer() - t0)
conn.close()
WMA Through SQL
"""
if the period is 10
then we need 9 previous candles or 15 x 9 = 135 mins on the interval department
we also need to start counting at row number - (count in that group - 10)
For example if AAPL had 134 coins and current row number was 125
weight at that row will be weight = 125 - (134 - 10) = 1
10 period WMA calculations
Row no Weight c
125 1
126 2
127 3
128 4
129 5
130 6
131 7
132 8
133 9
134 10
"""
query2 = """
WITH
condition(sym, maxts, cnt) as (
select symbol, max(ts), count(symbol) from ohlc_900 group by symbol
),
cte as (
select symbol, ts,
case when cnt >= 10 and ts >= maxts - interval '135 mins'
then (row_number() over (partition by symbol order by ts) - (cnt - 10)) * c
else null
end as weighted_close
from ohlc_900
INNER JOIN condition
ON symbol = sym
WINDOW
w as (partition by symbol order by ts rows between 9 preceding and current row)
)
select symbol, sum(weighted_close)/55 as wma
from cte
WHERE weighted_close is NOT NULL
GROUP by symbol ORDER BY symbol
"""
with psycopg2.connect('dbname=xyz user=xyz') as conn:
with conn.cursor() as cur:
t0 = timeit.default_timer()
cur.execute(query2)
# for i in cur.fetchall():
# print(*i)
print(timeit.default_timer() - t0)
conn.close()
Believe it or not, the query runs faster than the Pure Python version of doing a WEIGHTED MOVING AVERAGE!!! I went step by step into writing that query so hang in there and you ll do just fine
Speed
0.42141127300055814 seconds Python
0.23801879299935536 seconds SQL
I have 134000 fake OHLC records in my database divided amongst a 1000 stocks so that is an example of where SQL can outperform your app server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "182"
} |
Q: QSystemNetworkInfo not found I want to compile a Qt project on desktop, but I get an error:
QSystemNetworkInfo: file not found.
I have added INCLUDEPATH to my .pro file, but I still get the error.
Any suggestions?
A: QSystemNetworkInfo class is part of the QtMobility APIs, which is unfortunately unavailable for desktop targets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: extracting multidimension json array in javascript I am reading a json response from a server which is sending a multidimensional array from a sqlite database using the following php code:
while ($data = $result->fetchArray(SQLITE_NUM)) {
echo json_encode($data);
This works Ok and sends its data out as a string in the following format:
[1,"Board1","Floor1",1,100,1,"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10"]
[1,"Board2","Floor2",1,100,1,"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10"]
[1,"Board3","Floor3",1,100,1,"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10"]
I am using jQuery to request this data from the server using the following code and want to save the recieved data in a javascript array so that I can access individual items using for example data[0][1] would to refer to the "Board2" element - but cannot seem to do this?
The code works with a single array, but not with multi-arrays?
JAVASCRIPT CODE:
function requestMtrConfig() {
$.ajax({
url: '/php/getmtrconfig.php',
async:false, // synchronous read
success: function(datas) {
data[0] = datas[0];
data[1] = datas[1];
data[2] = datas[2];
}
},
cache: false
});
}
How can I put the returned json array into a multi-dimensioned javascript array?
PS: I have already created a global multidimensioned JavaScript array variable called data.
Any help would be much appreciated
thanks
Frank dobbs
A: The problem is that you're sending out several pieces of JSON without joining them together. That's not the same as sending out a JSON array.
Suggested remedy:
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
echo json_encode($json);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: phoenix lambda and argument dereferencing Can somebody show me how to implement an equivalent of the following using boost::phoenix lambda?
I know I could implement it in many other ways but I'm trying to learn the Phoenix lambda expressions and so far all my attempts in this example failed.
What I want to do is to use the std::remove_if to iterate through my set of weak_ptrs and remove the expired ones.
So the code would look something like:
typedef std::set<weak_ptr<Xyz>> XyzWptrSetType;
...
XyzWptrSetType xyzWptrSet;
...
XyzWptrSetType::iterator it =
std::remove_if(xyzWptrSet.begin(), xyzWptrSet.end(),
(boost::phoenix::arg_names::_1->expied()));
// the lambda part DOESN'T compile in previous line
std::erase(it, xyzWptrSet.end());
Most of the lambda examples I've found are very simplistic and do not deal with calling a member function on a lambda argument object especially when there is more than one level of indirection. I.e. the _1 is expected to represent the set's iterator which by dereferencing with "->" returns value_type (being weak_ptr), on which I want to call expired. But since _1 is in fact not dirrectly an iterator but rather an "phoenix::actor", my dereferencing doesn't compile.
Thanks for all the creative inputs in advance.
Gabe
A: Boost.Phoenix, and Boost.Lambda before it, excel at certain tasks, but not at others. One of those others that it doesn't really work at is anything to do with directly calling a function by name.
Boost.Phoenix lambdas can be quickly and easily created for overloaded operators. But if you need a function name, then you have to use ugly syntax:
boost::phoenix::bind(&boost::weak_ptr::expired, boost::phoenix::arg_names::_1)
That is what your lambda looks like. You can use some using directives to clip off namespaces, but that's ultimately what it's going to look like. It's really no different from using boost::bind at this point:
boost::bind(&boost::weak_ptr::expired, _1)
Boost.Phoenix, and Boost.Lambda before it, are best used for lambda expressions that use overloaded operators, or explicitly-defined Phoenix action objects. If you just have a plain old function or member function, you have to bind it to call it. So you may as well just use boost::bind.
A: Boost phoenix (and boost lambda) do not support the -> operator. You can use the "pointer to member" operator (->*) as a reasonable alternative.
I find it useful to define the member pointer as a separate variable immediately before the line that uses a lambda expression:
bool (weak_ptr<Xyz>::*expired)()const = &weak_ptr<Xyz>::expired ;
XyzWptrSetType::iterator it =
std::remove_if(xyzWptrSet.begin(), xyzWptrSet.end(), (&_1->*expired)() );
As others have noted, it is also worth considering bind() for situations like yours.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iOS OpenGL runtime texturing Is it possible somehow to automatically continue the building of an existing mesh? How this can be done?
Let's say an example. I have a cuboid and I would like to have a bigger cuboid in runtime. The cuboid also have some texture and the new parts of the cuboid should have new texture. I think for this problem the scaling isn't enough, because of the texturing. How can I add texture to my cuboid in runtime?
Can you suggest me please some tutorials / frameworks and any help to solve this problem?
Edit: according to @datenwolf answer:
I think I can extend the shape of the cuboid with reusing the same mesh more time.
Do you have any idea how to texturize something in runtime?
Edit2:
So, a more concrete problem: I would like to build a house, a simple cuboid house with one floor. And after some time I would like to add another floor. I think it is an easy task, but I never worked with these kind of problems before.
A: OpenGL is not a scene graph. It's simply a drawing API. There is no internal representation of what's visible on the screen. The only thing OpenGL is left with after drawing something are the contents of the framebuffer(s).
You want something changed, you clear the framebuffer and redraw your scene with the adjustments done.
Regarding Quation EDIT 2:
I can only reiterate my first statement: OpenGL is not a scene graph, i.e. you don't "build" a scene with it. What you have is geometry data (vertices) and sampling data (images/textures).
Then you have a drawing function, that tells OpenGL to make triangles, lines or points out of the geometry data and fill the fragments generated (=pixels) with values derived from illumination calculations, solid colour and texture sampling data.
Making a change to a scene does not happen in OpenGL! Making a change in the scene happens by making the changes in the geometry data supplied to OpenGL and the different drawing operations this implies.
Like I already said, you don't "build" your scene/geometry with OpenGL. You use a 3D modelling program like Blender, Maya, 3DS Max, Cinema 4D or similar for this, store the model to some data store (file, web resource, database entry, whatever) in a format your rendering program can access. A changed model is stored in a different storage location, loaded as well and to represent the change you draw the new model.
Another way to build geometry is using Constructive (Solid) Geometry (CSG) system, with which you build a scene from basic building blocks (planes, spheres, cones, closed surface patches) and logical operations (union, difference, intersection, exclusion). However OpenGL is not a geometry processing library.
What OpenGL gives you are drawing tools: Canvases (=framebuffers), Stencils, Scissors, Collage Images (textures), "Shapes" (=Primitives, i.e. points, lines, triangles) and "Smart Brushes" (shaders). Interestingly enough, by using the stencil buffer with multiple passes one can do screen space, image based logical operations on solids. But this is really just a image based effect and won't process the geometry itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XCode 4.1 How to add result of External Build System in Products folder of projects tree I have target of type "External Build System" in my XCode project (for packing Google Crome Plugin). How can I make XCode to show reference to built plugin in Products folder of project (like bundles, app, and others)?
A: The simplest way to do so is to edit project.pbproj in text editor
A: I found this via an old blog post on Reordering Xcode's Products Group but it works for other modifications too, even as of Xcode 9.3:
*
*Rename the "Products" group to something else, e.g. "Products-wip"
*Now you can edit it! Drag in files as you would to other groups, e.g. for a build script output that writes to "$BUILT_PRODUCTS_DIR" you could reference the file "Relative to Build Products"
*When done, change the group name back to "Products"
A goofy trick to be sure, but a little bit better than editing the project file by hand!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: javascript math, rounding to two decimal places in .05 increments I apologise in advance. I've read thru a number of post and I'm sure the answer lies in implementing the toFixed() method, but can't work out how.
$('.addsurcharge').click(function() {
$('span.depositamount').text(function(i,v) {
return Math.round(parseInt(v * 100, 10) * 0.025) / 100 + (v * 1);
});
});
$('.nosurcharge').click(function() {
$('span.depositamount').text(function(i,v) {
return Math.round(parseInt(v * 100, 10) * -0.025) / 100 + (v * 1);
});
});
Basically, the above is adding (or subtracting) a 2.5% surcharge for AMEX deposits and I want it to round up to the nearest two decimal amount. Preferably in .05 increments.
Help appreciated!
A: The easiest way for currency is to work in the minor units, then round and convert to major units only at the end. So for a system with dollars and cents, work in cents until the end, then convert to dollars. If the text to be input is of the format "2.03", then it can rounded it to the nearest $0.05 using something like:
function roundToFiveCents(v) {
// Turn dollars into cents and convert to number
var len;
v = v * 100;
// Get residual cents
var r = v % 5;
// Round to 5c
if (r) {
v -= (r == 1 || r == 2)? r : r-5;
}
// Convert to string
v = v + '';
len = v.length - 2;
// Return formatted string
return v.substring(0, len) + '.' + v.substring(len);
}
That can be more concise, but I can't see the point, it would only server to obfuscate. String manipulation is very fast and replaces the uncertainty of javascript multiplication and division of decimal fractions with simple addition and subtraction.
e.g. borrowing from rfausak's answer:
// Returns string, remove ' + ''' to return number
function roundToFiveCents(v) {
return (Math.round(v*20)/20).toFixed(2) + '';
}
A: If your question is "How do I take v, a variable that contains a dollar-and-cents amount, and apply a 2.5% AMEX surcharge with the result rounded to the nearest cent (i.e., to two decimals)?" Then you can try this:
return (v * 1.025).toFixed(2);
If you have a variable surcharge try this:
var surcharge = 0.025; // or whatever percentage applies
return (v * (1 + surchage)).toFixed(2);
Note that toFixed returns a string representation, but it does the rounding for you.
(Regarding your "nosurcharge" function, you can't remove a 0.025 surcharge that was applied previously by multiplying by -0.025. You apply the surchage by multiplying by 1.025, so you remove it by dividing by 1.025.)
A: Although the post is a bit old, the question isn't.
I think what the poster meant was, that some currency calculate with cents, but the prices are given in x.00 or x.05 cents. For example Swiss currency.
The solution, borrowed from RobG's answer with a little fix:
function roundToFiveCents(v) {
var len;
// Format to 2 numbers after decimal point an turn dollars into cents
v = v.toFixed(2) * 100;
// Get residual cents
var r = v % 5;
// Round to 5c
if (r) {
v -= (r === 1 || r === 2) ? r : r - 5;
}
// Convert to string
v = v + '';
len = v.length - 2;
// Return formatted string
return v.substring(0, len) + '.' + v.substring(len);
}
A: How about the following javascript:
function my_round(x) {
x *= 20;
x = Math.ceil(x);
return x / 20;
}
var amount = 3.37;
alert(my_round(amount));
A: var n = 8.22354;
roundx(n, 3)
function roundx(num, decPlace) {
return Math.round(num * Math.pow(10, decPlace))/Math.pow(10, decPlace);
}
This simple function works well for rounding to x number of places.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jqGrid MultiSelect Problem I use that when I construct my jqgrid:
multiselect: true
So I have a check all column. However when I click check all checkbox( the checkbox at header) it selects all checkboxes but the checkboxes are not clicked at each row. Here is a demo: http://www.trirand.com/blog/jqgrid/jqgrid.html and when I click the top checkbox all the checkboes become clicked.
What should I do additionally?
PS: I just want that: http://jsfiddle.net/YWVA8/24/ when a user clicks a row that row's checkbox should be clicked, when user clicks click all all the rows should be selected and their checkboxes clicked. Do I use any other paramater that I should not use with multiselect: true?
A: I solved the problem. My id column element was like:
User 0
User 1
...
I changed it to:
User_0
User_1
...
because it was not recognizing it as a proper id with whitespace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Physical car sound simulation in car racing game i have been thinking how to create realistic sound for a car. The main sound is the engine, then all kind of wind, road and suspension sounds.
Are there any open source projects for the engine sound simulation? Simply pitching up the sample does not sound too great. The ideal would be to something that allows me to pick type of the engine (i.e. inline-4 vs v-8), add extras like turbo/supercharger whine and finally set the load and rpm.
Something like http://www.sonory.org/examples.html
The kind of one used in EA sports iphone games and firemints real racing games.
A: When sampling pitched instruments you need a variety of samples, called multisampling. So you'll have a sample for say 600RPM, one for 1200RPM, another for 2400RPM, and so on. It is best to provide samples for exponential increments (which is how pitch is perceived).
As well as providing multisamples, you will also want to provide samples at different velocities (sometimes termed as hyper sampling), such as when you are 2 feet, 20 feet and 200 feet away. There is a difference in texture due to proximity and the way that sound travels.
Also on top of that you will want to cross fade between zones so that transitions are smooth, as well as providing mild modulations such as EQ boosts, cuts, pass filter sweeps and so on.
You can also save yourself a lot of time by asking synthesis experts on music forums such as Propellerheads or KVR. They can inform you on what synthesis methods produce a convincing engine sound, and if they can do it through synthesis, you will have a much more authentic and interactive engine sound.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make Java ignore escape sequences in a String? I am writing a Java code to read Blob objects from an Oracle database table.
I need to retrieve the blob objects and store them into a String for further processing.
I convert the blob objects contents to String by this :
java.sql.Blob blob = rs.getBlob(i);
columnValue = new String(blob.getBytes(1l, (int) blob.length()));
However when I try to parse the resultant string, I get errors which say "Not a valid escape sequence" because apparently the Blob data consists of some data like \x, \i or something !
Is there a way to make Java ignore these escape sequences and make it to just consider the string with its contents as it is (i.e Strings containing \x, \i etc.) ?
A: I assume that by "parse" you mean something related to regex, because otherwise storing these values in a string will work fine - the escape sequences are useful only for string literals and regexes.
Anyway, StringEscapeUtils.escapeJava(..) should do what you want (it's from commons-lang)
Apart from that - you should use java.sql.Clob for textual data.
A: The problem has nothing to do with "\x" escape sequences. (These escape sequences only have meaning in string literals -- they have nothing to do with new String. The escape sequences found in regular expressions are just an interpretation of a string.)
The problem is that the blob contains data which is invalid for the given encoding. From the new String(byte[]) documentation:
The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.
Also do note that new String(byte[]) should not be used because (also from the documentation):
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
I suspect thus that either
*
*The blob data used is outright invalid and/or;
*The "default charset" does not match the encoding of the supplied bytes
Happy coding
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem in form auto submit How do i submit my form when the timer goes and also if refresh is clicked.??
The problem i faced is whenever refreshed it is asking for user confirmation, if clicked cancel, it remains on same page.
A: You are probably arriving at that page via method="post". The browser will not re-submit that without permission from the user.
So instead you have two options:
*
*Use method="get"
*After the post, have the server redirect to a regular page, not a page that is the result of a post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Secure HTML Files or Secure Folder Which Contain HTML and PHP files in PHP (Wordpress) i have developed a project which uses HTML files (present in a single folder) in a iframe.
I have created a index.php which required login to access and inside this index.php i use index.html in a iframe. The problem is if the user call directly call index.html then it can directly see index.html. I want to restrict the users to see index.html directly . I have created this project inside wordpress and use IIS as a web server.
A: If you are under IIS 7.x, create a web.config file in your folder which you would like to restrict access and type or paste the following into it. It should look something like this:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<hiddenSegments applyToWebDAV="false">
<add segment="myfoldername" />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Have a look at the following resource for more information :
http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/hiddenSegments
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any limit in storing values in NSUserDefaults? I have used NSUserDefaults to store some values in my app. Is there any limit for storing values in NSUserDefaults?
A: As many already mentioned: I'm not aware of any SIZE limitation (except physical memory) to store data in a .plist (e.g. UserDefaults). So it's not a question of HOW MUCH.
The real question should be HOW OFTEN you write new / changed values... And this is related to the battery drain this writes will cause.
IOS has no chance to avoid a physical write to "disk" if a single value changed, just to keep data integrity. Regarding UserDefaults this cause the whole file rewritten to disk.
This powers up the "disk" and keep it powered up for a longer time and prevent IOS to go to low power state.
From "Energy Efficiency Guide for iOS Apps":
Minimize data writes. Write to files only when their content has changed, and aggregate changes into a single write whenever possible. Avoid writing out an entire file if only a few bytes have changed. If you frequently change small portions of large files, consider using a database to store the data instead.
READS are no problem, as all values are cached in memory.
EDIT: (July 2019): I just found this very good blog post by Jeffry Fulton.
https://jeffreyfulton.ca/blog/2018/02/userdefaults-limitations-and-alternatives
He describes in detail the different aspects of the user defaults and also writes about some performance tests.
Happy Coding!!!
A: As of iPadOS 13.1 beta 3, I'm now seeing the following message when trying to store a larger object (an image).
2019-09-14 11:01:29.634368+0100 MyApp[1686:147223] [User Defaults]
CFPrefsPlistSource<0x283c7d980> (Domain: com.example.MyApp, User:
kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents
Need Refresh: No): Attempting to store >= 4194304 bytes of data in
CFPreferences/NSUserDefaults on this platform is invalid. This is a
bug in MyApp or a library it uses
However retrieving the key appears to still work.
A: As long as there's enough space on the iPhone/iPad, you can store NSUserDefault values. All those values is stored into a .plist file, and this file is very small, most of the time under 1 kb (unless you store a lot of data).
A: There are limits on what types you may store: they must all be Property List objects, namely NSString, NSNumber, NSData, NSArray, and NSDictionary. Furthermore, you may only store NSArray and NSDictionary if the values are also property list objects; also, all the keys of the NSDictionary must be strings.
Note that an object like UIColor is not on the above list. So if you want to store a color in the defaults database, you'll need to convert it into a string or data object first, then convert it back when you read the defaults.
As far as size limits, there are none that are documented, but note that all data will be stored as a property list file. The entire file is read in and written out as a whole, so if you use NSUserDefaults to store a large amount of data that only changes in parts, you will be wasting a lot of time doing unnecessary I/O.
A: There is No Limit for storing values in NSUserDefaults..
A: The only Storage Limitation in NSUserDefaults is the Device Storage Capacity.
As much as there are available Storage Space in an iOS Device, you can practically store data in NSUserDefaults. The key-value pair is stored on a xml structured file (.plist) which is stored in an App Bundle.
The user defaults system and key-value store are both designed for
storing simple data types—strings, numbers, dates, Boolean values,
URLs, data objects, and so forth—in a property list. The use of a
property list also means you can organize your preference data using
array and dictionary types. It is also possible to store other objects
in a property list by encoding them into an NSData object first.
*
*About the User Defaults System
A: As far as my knowledge there is no limit for storing in NSUserdefaults.
A: From iOS SDK codes, and related Apple official document..
extension UserDefaults {
/*!
NSUserDefaultsSizeLimitExceededNotification is posted on the main queue when more data is stored in user defaults than is allowed. Currently there is no limit for local user defaults except on tvOS, where a warning notification will be posted at 512kB, and the process terminated at 1MB. For ubiquitous defaults, the limit depends on the logged in iCloud user.
*/
@available(iOS 9.3, *)
public class let sizeLimitExceededNotification: NSNotification.Name
// ....
}
Summary
*
*Currently there is no limit for local user defaults
*On tvOS, where a warning notification will be posted at 512kB, and the process terminated at 1MB.
*For ubiquitous defaults, the limit depends on the logged in iCloud user.
A: Everyone has answered the direct question of "is there a limit?" However, I found this thread really looking to understand "how much is too much to store in UserDefaults?"
If you're looking for that answer, here's a useful thread. The responses I found helpful were to go to your project file and look at the plist file size:
5 objects is almost nothing. You'll be fine!
On my machine, I have about 28 megs of data in my user defaults. That's not causing any problems at all.
From general programming experience with arrays I would guess performance starts to rapidly decay when you get into 1000’s, depending on element size. Therefore in a program I wouldn’t have an issue storing a couple of hundred elements. This said I would probably start using a sqlite3 database or coredata, sooner rather than later if I were you.
Important to remember:
The above alleviated my concerns that my growing number of defaults (about 20-25 now) would cause problems. I use CoreData already, so I was considering which to use since my number of allowed user preferences/customizations is growing long. So, I'm going to stay with user defaults.
However, as other answers have pointed out, the file will be read and written as a whole. So reading 20 key/string dictionaries and 5 key/boolean dictionaries just to retrieve one string... not exactly ideal. Nonetheless, if it doesn't hurt performance and it saves you a ton of code, why not?
A: It whatever the maximum allowed file size is on the drive. You can use this piece of code to check it out!
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *myKey = @"key";
int sizeOfFile = 1024; // Fill in proper file size here
NSData myObject;
NSString *someFilePath = @"PathToYourFileHere";
for(int i = 1; i < 9999999999999999; i++)
{
myObject = [NSData dataWithContentsOfFile:someFilePath];
[defaults setObject:myObject forKey:[NSString stringWithFormat:@"%@%i", myKey, i]];
NSLog(@"Iteration: %i, TotalWritten: %i", i, i * sizeOfFile);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
} |
Q: JPA 2.0 / Hibernate: Why does LAZY fetching with "@OneToOne" work out of the box? my question is regarding JPA 2.0 with Hibernate, @OneToOne relationships and lazy loading.
First my setup:
*
*Spring 3.0.5.RELEASE
*SprnigData JPA 1.0.1.RELEASE
*Hibernate 3.5.2-Final
*DBMS: PostgreSQL 9.0
I recently came across the fact, that a @OneToOne relationship can't be fetched the lazy way (FetchType.LAZY), at least not without byte code instrumentation, compile time weaving or the like. Many sites out there say this, for example:
*
*http://community.jboss.org/wiki/SomeExplanationsOnLazyLoadingone-to-one
*http://justonjava.blogspot.com/2010/09/lazy-one-to-one-and-one-to-many.html
*Making a OneToOne-relation lazy
The thing is, with my setup, a lazy loading of a @OneToOne entity seems to work "out of the box", and I really would like to understand why. Please, have a look at my unit test:
@Test
@Transactional
public void testAvatarImageLazyFetching()
{
User user = new User();
user.setAvatarImage( new AvatarImage() );
User = userRepository.save( user );
entityManager.flush();
entityManager.clear();
User loadedUser = userRepository.findOne( user.getId() );
assertNotNull( loadedUser );
PersistenceUtil persistenceUtil = Persistence.getPersistenceUtil();
assertTrue( persistenceUtil.isLoaded( loadedUser ) );
assertFalse( persistenceUtil.isLoaded( loadedUser, "avatarImage" ) );
}
This test case is successful, and in Hibernates SQL logging output, I can see clearly, that the "avatarImage" will not be fetched, just the "user" (just a single SELECT, no JOIN, no access to the "AvatarImage" table etc.)
The unidirectional @OneToOne relationshop in the User class looks like this:
@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY )
private AvatarImage avatarImage;
So, everything very simple - and it seems to work.
To repeat my question: why is it working, why can the "AvatarImage" be fetched lazily, although it is referenced with a @OneToOne association?
I really appreciate any help you can offer
Thanks a lot!
A: The problem with lazy loading of OneToOne relationship is only on the inverse part of it (the one which is marked with mappedBy attribute). It works fine on the owning side of the relationship. T
he difference between those is clear on database level. In your case the question is if the User database table holds an id of AvatarImage as one of the columns or the other way round.
If User table has a column with an id of AvatarImage then the lazy loading will work as you said "out-of-box" but it will not work the other way round.
A: Lazy fetching works out of the box for @OneToOne annotated relationships, with the Hibernate JPA provider, when some form of bytecode instrumentation is performed. In your case, we could rule out build-time instrumentation (inferring from your comment that it works out-of-the-box). This leaves you with the possibility of runtime weaving, which is quite possible in Hibernate & Spring. In recent releases of Hibernate, Javassist is used as the runtime bytecode instrumentation framework for Hibernate, as opposed to the other alternative of CGLIB (which has been deprecated since Hibernate 3.5.5).
The question of whether Javassist is enabled in Spring is quite simple to answer. Hibernate EntityManager (which is the JPA 2.0 provider that delegates to Hibernate Core), requires Javassist, and therefore, it ought to be in the classpath of Hibernate, allowing for runtime weaving of the classes. You can confirm this by setting a breakpoint (in a remote debugger connected to your application server), and you'll notice that a Hibernate managed instance of the User class will not contain a reference to an AvatarImage instance; rather it would contain a reference to an enhanced class with a name like <package_name>.AvatarImage_$$_javassist_0 (which is the proxy that allows for lazy fetching).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Who is the better for Android development ? Eclipse Helios or Eclipse Galileo? which is the best Eclipse Helios or Eclipse Galileo?
Thanks.
A: The latest is Eclipse Indigo. Use that, its quite good. The performance is also up to the mark.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "The default heap size is 1 MB". How come can I malloc() more then, do I misunderstand the word 'heap'? In Microsoft Visual C++, I needed more stack space. So I went into the linker properties and raised it. But then I noticed another property: "Heap Reserve Size" (Linker Option: /HEAP) with the Note: "The default heap size is 1 MB".
How come I can malloc 50MB "on the heap" with a heap size of 1MB?
If I do the same with the stack, I get an out of stack space exception.
A:
How come I can malloc 50MB "on the heap" with a heap size of 1MB?
If I do the same with the stack, I get an out of stack space
exception.
That's because the heap can grow whereas the stack is fixed. 1MB is just the initial size of the heap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ExtJS3 Virtual Keyboard plugin throws a exception in ExtJS4 I had used virtual keyboard plugin available here in Ext JS 3 :
It does not seem to be working with Ext JS 4 . I have changed VirtualKeyboard.js file & it looks as follwing, problem is BackSpace gives me an error :
Uncaught TypeError: Cannot read property 'length' of undefined
Thrown while executing dom.value.substr(0, dom.value.length - 1)
Here is modified VirtualKeyboard.js :
http://www.sencha.com/forum/showthread.php?147963-Extjs-4-virtual-keyboard-plugin
A: Instead of making changes in the original virtual keyboard file, use the sencha provided, Ext JS 3 to Ext JS 4 migration pack. This will allow the you to run Ext 3 code under Ext JS 4. You can use this pack until the original author of the virtual keyboard provides a patch for ext js 4. Using this pack does not have a drastic effect on the performance of the application because of the increased indirection.
You can download the migration pack from here.
Cheers.
A: To fix you error use Firebug and debug the content of your dom variable. It seems that either your keyboardTarget variable has a wrong value or you need to fix your value accessor then you should just select the el and access it with el.getValue() (untested!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Don't get to view in the Design View - NetBeans I Declare two arrays and initialized them into the field declarations: the following is the example:
final String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
final Object[][] data = {
{"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}
};
and then drag and drop jTable in Frame. then go to the table Property>model>Custom Code, and there I write the following code:
new DefaultTableModel(data, columnNames)
When I run the application, working fine.But in this way, I don't get to view it in the Design View of Netbeans.
Update me! why Design view don't get to view it even I use the following code in the property to access the array
new DefaultTableModel(data, columnNames)
A: Currently Netbeans not supporting this feature may be on later version it is available. It is only not showing view on design view but working fine. So, I think without design view you can continue your working, not problem at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make each TextField of a BoxLayout.Y_AXIS have their own width? There are TextFields , four , contained into a Container whose Layout is BoxLayout(BoxLayout.Y_AXIS). I want each of these TextFields to have their own width. I tried setPreferredW , also setColumns but the TextFields are all the same size which is occupying all the remaining row's width.
So how to make each or some TextFields have their own width visually ?
A: BoxLayout always stretches components on the opposite AXIS so the text fields will always stretch regardless of their preferredW (another reason why you must never mess with that value unless you know what you are doing...).
The solution is simple, nest the text fields in multiple FlowLayout/BoxLayoutX containers and add the containers one by one to the box layout Y. The containers will each occupy the full width of the Y AXIS container but the text fields within won't take up all the space.
A: I found the solution : I derived the TextField class and in the constructor I set the preferred width value.
PS : I did not call super();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: twig template engine's form_widget I am currently updating a PHP application so that it uses the very nice twig template engine.
I have hit a snag as to how to approach this issue. The application has their own set of custom developed form classes. Essentially, one can progammatically add fields, set methods and actions to the form object. Once this is all done, a the render() method is called, which then spits out a generated HTML snippet for the form.
I was able to output the form in a template using the raw filter like so:
{{ form|raw }}
While this works well, I notice that symfony2 has a method called form_widget() which specifically deals with rendering forms without having to output as raw.
I would like to adapt the application so that I can use form_widget(), however, I am unable to find any indepth documentation on it. Can anyone point out how data should be passed to form_widget() without using the symphony2 framework? Whether it is an array, object, or something else?
A: After looking at the trawling through Symphony's source code, it looks like all they have done is created an extension so that forms will be rendered as HTML:
'form_widget' => new \Twig_Function_Method($this, 'renderWidget', array('is_safe' => array('html'))),
So, I guess all I need to do is create my own twig extension to provide similiar functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery pass across something?
Possible Duplicate:
jQuery Load form elements through ajax, from onchange event of drop down box
I have a dropdown form which when the selection is changed, that div hides and another appears.
How would I get the value of the drop down to appear on the next div?
For example:
<div id="fruit">
<select name="comp" id="comp" class="text">
<option value="29">Apple</option>
<option value="160">Pear</option>
<option value="132">Orange</option>
</select>
</div>
<div id="display">
</div>
Ideally, I'd like it to pass the ID to a page, for example fruit.php?id=132
This page would then have some PHP in which I can do, to return the other values from the database.
I need it to pass #comp value over to fruit.php (via ajax?) and then return the data to #display
How could I do this?
Thank you.
A: $("#comp").change(function() {
$("#display").load("fruit.php?id="+$("#comp").val());
});
A: $('#comp').change(function(){
$.get('fruit.php',{id: $(this).val()}, function( result ){
$('#display').html( result );
})
});
A: You can do it by a .load()
I will add jquery.ajax method
var compVal=$("#comp").val();
$.ajax({
url: "fruit.php?id="+compVal,
type: "get", // you can also use post
success: function( result ){ // result contains the response of fruit.php page
$('#display').html( result );
}
});
http://jquery.ajax
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: I keep getting a "ArrayIndexOutOfBounds" Exception when using String.split I am writing this class for another program and I keep getting an Array out of bounds exception when I am splitting the string str.
static String[][] readFile(){
BufferedReader in;
count = 0;
String[][] ret = new String[20][2];
try
{
in = new BufferedReader(new FileReader(CFGfolder+"\\input.ini"));
String str;
while((str=in.readLine()) != null){
if(str!="[GameEvents]"){
ret[count][0]=str.split("=")[0];
ret[count][1]=str.split("=")[1];
count++;
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
This is the format of the file it is reading.
evtCastSpell1=[q]
evtCastSpell2=[w]
evtCastSpell3=[e]
evtCastSpell4=[r]
I tried seeing what the str string really is (meaning, print it without the splitting) and it shows that it is correctly reading the file and putting it in the array. The problem comes when I try to read the [1] of the splitted string. The [0] is fine and it correctly prints
evtCastSpell1
evtCastSpell2
evtCastSpell3
evtCastSpell4
I really have no idea why it is not reading the [1] part. Usually this kinds of errors come from regex expressions, is it understanding the [ in the second part as a regex expression? How would I get around that if so? I've tried looking around but all I can find is similar errors that happen because of regex expressions. Is this one the same?
Thank you for your help.
A: The reason for the exception could be the number of lines in file going more than the size of your array.
Also replace this if(str!="[GameEvents]") with if(!str.equals("[GameEvents]")) for getting correct results.
A: You are doing a reference equality comparison instead of a string equals() comparison:
I would do this:
while((str=in.readLine()) != null){
if(!"[GameEvents]".equals(str)) {
String[] splits = str.split("=");
ret[count][0]=splits[0];
ret[count][1]=splits[1];
count++;
}
}
The reason of you ArrayIndexOutOfBoundsException is because of this:
if(str!="[GameEvents]"){
Because of the reference equality, the if expression returns a true and you're doing a split() on the value [GameEvents].
I hope this helps:
*
*More insight: Java String.equals versus ==.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverlight Toolkit error: 'Invalid attribute value controls:LongListSelector for property TargetType' Whem im add a toolkits objects and run app i always have the same error: Invalid attribute value controls:LongListSelector for property TargetType. [Line: 440 Position: 12], datepicker, timepicker, or switch doesn't matter, whats a problem?
here is datepicker xaml: Controls:DatePicker x:Name="DatePicker" Margin="119,260,0,0"></Controls:DatePicker>
A: It sounds like you are missing the XML namespace declaration for the Silverlight Toolkit controls. If you are using the controls prefix, then you need the following:
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
NOTE: XML namespace declarations are case sensitive, so you cannot use Controls, just controls
A: Downloading the last phone toolkit from NuGet will fix the problem.
A: Maybe you are using the August 2011 Build of the Toolkit together with the old Windows Phone Developer Tools?
The August 2011 Build is dedicated for the 7.1 SDK ("Mango"), so you should either use the 7.1 SDK with the August Build OR use the old SDK with the February 2011 Build.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ Static variable and unresolved externals error I was hoping I could get some clarification on static variables of a class.
For example:
I have two different classes which perform completely different functions, alpha and beta. Within alpha, I declare a static variable of type beta so it looks like this:
//alpha.h
#pragma once
#include <iostream>
#include "beta.h"
class alpha{
public:
alpha(){
}
static beta var;
void func(){
var.setX(3);
}
void output(){
}
};
//beta.h
#pragma once
#include <iostream>
using namespace std;
class beta{
public:
int x;
char y;
beta(){
x = 0;
y = ' ';
}
void setX(int _X){
x = _X;
}
};
//main.cpp
#include <iostream>
#include <iomanip>
#include "alpha.h"
using namespace std;
int main(){
alpha x, y, z;
x.func();
}
Now when I try to compile this, I get an unresolved externals error:
error LNK2001: unresolved external symbol "public: static class beta
alpha::var" (?var@alpha@@2Vbeta@@A)
I'm not sure what to change or what else I need to add to make something like this work. I want x, y, and z to essentially share the same beta variable. I think I can accomplish this same thing by just passing by reference one beta variable into each of them. But I want to know if it's possible to do this same thing using the static keyword here because static members of a class have the same value in any instance of a class. Unless I have that definition wrong.
A: static variables inside a class must still be defined somewhere, just like methods:
Put this in main.cpp:
beta alpha::var;
A: Add this to main.cpp:
beta alpha::var;
var in h-file is only type declaration. Variable should be created in some source file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: little endian to big endian see
i have already written one library (on little endian machine)it works fine in little endian machine now i when i run in in big endian platform it doesn't works .error are very hard to understand.
Now i have understood the concept of endianess but still i am not getting...
i want to know for making ma library for `big-endian` which changes should i
take care in ma code?
i wan to know which operation does have different behaviour in both endian
A: Lots of things might need to be changed (it's difficult to give a comprehensive list: "this is what could go wrong").
Generally endianness issues arise when one tries to access directly the contents of the memory of an integer (say with memcpy for example, union tricks etc).
A: To specify the issue cnicutar mentions, a typical candidate for issues is when you directly access parts of a type by an array of a different type, instead of using calculations for access.
unsigned long int a = 0x04030201ul;
/* Directly accesses the representation, gives 2 on LE and 3 on BE */
b = ((unsigned char *)&a)[1];
/* Works with the values, always gives 2 */
b = (a >> 8) & 0xff;
A: Is your library using binary data files?
When using binary files you have to take care in which format (big vs. little endian) you are writing/reading your data. For instance when writing an array of integers to a file they will be stored in the endianess of the machine that does the writing. When reading you have to take this circumstance into account and convert the data if necessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php tag data not executing when retrieving from database I want to use the base url to display the image in the content. so i am storing follwing text in the database
<p>
<img src="<?php echo base_url; ?>images/abc.jpg" />
</p>
when i display the content on the page the the php tag is not executing , it displays only <img src="<?php echo base_url; ?>images/abc.jpg" />. please help me.
A: You need preprocess your page before output. Something like this:
in database:
<p > <img src="{{BASEURL}}images/abc.jpg" /></p>
in php code:
$output = getOutput(); // Get your output string from database
$baseURLPattern = '{{BASEURL}}';
echo preg_replace('/' . preg_quote($baseURLPattern) . '/', $yourBaseURL, $output);
[updated]
Simple example which works as is:
$output = '<p > <img src="{{BASEURL}}images/abc.jpg" /></p>';
$baseURLPattern = '{{BASEURL}}';
$yourBaseURL = 'http://www.example.com/';
echo preg_replace('/' . preg_quote($baseURLPattern) . '/', $yourBaseURL, $output);
A: If you are using codeigniter, see the config file. Set the base_url from there.
base_url() is a function, you lack '()' in your syntax
<img src="<?php echo base_url(); ?>/images/abc.jpg" />
A: You should not be storing that whole code block in the database. Instead store just the filename part. For example, your database might have a filename column with rows like:
abc.jpg
xyz.jpg
Then your php render the rest, like this
<?php
// Get your $row
?>
<p>
<img src="<?php echo $base_url; ?>images/<?php echo $row['filename']; ?>" />
</p>
<?php
// Continue with your code
?>
You'll change 'filename' in $row['filename'] to whatever your column name is.
A: Storing that in database would not work, as php tags are not evaluated by echo.
For what you vant to do there are 2 ways.
First, Store the image url only then output it like this in PHP
echo '<img src="' . $base_url . $url_from_db . '"/>';
Second, also in this store just the image url. And use the HTML BASE tag to make a URL the BASE url for all relative URLs on your HTML page. Like this:
In your element put this
<base href="<?php echo $base_url ?>">
And use following for image output
<p><img src="<?php echo $img_orl_from_db ?>" /></p>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Odd with the main() function in C When I attempt to pass parameters into the main() function in C, I could always only get 1 parameter(and the argc is always 1, the name of the program). My program is well compiled in gcc.
#include <stdio.h>
#include <string.h>
#include "chkin.h"
#include "sort.h"
#include "display.h"
int main(int argc, char* argv[])
{
if(1 == chkin(argc, argv))
return 0;
if(strcmp("sort", argv[1]));
sort(argc, argv);
if(strcmp("display", argv[1]));
display(argc, argv);
return 0;
}
and my running commad is: ./program sort tfile.txt.
What would be the problem?
A: gdb (based on your comment to @Jack) will only read the first argument 'program'.
If you want to run the program via gdb you must try :
gdb ./program
(gdb) r sort tfile.txt
Hope this helps
A: Can you also show code for chkin and display?
Most likely, problem lies there.
Alternatively, you can attach your program to gdb and then say "br main; r sort file.txt; p argv; p argc"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why do we need PDDL, when we already have first order logic? This might be a totally naive question, but i am interested to know the particular reasons. Why was PDDL developed in the first place? Why could we not do the reasoning using First Order Logic?
A: Efficiency In Solving
Using a more specific language to express your problem makes it possible to apply more specific algorithms to solve them.
From a theoretic point of view FOL is undecidable while most flavors of PDDL are still decidable, because PDDL can only express planning problems. And e.g. classical planning with parameterized actions is "only" like EXPSPACE-complete.
Of course an EXPSPACE-complete problem expressed in more general/expressive FOL is still solvable in EXPSPACE, if you know about it. But how hard is it to come up with a general FOL solver that guarantees to solve all problems that are in EXPSPACE using only exponential space?
Efficiency In Modeling
On the practical side, expressing a planning problem using a language designed for modeling planning problems is far more convenient than writing it down in FOL.
Wouldn't you prefer to write C++ instead of Assembler? Even though everything you can write in C++ can be expressed in Assembler.
A: Another point not explicitly mentioned by ziggystar is -- in addition to the fact that using PDDL is more convenient than FOL -- that planning problems underly a completely different semantics than FOL.
While assembler and C++ are both used to describe computer programs (with assembler being more general than C++ since the latter is translated into assembler), FOL serves a completely different purpose than PDDL (while FOL, as ziggystar pointed out, is more general than PDDL).
FOL was designed to express statements, propositions, and relations between objects like (to quote ziggystar's example from the similar question Reason for the development of First Order Logic and PDDL) "All humans can think". Ordinarily, when using FOL, we are just interested in whether a formula holds or not (or, e.g., whether one proposition follows from another). The most prominent example would be the following set of propositions (formalized in FOL): (1) "All men are mortal." (2) "Socrates is a man." When formalizing this using FOL, we can ask whether (3) "Socrates is mortal" follows from "(1) and (2)". Any complete FOL reasoner will answer this with yes.
Planning (and hence problems described relying on PDDL) is about asking the question whether there exists a sequence of actions (i.e., instantiated PDDL operator schemata) that transform the initial state (description of a world prior execution of an action) to some desired goal state. Thus, planning is about the execution of actions and reasoning whether such a sequence exists. This has basically nothing to do with FOL.
Since FOL is more expressive than most standard planning formalisms (e.g., "flavors of PDDL"), one can also use FOL to describe planning problems. However, due to the complete difference of the semantics of planning and FOL, one would have to "misuse" FOL to express planning problems - and it is actually a complicated research question how one can do so. In case you are interested: google for "planning as SAT".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Need a good CSS spinners creator. Does anybody know one? Does anyone know good CSS spinners creator online application? I tried to find several and found one only on David Walsh blog. It has only one of those :(
A: http://cssload.net - this is exactly what you need. As for GIF as Matthew told you - try http://preloaders.net. It's A LOT better
A: Does it have to be done in css / javascript? I always use gifs for my spinners and I generate them here:
http://www.loadinfo.net/
A: Have you seen Spin.js? It uses only css/javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does std::move() transfer values into RValues? I just found myself not fully understanding the logic of std::move().
At first, I googled it but seems like there are only documents about how to use std::move(), not how its structure works.
I mean, I know what the template member function is but when I look into std::move() definition in VS2010, it is still confusing.
the definition of std::move() goes below.
template<class _Ty> inline
typename tr1::_Remove_reference<_Ty>::_Type&&
move(_Ty&& _Arg)
{ // forward _Arg as movable
return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg);
}
What is weird first to me is the parameter, (_Ty&& _Arg), because when I call the function like you see below,
// main()
Object obj1;
Object obj2 = std::move(obj1);
it basically equals to
// std::move()
_Ty&& _Arg = Obj1;
But as you already know, you can not directly link a LValue to a RValue reference, which makes me think that it should be like this.
_Ty&& _Arg = (Object&&)obj1;
However, this is absurd because std::move() must work for all the values.
So I guess to fully understand how this works, I should take a look at these structs too.
template<class _Ty>
struct _Remove_reference
{ // remove reference
typedef _Ty _Type;
};
template<class _Ty>
struct _Remove_reference<_Ty&>
{ // remove reference
typedef _Ty _Type;
};
template<class _Ty>
struct _Remove_reference<_Ty&&>
{ // remove rvalue reference
typedef _Ty _Type;
};
Unfortunately it's still as confusing and I don't get it.
I know that this is all because of my lack of basic syntax skills about C++.
I'd like to know how these work thoroughly and any documents that I can get on the internet will be more than welcomed. (If you can just explain this, that will be awesome too).
A: _Ty is a template parameter, and in this situation
Object obj1;
Object obj2 = std::move(obj1);
_Ty is type "Object &"
which is why the _Remove_reference is necessary.
It would be more like
typedef Object& ObjectRef;
Object obj1;
ObjectRef&& obj1_ref = obj1;
Object&& obj2 = (Object&&)obj1_ref;
If we didn't remove the reference it would be like we were doing
Object&& obj2 = (ObjectRef&&)obj1_ref;
But ObjectRef&& reduces to Object &, which we couldn't bind to obj2.
The reason it reduces this way is to support perfect forwarding. See this paper.
A: We start with the move function (which I cleaned up a little bit):
template <typename T>
typename remove_reference<T>::type&& move(T&& arg)
{
return static_cast<typename remove_reference<T>::type&&>(arg);
}
Let's start with the easier part - that is, when the function is called with rvalue:
Object a = std::move(Object());
// Object() is temporary, which is prvalue
and our move template gets instantiated as follows:
// move with [T = Object]:
remove_reference<Object>::type&& move(Object&& arg)
{
return static_cast<remove_reference<Object>::type&&>(arg);
}
Since remove_reference converts T& to T or T&& to T, and Object is not reference, our final function is:
Object&& move(Object&& arg)
{
return static_cast<Object&&>(arg);
}
Now, you might wonder: do we even need the cast? The answer is: yes, we do. The reason is simple; named rvalue reference is treated as lvalue (and implicit conversion from lvalue to rvalue reference is forbidden by standard).
Here's what happens when we call move with lvalue:
Object a; // a is lvalue
Object b = std::move(a);
and corresponding move instantiation:
// move with [T = Object&]
remove_reference<Object&>::type&& move(Object& && arg)
{
return static_cast<remove_reference<Object&>::type&&>(arg);
}
Again, remove_reference converts Object& to Object and we get:
Object&& move(Object& && arg)
{
return static_cast<Object&&>(arg);
}
Now we get to the tricky part: what does Object& && even mean and how can it bind to lvalue?
To allow perfect forwarding, C++11 standard provides special rules for reference collapsing, which are as follows:
Object & & = Object &
Object & && = Object &
Object && & = Object &
Object && && = Object &&
As you can see, under these rules Object& && actually means Object&, which is plain lvalue reference that allows binding lvalues.
Final function is thus:
Object&& move(Object& arg)
{
return static_cast<Object&&>(arg);
}
which is not unlike the previous instantiation with rvalue - they both cast its argument to rvalue reference and then return it. The difference is that first instantiation can be used with rvalues only, while the second one works with lvalues.
To explain why do we need remove_reference a bit more, let's try this function
template <typename T>
T&& wanna_be_move(T&& arg)
{
return static_cast<T&&>(arg);
}
and instantiate it with lvalue.
// wanna_be_move [with T = Object&]
Object& && wanna_be_move(Object& && arg)
{
return static_cast<Object& &&>(arg);
}
Applying the reference collapsing rules mentioned above, you can see we get function that is unusable as move (to put it simply, you call it with lvalue, you get lvalue back). If anything, this function is the identity function.
Object& wanna_be_move(Object& arg)
{
return static_cast<Object&>(arg);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "118"
} |
Q: Python indentation issues using panic CODA Any one else getting lots of indentation syntax errors when writing python in panics coda IDE? Ive been getting a lot of these, and just shuffling my code around seems gets rid of the error. Bug?
A: This is usually due to shifting between tabs and spaces as tabs. I've set my invisible character color (Preferences -> Colors) to be visible on the page so that I can see if I'm using tabs or spaces. The Python standard is to use 4 spaces for a tab. I've set this as the default as well (Preferences -> Editor then uncheck 'Use tabs' and set tab width to 4). Finally, you can clean up a file that switches between tabs and spaces or is using tabs instead of spaces by selecting the text and then going to the Text menu and selecting Detab.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Microsoft.Jet.OLEDB.4.0 provider is not registered Hi I am getting a problem like this while uploading filetype .xls "Error in excel file:The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine."
I am using following system versions:
*
*64-bit Operating System( Windows 7).
*32-bit Office of which I have attached screen shot.
*Trying these for .aspx pages in C#.
I have tried following:
*
*Downloading 32 and 64 bits of Microsoft.Jet.OLEDB.4.0 from
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=13255.
*Tried IIS Edit Application Pool > Advanced Setting > Enable 32-Bit Applications :True.
BUT BOTH OF THEM ARE NOT WORKING FOR ME. DO ANYONE HAVE GOT AN IDEA?
containt of Image mentiontioned are here:
Microsoft Office Professional Plus 2010
Version: 14.0.4760.1000(32-bit)
A: If you installed Office 32-bit, then you need to install the Access Database Engine 2010 64-bit on the machine, but there is a trick to install it. See here about the 'passive' argument: Microsoft Access Database Engine 2010 Redistributable
A: You need to install Microsoft Access Database Engine Redistributable in your (target) machine and the connection string should be changed accordingly.
Refer to the following links:
http://blogs.msdn.com/b/farukcelik/archive/2010/06/04/accessing-excel-files-on-a-x64-machine.aspx
http://www.microsoft.com/download/en/details.aspx?id=13255
Hope this helps...
A: OleDB does not have any 64bit drivers (its annoying I know), and 32bit drivers are not compatible with 64bit OS AFAIK
http://social.msdn.microsoft.com/Forums/en-GB/netfx64bit/thread/d2d33cfd-ed81-490a-906e-b9e29d572b59
Edit: you are using 32bit office... that should work with 32bit drivers. Ignore this post then.
A: By default a .NET program is compiled to Any CPU which gets translated to 64bit at runtime. For 64bit there is by default no driver installed.
One common solution is to compile explicitly for x86, such that the program uses 32bit OLEDB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: WAR deployment fails on JBoss 6.1 when it is in collapsed/archived format I have a J2EE based web application which perfectly gets deployed on JBoss 6.0 app server.
I am using JBoss's "default" server configuration.
I have an ".ear" file which contains EJBs and a ".war" file.
I am using Spring Security for user authentication and authorization.
When I deploy the same ear file on JBoss 6.1, I find my WAR deployment fails with following errors.
Surprising thing is if I deploy the same ".ear" file in exploded format, then the deployment is successful.
22:31:14,827 INFO [StdSchedulerFactory] Quartz scheduler version: 1.8.3
22:31:14,828 INFO [QuartzScheduler] Scheduler EdmQuartzScheduler_$_NON_CLUSTERED started.
22:31:14,828 INFO [QuartzService] QuartzService(EdmQuartzMBean) started.
22:31:14,837 INFO [TomcatDeployment] deploy, ctxPath=/edm
22:31:14,896 INFO [[/edm]] Initializing Spring root WebApplicationContext
22:31:14,897 INFO [ContextLoader] Root WebApplicationContext: initialization started
22:31:14,907 INFO [XmlWebApplicationContext] Refreshing Root WebApplicationContext: startup date [Wed Sep 21 22:31:14 PDT 2011]; rootof context hierarchy
22:31:14,910 INFO [XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext-business.xml]
22:31:14,911 ERROR [ContextLoader] Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-business.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-business.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) [:3.0.5.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) [:3.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) [:3.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) [:3.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) [:3.0.5.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) [:3.0.5.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) [:3.0.5.RELEASE]
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) [:3.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) [:3.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) [:3.0.5.RELEASE]
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) [:3.0.5.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) [:3.0.5.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [:3.0.5.RELEASE]
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3369) [:6.1.0.Final]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3828) [:6.1.0.Final]
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:294) [:6.1.0.Final]
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:146) [:6.1.0.Final]
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:476) [:6.1.0.Final]
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118) [:6.1.0.Final]
at org.jboss.web.deployers.WebModule.start(WebModule.java:95) [:6.1.0.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_27]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_27]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_27]
at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_27]
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157) [:6.0.0.GA]
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96) [:6.0.0.GA]
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) [:6.0.0.GA]
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:271) [:6.0.0.GA]
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:670) [:6.0.0.GA]
at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206) [:2.2.0.SP2]
at $Proxy41.start(Unknown Source) at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:53) [:2.2.0.SP2]
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:41) [:2.2.0.SP2]
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:301) [:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2]
.
.
.
.
In my WAR's web.xml I have specified Spring configuration file locations as:
<!-- Spring configuration file location -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-business.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
So, it seems the relative path of those xml files are well understood by JBoss when the ear is in exploded format - but if I have the same EAR file in collapsed/archived format, then JBoss cannot locate those xml files.
Both format of ear works fine in JBoss 6.0 - so this might be a bug in 6.1 release?
Can anyone please suggest the possible areas to look for?
Thanks in advance
[EDITED]
I did more debugging.
As part of the stack trace I noticed following.
00:29:17,926 ERROR [StandardContext] Error listenerStart
00:29:17,926 ERROR [StandardContext] Context [/edm] startup failed due to previous errors
00:29:17,929 INFO [[/edm]] Closing Spring root WebApplicationContext
00:29:17,935 ERROR [AbstractKernelController] Error installing to Start: name=jboss.web.deployment:war=/edm state=Create mode=Manual requiredState=Installed: org.jboss.deployers.spi.DeploymentException: URL file:**/C:/discovery_manager/edm/appserver/server/default/tmp/vfs
/automount5d67b4cc2c2a38ae/edm.ear-c3f755775af83fc3/contents/web.war/** deployment failed
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:325) [:6.1.0.Final]
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:146) [:6.1.0.Final]
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:476) [:6.1.0.Final]
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118) [:6.1.0.Final]
at org.jboss.web.deployers.WebModule.start(WebModule.java:95) [:6.1.0.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_26]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_26]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_26]
at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_26]
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157) [:6.0.0.GA]
=============================
Now, using windows explorer, when I navigate to that directory, i.e. "C:\discovery_manager\edm\appserver\server\default\tmp\vfs\automount5d67b4cc2c2a38ae\edm.ear-c3f755775af83fc3\contents\web.war\WEB-INF" directory, there I could not locate any XML file - that means JBoss could not properly extract the WAR file content under "tmp" folder, for some reason.
I believe it is a bug in 6.1
This explains when I explicitly deploy the ear in "exploded" format, it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTML5 - unexpected results with canvas drawImage I'm just learning how to use the HTML5 canvas element. I've been successful in drawing rectangles, calling getImageData, manipulating pixels and then putImageData to see the rectangles change colour, etc.
Now I'm trying to load an image into the canvas I've hit a snag. After calling drawImage on the canvas's context, fillRect only draws in areas that don't have an image drawn into them, like it's drawing the rectangles behind the images, even though it's called after drawImage. Also, putImageData stops working, even on the visible areas containing rectangles, my pixel manipulation no longer happens. If I comment out the line with drawImage, it works again.
What I want to be able to do is manipulate pixels in the image the same way I was doing with the rectangles. Is there any reason why this wouldn't work?
Draw Image code:
var img = new Image();
img.onload = function () {
//comment out the following line, everything works, but no image on canvas
//if it's left in, the image sits over the rectangles, and the pixel
//manipulation does not occur
context.drawImage(img, 0, 0, width / 2, height / 2);
}
img.src = path;
Draw Rectangles code:
for (var i = 0; i < amount; i++)
{
x = random(width - size);
y = random(height - size);
context.fillStyle = randomColor();
context.fillRect(x, y, size, size);
}
Maniuplate pixels code:
var imgd = context.getImageData(0, 0, width, height);
var pix = imgd.data;
//loop through and do stuff
context.putImageData(imgd, 0, 0);
A: Nothing looks particularly wrong with the code you posted. Give us the whole code or consider the following:
*
*Are you changing globalCompositeOperation anywhere?
*is randomColor() making colors that are too transparent to see?
*Is there some clipping region you haven't mentioned?
*Are you drawing everything to the correct contexts?
*Is there a spelling mistake that is stopping execution and causing an error?
*Its possible your sequence of events is wrong. You could be loading the image, then drawing rectangles, then finish loading the image, so that it appears as if the rectangles were drawn behind your image when that was simply the natural order of things.
*Is putImageData causing a security error (easier to see in Firefox) because an image has been drawn to the canvas that was from a different domain? This error might stop all subsequent drawing code execution and therefore give the effect you are describe. See if you are violating one of these rules. Specifically drawing an image to a canvas from a different origin and then trying to use getImageData.
It is most likely the last item or second-to-last item on my list that is giving you grief.
Try hosting the image on your own server and see if it goes away, or look at the web console in Firefox to see if it is complaining about a security error.
Or just open the web console in Chrome/IE9 and see if the drawing code actually gets hit when you draw an image
A: OK, Simon put me on the right path. It looks like browsers treat files from the local file system differently to files from a web server -- specifically, image files are flag as origin-clean = false. This was causing a security exception (NS_ERROR_DOM_SECURITY_ERR 1000) when I tried calling getImageData on the context after having drawn the image.
Solution 1 is to host the files on a web server.
Solution 2 is a bit of a hack but it's fine for my purposes:
try {
try {
var imgd = context.getImageData(0, 0, width, height);
} catch (e) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
var imgd = context.getImageData(0, 0, width, height);
}
} catch (e) {throw new Error("unable to access image data: " + e)}
If a security exception is thrown, the browser will prompt the user for permission to override.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: dynamic label using timer in c# I need a label that text will be change after a timer one tick.For example, timer 1st tick label will show "1 program running", in 2nd tick label will show "2 program running" in 3rd tick label will show "3 program running" and so on.
I am new in programming.Any help will be great appriciated.
A: Well, you'll need to maintain some state. To be honest, the simplest way of doing that is to capture a variable in a lambda expression:
int count = 0;
timer.Tick += (sender, args) => {
count++;
label.Text = string.Format("{0} {1} running", count,
count == 1 ? "program" : "programs");
};
Alternatively, you can create a new class to maintain that state:
internal class ProgramCounterTimerHandler
{
private int count = 0;
private readonly Label label;
internal ProgramCounterTimerHandler(Label label)
{
this.label = label;
}
internal void ShowProgramCount(object sender, EventArgs e)
{
count++;
label.Text = string.Format("{0} {1} running", count,
count == 1 ? "program" : "programs");
}
}
Then you can use:
timer.Tick += new ProgramCounterTimerHandler(label).ShowProgramCount;
Alternatively, if you're happy having an instance variable within your class, you can keep track of the count that way.
A: Did you try handling timer tick event with sth like that:
int counter = 1;
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = counter + " program running";
label1.Refresh(); //not necessarily
counter++;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: TypeError testing Backbone.js in CoffeeScript with Jasmine I'm currently working through the PeepCode video on Backbone.js but attempting to write it all in CoffeeScript rather than bare JavaScript.
So far so good, except when I try to run Jasmine tests on the code I run into some TypeErrors:
TypeError: Cannot call method 'isFirstTrack' of undefined
TypeError: Cannot call method 'get' of undefined
My CoffeeScript/Backbone file looks like this:
jQuery ->
class window.Album extends Backbone.Model
isFirstTrack: (index) ->
index is 0
class window.AlbumView extends Backbone.View
tagName: 'li'
className: 'album'
initialize: ->
@model.bind('change', @render)
@template = _.template $('#album-template').html()
render: =>
renderedContent = @template @model.toJSON()
$(@el).html(renderedContent)
return this
And the Jasmine test spec like this:
var albumData = [{
"title": "Album A",
"artist": "Artist A",
"tracks": [
{
"title": "Track A",
"url": "/music/Album A Track A.mp3"
},
{
"title": "Track B",
"url": "/music/Album A Track B.mp3"
}]
}, {
"title": "Album B",
"artist": "Artist B",
"tracks": [
{
"title": "Track A",
"url": "/music/Album B Track A.mp3"
},
{
"title": "Track B",
"url": "/music/Album B Track B.mp3"
}]
}];
describe("Album", function () {
beforeEach(function () {
album = new Album(albumData[0]);
});
it("creates from data", function () {
expect(this.album.get('tracks').length).toEqual(2);
});
describe("first track", function() {
it("identifies correct first track", function() {
expect(this.album.isFirstTrack(0)).toBeTruthy();
})
});
});
I'm guessing the problem has something to do with CoffeeScript wrapping everything in a function. When I remove jQuery from the equation it works fine.
Strangely though even though Jasmine is telling me TypeError: Cannot call method 'isFirstTrack' of undefined if I run album.isFirstTrack(0) in the console on the page it returns true so the window does have access to the variables and methods.
A: the reason is scoping, yes.
when you declare the album variable with no var keyword and without attaching it to another object, you are creating a variable in the global scope.
this is a bad idea. you really want to limit the number of global objects that you create, because it's easy for another chunk of javascript to overwrite your data, or cause conflicts, etc.
your idea of calling this.model in the tests is correct from this perspective. the problem is that you need to attach model to this to be able to do that. easy enough:
beforeEach(function () {
this.album = new Album(albumData[0]);
});
all you have to do is say this.album = ... and you're done. now your tests will be able to find this.album and everything should work.
A: (Note: I believe Derick's answer is correct—it explains the TypeError: Cannot call method 'isFirstTrack' of undefined message—but this answer may also be pertinent.)
You say
When I remove jQuery from the equation it works fine.
Meaning that if you cut out the line jQuery ->, then your tests pass? If that's the case, it's not a scope issue; it's a code order issue. When you pass a function to jQuery, that function isn't executed until the document is ready. Meanwhile, your tests are running immediately—before the Album and AlbumView classes are defined.
There's no reason to use the jQuery -> wrapper, since your class definitions don't depend on any existing DOM elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What exactly happens with new session creation when php + memcache PECL extension 'looses' one of its memcache session servers? Quick note, I am not talking about existing session, I know, they will be lost if a memcache server is taken offline.
Imagine the following situation:
a) PHP
b) PECL memcache extension ( http://pecl.php.net/package/memcache )
c) PECL memcache setup as the session handler
d) Multiple memcache servers setup to do this via session.save_path = "tcp:....., tcp:.....";
e) One of the memcache servers goes down (server reboot, daemon stop, etc). So at this point we would still be left with at least one valid, and working, memcache server.
How does the above affect new sessions being created?
I have taken a look at the memcache manual at http://www.php.net/manual/en/memcache.ini.php and the manual is a bit thin.
Although it does say that the same params as listed in http://www.php.net/manual/en/memcache.addserver.php apply.
We have tried shuting down one of our memcached servers to test and our php log starts to fill with 'unable to write session data, check your....'.
Currently our session.save_path ini setting looks something like:
session.save_path = "tcp://xxx.xxx.xxx.xxx:z?persistent=1, tcp://yyy.yyy.yyy.yyy:z?persistent=1";
So, to summarize:
1) What happens when one of the session handlers goes down?
2) Is there a way to configure this extension to transparently attempt one of the 'other' memcache servers listed if the attempted one fails? Or is this done automatically?
3) In the memcache runtime config manual pages @ php.net I see a setting "memcache.allow_failover", defaulted to true (on), does this apply to the session handling as well? Or only 'in php' calls to memcache?
Thank you kindly.
Further clarification, we are using version 3.0.6 of the extension as located at http://pecl.php.net/package/memcache.
A: It seems that failover in 3.0.x is broken. I've been trying to work out this for hours and session failover only worked on stable branch (2.2.x). Tried 3.0.5, 3.0.4 and both failed for me.
When using 3.0.6 - it fails silently and doesn't return any error. When using 3.0.4 or 3.0.5 it segfaults and doesn't return any content.
So I'd suggest using your own custom session handler which encapsulates and uses memcache for storing sessions. There you can implement your own failover mechanism.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to decompress SVGZ with JavaScript? I'm trying to set up this world map using SVGZ instead of SVG so I can give my users a richer, more detailed map.
So far I've tried decompressing it using js-deflate, but to no avail.
A: If you want the SVG file inside of the SVGZ, you gunzip it (it's a renamed archive):
cp file.svgz file2.svg.gz
gunzip file2.svg.gz
If you want to use a SVGZ image, then you might run into trouble. I think some browsers support it (virtually all support Gzip compression), but I doubt many do (if any at all).
A: As I write in comment SVGZ uses gzip. Top browsers can decompress gzip files without assistance. Your page http://home.no/dwaynie/map load .svgz file with Content-Type:text/plain; charset=ISO-8859-1. But for SVG|SVGZ it's not valid MIME type.
svg Content-Type: image/svg+xml
svgz Content-Type: image/svg+xml
Content-Encoding: gzip
Above headers must be configured in web server (IIS, Apache).
A: Just below the map on the page you refer to there's a link to Wikipedia that explains what it is: an SVG file compressed with gzip.
For completeness sake: gzip and (pk)zip are not the same format, but Windows tools like WinRAR and 7-Zip understand gzip as well as zip. Every Linux distro probably has gzip/gunzip installed by default.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting Playstation 2 dualport usb adapter to work in Windosw 7 64-bit I have a: Play.com USB Dual PS2 to PC Converter XP made by Joytech
It is pretty old and the driver CD is for XP. It sometimes works in 32-bit with EMS 32-bit Vista beta drivers.
Back to 64-bit:
The gamepads are not shown in the game controllers dialog. They work when programming using the SDL library as well as in an old game from 1999 called Re-Volt. I have downloaded the Windows Driver Development kit but find the documentation regarding game controllers lacking so far.
Are there any good resources on the net for writing such a driver?
A: Since you probably have no documentation on the protocol the converter uses -- manufacturers practically never release that sort of thing -- you're looking at a very difficult task. Unless you're after an "educational" (read: incredibly frustrating) experience, your best bet will be to just buy a new converter which is better supported by current OSes.
If you want to take it on anyway, though, your first step will probably be to get a logic analyzer and read up on how USB works. Good luck... you'll need it.
A: I recently upgraded to Windows 64; for a sec you had me worried I could no longer use my adapter + controllers! Before writing drivers, try the latest drivers from the Mayflash web site (in case Play.com/Joytech is just an OEM/rebranding...)
*
*I identified my adapter as PC013 (Super Dual Box)
*Then I downloaded the latest drivers (Oct 2009) from the download page
I am running Windows 7 64 Ultimate. Both my PS controllers are identified as "Dual USB Force Feedback Joypad (MP-8866)" in Control Panel\All Control Panel Items\Devices and Printers. The "Properties" button brings up the custom Mayflash dialog; all buttons, sticks, lights, and force feedback seem to be working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Ruby condition within HAML and Javascript Here is my best attempt that does not work:
:javascript
$(document).ready(function(){
- if params[:filtered] == "a"
highlightLink(0);
- elsif params[:filtered] == "b"
highlightLink(1);
- elsif params[:filtered] == "c"
highlightLink(2);
});
What should I do so that my above attempt works?
A: Just an example you can try something like following
num = params[:filtered] == "a" ? 0 : (params[:filtered] == "b" ? 1 : 2)
a= %(:javascript $(document).ready(function(){ highlightLink(#{num})}); )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deleting Row in SQLite in Android This might be a dumb question, but I'm new to SQLite and I can't seem to figure this out. I have 1 table that has columns KEY_ROWID, KEY_NAME, KAY_LATITUDE, and KEY_LONGITUDE. I want the user to be able to select one and delete it; Can anyone give me a direction to start in? My question is in the actual deletion of the row given only its name.
Relevant code:
public class BeaconDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "beacon_name";
public static final String KEY_LATITUDE = "beacon_lat";
public static final String KEY_LONGITUDE = "beacon_lon";
private static final String DATABASE_NAME ="BeaconDatabase";
private static final String DATABASE_TABLE ="beaconTable";
private static final int DATABASE_VERSION = 1;
private DbHelper helper;
private final Context context;
private SQLiteDatabase db;
public BeaconDatabase(Context context) {
this.context = context;
}
public BeaconDatabase open() {
helper = new DbHelper(this.context);
db = helper.getWritableDatabase();
return this;
}
public void close() {
helper.close();
}
public long createEntry(String name, Double lat, Double lon) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_LATITUDE, lat);
cv.put(KEY_LONGITUDE, lon);
return db.insert(DATABASE_TABLE, null, cv);
}
public void deleteEntry(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
//db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row, null);
}
public String getData() {
String[] columns = { KEY_ROWID, KEY_NAME, KEY_LATITUDE, KEY_LONGITUDE };
Cursor cursor = db.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = cursor.getColumnIndex(KEY_ROWID);
int iName = cursor.getColumnIndex(KEY_NAME);
int iLat = cursor.getColumnIndex(KEY_LATITUDE);
int iLon = cursor.getColumnIndex(KEY_LONGITUDE);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result += cursor.getString(iRow) + ": " + cursor.getString(iName) + " - " + cursor.getDouble(iLat) + " latitude " + cursor.getDouble(iLon) + " longitude\n";
}
return result;
}
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_LATITUDE + " DOUBLE, " +
KEY_LONGITUDE + " DOUBLE);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
}
A: Try this code...
private static final String mname = "'USERNAME'";
public void deleteContact()
{
db.delete(TABLE_CONTACTS, KEY_NAME + "=" + mname, null);
}
A: it's better to use whereargs too;
db.delete("tablename","id=? and name=?",new String[]{"1","jack"});
this is like useing this command:
delete from tablename where id='1' and name ='jack'
and using delete function in such way is good because it removes sql injections.
A: This works perfectly:
public boolean deleteSingleRow(String rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
You can also refer to this example.
A: if you are using SQLiteDatabase then there is a delete method
Definition of Delete
int delete (String table, String whereClause, String[] whereArgs)
Example Implementation
Now we can write a method called delete with argument as name
public void delete(String value) {
db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{String.valueOf(value)});
}
if you want to delete all records then just pass null to the above method,
public void delete() {
db.delete(DATABASE_TABLE, null, null);
}
Source Of Information
A: Guys this is a generic method you can use for all your tables, Worked perfectly in my case.
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
String whereClause = columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
yourDatabase.delete(tableName, whereClause, whereArgs);
}
A: Try the below code-
mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
//delete success.
} else {
//delete failed.
}
A: To delete rows from a table, you need to provide selection criteria that identify the rows to the delete() method. The mechanism works the same as the selection arguments to the query() method. It divides the selection specification into a selection clause(where clause) and selection arguments.
SQLiteDatabase db = this.getWritableDatabase();
// Define 'where' part of query.
String selection = Contract.COLUMN_COMPANY_ID + " =? and "
+ Contract.CLOUMN_TYPE +" =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { cid,mode };
// Issue SQL statement.
int deletedRows = db.delete(Contract.TABLE_NAME,
selection, selectionArgs);
return deletedRows;// no.of rows deleted.
The return value for the delete() method indicates the number of rows that were deleted from the database.
A: You can try like this:
//---deletes a particular title---
public boolean deleteTitle(String name)
{
return db.delete(DATABASE_TABLE, KEY_NAME + "=" + name, null) > 0;
}
or
public boolean deleteTitle(String name)
{
return db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{name}) > 0;
}
A: Till i understand your question,you want to put two conditions to select a row to be deleted.for that,you need to do:
public void deleteEntry(long row,String key_name) {
db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row + " and " + KEY_NAME + "=" + key_name, null);
/*if you just have key_name to select a row,you can ignore passing rowid(here-row) and use:
db.delete(DATABASE_TABLE, KEY_NAME + "=" + key_name, null);
*/
}
A: Try like that may you get your solution
String table = "beaconTable";
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);
A: Try this code
public void deleteRow(String value)
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+COlUMN_NAME+"='"+value+"'");
db.close();
}
A: Guys if above solutions don't work for you then try this one also because it worked for me.
public boolean deleteRow(String name)
{
return db.delete(DATABASE_TABLE, KEY_NAME + "='" + name +"' ;", null) > 0;
}
A: Works great!
public void deleteNewMelk(String melkCode) {
getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}
A: Try this one:
public void deleteEntry(long rowId) {
database.delete(DATABASE_TABLE , KEY_ROWID
+ " = " + rowId, null);}
A: public boolean deleteRow(long l) {
String where = "ID" + "=" + l;
return db.delete(TABLE_COUNTRY, where, null) != 0;
}
A: You can do something like this, sharing my working code snippet
Make sure query is like this
DELETE FROM tableName WHERE
KEY__NAME = 'parameterToMatch'
public void removeSingleFeedback(InputFeedback itemToDelete) {
//Open the database
SQLiteDatabase database = this.getWritableDatabase();
//Execute sql query to remove from database
//NOTE: When removing by String in SQL, value must be enclosed with ''
database.execSQL("DELETE FROM " + TABLE_FEEDBACKS + " WHERE "
+ KEY_CUSTMER_NAME + "= '" + itemToDelete.getStrCustName() + "'" +
" AND " + KEY_DESIGNATION + "= '" + itemToDelete.getStrCustDesignation() + "'" +
" AND " + KEY_EMAIL + "= '" + itemToDelete.getStrCustEmail() + "'" +
" AND " + KEY_CONTACT_NO + "= '" + itemToDelete.getStrCustContactNo() + "'" +
" AND " + KEY_MOBILE_NO + "= '" + itemToDelete.getStrCustMobile() + "'" +
" AND " + KEY_CLUSTER_NAME + "= '" + itemToDelete.getStrClusterName() + "'" +
" AND " + KEY_PRODUCT_NAME + "= '" + itemToDelete.getStrProductName() + "'" +
" AND " + KEY_INSTALL_VERSION + "= '" + itemToDelete.getStrInstalledVersion() + "'" +
" AND " + KEY_REQUIREMENTS + "= '" + itemToDelete.getStrRequirements() + "'" +
" AND " + KEY_CHALLENGES + "= '" + itemToDelete.getStrChallenges() + "'" +
" AND " + KEY_EXPANSION + "= '" + itemToDelete.getStrFutureExpansion() + "'" +
" AND " + KEY_COMMENTS + "= '" + itemToDelete.getStrComments() + "'"
);
//Close the database
database.close();
}
A: The only way that worked for me was this
fun removeCart(mCart: Cart) {
val db = dbHelper.writableDatabase
val deleteLineWithThisValue = mCart.f
db.delete(cons.tableNames[3], Cart.KEY_f + " LIKE '%" + deleteLineWithThisValue + "%' ", null)
}
class Cart {
var a: String? = null
var b: String? = null
var c: String? = null
var d: String? = null
var e: Int? = null
var f: String? = null
companion object {
// Labels Table Columns names
const val rowIdKey = "_id"
const val idKey = "id"
const val KEY_a = "a"
const val KEY_b = "b"
const val KEY_c = "c"
const val KEY_d = "d"
const val KEY_e = "e"
const val KEY_f = "f"
}
}
object cons {
val tableNames = arrayOf(
/*0*/ "shoes",
/*1*/ "hats",
/*2*/ "shirt",
/*3*/ "car"
)
}
A: But the Accepted answer Not worked for me. I think String should be In SQL, strings must be quoted. So, in my case this worked for me against the accepted answer :
database.delete(TABLE_DAILY_NOTES, WORK_ENTRY_CLUMN_NAME + "='" + workEntry+"'", null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "111"
} |
Q: Facebook Library: Uncaught RangeError: Maximum call stack size exceeded I have an error at the page:
http://www.thalasoft.com/engine/modules/user/login.php
The Chromium browser says: Uncaught RangeError: Maximum call stack size exceeded
And the Facebook Connect button does not work any longer..
Any clue ?
A: You have both the deprecated Facebook javascript library loaded as well as the old one. Remove the old one:
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
Keep the valid one:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '35944321698',
status: true,
cookie: true,
xfbml: true
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Not entirely sure it will fix it, but I know mixing them is not supported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add data in Cassandra? I am writing simple java program to insert data into Cassandra. Can it be done through java code only using hector APIs ? or does it require yaml file to be loaded from jconsole ?
I am using cassandra 0.8.5 and when i do jsoncole i do not see load from yaml operation there.
Hence searching for a way to load schemas as well as data from java program into cassandra.
Thanks,
Gaurav
A: You can certainly insert data through java code using Hector. However, in order to do so, you need an instantiated schema.
In previous Cassandra versions (0.6.x branch) the schema was specified in the YAML, you can still do that in the current version. However, recent Cassandra versions support dynamic schema creations which can be done through Java code in hector.
Have a look at hector-examples. The SchemaManipulation example demonstrates how to create a simple schema through hector. The Insert* examples demonstrate how to insert data.
A: You can use the CLI to set the schema as well as load data; useful for experimenting, etc. until you dive in with higher level clients and even then, the CLI is very useful for resetting schema, adding test data, etc.
Wiki has great information:
*
*http://wiki.apache.org/cassandra/CassandraCli
*http://wiki.apache.org/cassandra/ClientOptions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select Box Alignment How could I align the select box so its inline with the others? I am also trying to do this with the 3 option input boxes.
CSS:
#newwebsiteSection, #websiteredevelopmentSection, #otherSection{
display:none;
}
#newwebsiteForm form{
padding:10px;
margin:10px 0;
width:480px;
position: relative;
}
#newwebsiteForm label{
display:block;
float:left;
clear:both;
margin:0 15px 0 25px;
width:240px;
border:1px solid green;
}
#newwebsiteForm input{
display:block;
float:left;
width:240px;
height:15px;
}
#newwebsiteForm .radioButton {
width:15px;
height:15px;
}
#newwebsiteForm .radioText {
display:block;
width:30px;
height:20px;
float:left;
font-size:12px;
border:1px solid red;
}
#newwebsiteForm select{
margin-left:123px;
}
#newwebsiteForm #color1,#color2,#color3,#fav1,#fav2,#fav3{
display:block;
float:left;
margin-left:25px;
background-color:red;
}
#newwebsiteForm textarea{
display:block;
float:left;
}
HTML:
<section id="content">
<h1>Free Quote</h1>
<p>Please fill out the below questionnaire to receive your free web development quote</p>
<form action="#" method="post">
<select name="requiredOption" id="requiredOption">
<option id="pleaseselect" value="pleaseselect">Please Select Your Required Quote</option>
<option id="newwebsite" value="newwebsite">New Website</option>
<option id="websiteredevelopment" value="websiteredevelopment">Website Redevelopment</option>
<option id="other" value="other">Other</option>
</select>
</form>
<div id="newwebsiteSection">
<form action="#" id="newwebsiteForm" method="get">
<fieldset>
<label>Do You Require Hosting?</label>
<span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/>
<label>Do You Require A Domain?</label>
<span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/>
<label>Do You Have A Logo?</label>
<span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/>
<label for="domain">What is your Domain?</label>
<input type="url" id="domain" value="http://example.com"/>
<label for="newwebsiteType">Type of site Required?</label>
<select name="newwebsiteType" id="newwebsiteType">
<option value="shoppingCart">Shopping Cart</option>
<option value="CMS">Content Management System</option>
<option value="static">Static Website</option>
<option value="otherDevelopment">Other Development</option>
</select>
<label>Do You Require A Design?</label>
<span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/>
<label>Three Favorite colors?</label>
<input id="color1" value=""/>
<input id="color2" value=""/>
<input id="color3" value=""/>
<label>What are your favorite websites?</label>
<input type="text" id="fav1" value=""/>
<input type="text" id="fav2" value=""/>
<input type="text" id="fav3" value=""/>
<label for="comments">Comments?</label>
<textarea name="comments" id="comments"></textarea>
<input type="submit" name="submit" value="Send Quote Request"/>
</fieldset>
</form>
</div>
<div id="websiteredevelopmentSection">
<p>Website Redevelopment</p>
</div>
<div id="otherSection">
<p>Other</p>
</div>
</section>
A: Your css form selector is wrong.
#newwebsiteForm form{}
should just be
#newwebsiteForm{}
I modified your html and css slightly to get this layout:
html - wrap label/input pairs in a div. This helps a lot with styling. Hosting and Domain pairs are wrapped so that IE7 will display them on a new line.
<div>
<label>Do You Require Hosting?</label>
<span class="radioText">Yes</span>
<input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span>
<input class="radioButton" type="radio" name="No" value="No"/>
</div>
<div>
<label>Do You Require A Domain?</label>
<span class="radioText">Yes</span>
<input class="radioButton" type="radio" name="Yes" value="Yes"/>
<span class="radioText">No</span>
<input class="radioButton" type="radio" name="No" value="No"/>
</div>
The .form-field class aligns the inputs. Outer wrapper again helps IE7 formatting.
<div>
<label>Three Favorite colors?</label>
<div class="form-field">
<input id="color1" value=""/>
<input id="color2" value=""/>
<input id="color3" value=""/>
</div>
</div>
<div>
<label>What are your favorite websites?</label>
<div class="form-field">
<input type="text" id="fav1" value=""/>
<input type="text" id="fav2" value=""/>
<input type="text" id="fav3" value=""/>
</div>
</div>
css
#newwebsiteForm label{
height:15px
}
#newwebsiteForm select{
/*margin-left:123px*/
}
input#domain,
#newwebsiteForm select,
.form-field{float:right;width:200px;margin-top:-15px}
.form-field{width:220px}
Demo: http://jsfiddle.net/mjcookson/GTd9J/
Cheers :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Windows 8 fat binary (exe for x86 & ARM) Does anyone (here) know if Windows 8 will have a sort of fat exe that one can compile with Visual Studio 2012 that will be supported on both ARM and x86 machines? I am guessing not, since you can't create fat binaries that will execute 32 or 64 bit code so far as I am aware (only solution available that I am aware of is 32 bit that creates a 64 bit executable on the fly).
It seems like it would be helpful of Microsoft to extend exe or create a fat binary format for Windows 8 and beyond at least that would allow one to compile a single executable for Window's expanding palette of platforms.
edit: The following link shows how to compile an ARM exe in the first dev preview. Figured I would add that because it gives no hint of fat binary support, but it is also early in the game. I don't think not having it now rules it out as a possibility. Compile for ARM
A: The need for fat binary support in Windows 8 is mitigated by the requirement that binaries for the ARM platform be distributed through the Windows app store. Modern apps are compiled to a single package.
A: Separate binaries are needed for execution on different systems. Similar as they have for win32 and win64.
A: I've seen no news, hints, or even rumors about such feature. Considering that we already have to keep a separate set of executables and DLLs for x86 and x64, I don't see this changing for ARM. Also, considering ARM machines usually have quite limited memory as it is, dragging along x86/x64 ballast "just in case" makes even less sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Bash and For loop I have two files with the following lines:
File1:
[2011-09-21 11:27:44.663] EXT-RESPONSE|13166260540762613|50498692776|4|Activation|0|600
[2011-09-21 11:27:44.906] EXT-RESPONSE|13166260643402689|50494792676|*702|Activation|0|600
[2011-09-21 11:27:44.907] EXT-RESPONSE|13166260644572692|50497855449|*702|Activation|0|600
[2011-09-21 11:27:45.334] EXT-RESPONSE|13166260649992694|50496364022|*902|Activation|0|600
[2011-09-21 11:27:45.437] EXT-RESPONSE|13166260650582695|50497646930|*702|Activation|0|600
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|516
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|605
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|600
[2011-09-21 11:27:45.733] EXT-RESPONSE|13166260623002676|50499119706|2|Activation|0|600
[2011-09-21 11:27:45.755] EXT-RESPONSE|13166260653182698|50496437811|*702|Activation|0|600
File2:
[2011-09-21 11:27:44.663] EXT-RESPONSE|13166260540762613|50498692776|4|Activation|0|600
[2011-09-21 11:27:44.906] EXT-RESPONSE|13166260643402689|50494792676|*702|Activation|0|600
[2011-09-21 11:27:44.907] EXT-RESPONSE|13166260644572692|50497855449|*702|Activation|0|600
[2011-09-21 11:27:45.334] EXT-RESPONSE|13166260649992694|50496364022|*902|Activation|0|600
[2011-09-21 11:27:45.437] EXT-RESPONSE|13166260650582695|50497646930|*702|Activation|0|600
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|504
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|605
[2011-09-21 11:27:45.639] EXT-RESPONSE|13166260651372696|50494876344|*702|Activation|0|600
[2011-09-21 11:27:45.733] EXT-RESPONSE|13166260623002676|50499119706|2|Activation|0|504
[2011-09-21 11:27:45.755] EXT-RESPONSE|13166260653182698|50496437811|*702|Activation|0|600
I want to read both file on a shell script and get some values... I have created a For in order to work with both file...
Here is the script..
#!/bin/bash
UD_GW1='/root/Lab/UD_GW1'
UD_GW2='/root/Lab/UD_GW2'
i='1'
while [ $i -le "2" ]; do
for e in $UD_GW1 $UD_GW2 ; do
echo "TABLE USSD_GW$i"
echo "START_SAMPLE_PERIOD"
while read numcodigo; do
cantidad_uniq=`tail -n 60000 $e | egrep "EXT-RESPONSE" | cut -d '|' -f 7 | egrep -v ^$ | egrep "$numcodigo" | wc -l`
echo "$numcodigo".Metric" "=" $numcodigo"
echo "CantCod."$numcodigo"Metric "=" $cantidad_uniq"
done #fin while read numcodigo;
echo "END_SAMPLE_PERIOD"
echo "END_TABLE"
let i=$i+1
done
done
And i need something like:
TABLE USSD_GW1
START_SAMPLE_PERIOD
600.Metric = 600
CantCod.600Metric = 8
518.Metric = 518
CantCod.518Metric = 0
504.Metric = 504
CantCod.504Metric = 0
516.Metric = 516
CantCod.516Metric = 1
527.Metric = 527
CantCod.527Metric = 0
END_SAMPLE_PERIOD
END_TABLE
TABLE USSD_GW2
START_SAMPLE_PERIOD
600.Metric = 600
CantCod.600Metric = 7
518.Metric = 518
CantCod.518Metric = 0
504.Metric = 504
CantCod.504Metric = 2
516.Metric = 516
CantCod.516Metric = 0
527.Metric = 527
CantCod.527Metric = 0
END_SAMPLE_PERIOD
END_TABLE
However when i run my script i got:
TABLE USSD_GW1
START_SAMPLE_PERIOD
600.Metric = 600
CantCod.600Metric = 8
518.Metric = 518
CantCod.518Metric = 0
504.Metric = 504
CantCod.504Metric = 0
516.Metric = 516
CantCod.516Metric = 1
527.Metric = 527
CantCod.527Metric = 0
END_SAMPLE_PERIOD
END_TABLE
TABLE USSD_GW2
START_SAMPLE_PERIOD
END_SAMPLE_PERIOD
END_TABLE
Please any help would be great....
Thanks,
Michael.
A: remove the while loop and the references to i. You only need the for loop.
Alternatively you could remove the for loop, assigning e=/root/Lab/UD_GW$i
You should also write the inner loop as cat $e | while read numcodigo; do
A: I have a few suggestions for your script. Why don't you use array for files & also move your display logic to a function?
The advantage of using an array will be that you can easily extend it to multiple files (more than 2 in current case)
Separating the display logic into a function will help you debug & change the logic easily
#!/bin/bash
#First param is the file to read to check for codes
#Second param is the file to read the codes from
function display_info()
{
#Your display logic is here...
for numcodigo in `cat $2`
do
cantidad_uniq=`tail -n 60000 $1 | egrep "EXT-RESPONSE" | cut -d '|' -f 7 | egrep -v ^$ | egrep "$numcodigo" | wc -l`
echo "$numcodigo".Metric" "=" $numcodigo"
echo "CantCod."$numcodigo"Metric "=" $cantidad_uniq"
done
}
#Main operation
#Array elements are space separated
#newline is used only to make it more readable & easier to add new array elements
file_list=(
/root/Lab/UD_GW1
/root/Lab/UD_GW2
)
index=1
for file in ${file_list[@]}
do
echo "TABLE USSD_GW$index"
echo "START_SAMPLE_PERIOD"
#Pass file to read from the list as first param
#Pass file to read the codes to check from command line argument as second param
display_info $file $1
echo "END_SAMPLE_PERIOD"
echo "END_TABLE"
let "index++"
done
Hope this helps!
PS: BTW how does your output have 518 etc which are not in the files? Are you checking for tokens from elsewhere?
EDIT:
Please run this script as ./<scripts_name> codes.txt
There are alternative to achieve what you need, but this is just one of the ways!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: One-to-many Primary /Foreign Key in Entity Framework How to map one-to-many relationship on following entites using Fluent API.
[Table("LU_COMMODITY_ID")]
public class LU_COMMODITY_ID
{
[Key]
public string COMMODITY_ID { get; set; }
public virtual string COMMODITY_DESC { get; set; }
...
public virtual ICollection<LU_SUPPLIER_COMMODITY> LU_SUPPLIER_COMMODITIES { get; set; }
}
[Table("LU_SUPPLIER_COMMODITY")]
public class LU_SUPPLIER_COMMODITY
{
[Key, Column(Order = 0)]
public string COMMODITY_ID { get; set; }
[Key, Column(Order = 1)]
public virtual string SUPPLIER_NAME { get; set; }
...
public virtual LU_COMMODITY_ID LU_COMMODITY_ID {get; set; }
}
I've tried the following mapping:
modelBuilder.Entity<LU_SUPPLIER_COMMODITY>()
.HasRequired(l => l.LU_COMMODITY_ID)
.WithMany(a => a.LU_SUPPLIER_COMMODITIES)
.HasForeignKey(l => l.COMMODITY_ID);
and it gave me next error:
The 'LU_SUPPLIER_COMMODITIES' property does not exist or is not mapped for the type 'LU_COMMODITY_ID'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to download using dialog box? SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
SqlCommand Command = connection.CreateCommand();
SqlDataReader SQLRD;
Command.CommandText = "Select * from Attendance";
connection.Open();
SQLRD = Command.ExecuteReader();
string data = "";
while (SQLRD.Read())
{
data += SQLRD[0].ToString() + ",";
data += SQLRD[1].ToString() + ",";
data += SQLRD[2].ToString() + ",";
data += SQLRD[3].ToString() + ",";
data += SQLRD[4].ToString() + ",";
data += SQLRD[5].ToString() + ",";
data += SQLRD[6].ToString() + ",";
data += SQLRD[7].ToString();
data += "\n";
}
SQLRD.Close();
connection.Close();
string filename = @"C:\download.csv";
FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();
Currently my code does not display a dialog box for the user to specify the file location. It is "hardcoded" to always store in @"C:\download.csv";. In replace of this i want to use a dialog box.
A: First of all I'd say do not use System.String object to contact strings. Always use System.Text.StringBuilder object.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (SQLRD.Read())
{
sb.Append(String.Format("{0},{1},{2},{3},{4},{5},{6},{7}\n",
SQLRD[0],SQLRD[1],SQLRD[2],SQLRD[3],SQLRD[4],SQLRD[5],SQLRD[6],SQLRD[7]));
}
To download data,
byte[] ar = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/octet-stream");
Response.AddHeader("Content-Length", ar.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
Response.BinaryWrite(ar);
Response.Flush();
Response.End();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Opera (and Chrome) is changing colors of my images! Why ? How to stop that?
link to this image : img
Firefox shows this image as is.
But if I open it with Opera Gray colors is different instead if I download it and open with any editor. Why ?
Here is how opera shows me my image :
Here is true image colors :
More picture (Just wondering)
How to make my png shows native in all browsers. (as like as on FireFox or IE or Windows picture viewer)
A: According to Photoshop, the image contains a embedded color profile "LG L245WP". This will natually make the colors different. Opera (and presumably Chrome) doesn't support color profiles. I recommend saving the image out with sRGB color profile, then it'll look the same in all browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Validating checkboxes present inside gridview with Javascript
Possible Duplicate:
Validating checkboxes present inside gridview with Javascript
This is my aspx code...
<asp:TemplateField HeaderText="IsExist">
<ItemTemplate>
<asp:CheckBox ID="chkExists" runat="server" Text="Exists" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Not Exists In Update">
<ItemTemplate>
<asp:CheckBox ID="chkExistsInUpdate" runat="server" Text="NotExists" AutoPostBack="false"/>
</ItemTemplate>
</asp:TemplateField>
Here I have 2 checkboxes but in different columns i.e. chkExist for Exist column and chkExistInUpdate for NotExist column in gridview. I want If they both checked then alert() mesg should display like "You can check Only one checkbox"..
So here is my javascript code....
function check_one() {
var obj = document.form1;
var isValid = false;
var gridView = document.getElementById('<%= Gridview1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
if (inputs == null) {
if (inputs[0].type == "chkExists" && inputs[0].type == "chkExistsInUpdate") {
if (inputs[0].checked && inputs[0].checked) {
isValid = true;
}
}
var ch1 = inputs[0].type["chkExists"];
}
//alert(inputs[0].type == "chkExists");
alert(ch1);
}
alert("Plese select only 1 check");
return false;
}
So plese suggest me that what changes has to do in javascript...
A: You should use radio buttons, and set a group name dependent by row, because you have a group per row:
<asp:TemplateField HeaderText="IsExist">
<ItemTemplate>
<asp:RadioButton ID="chkExists" runat="server" Text="Exists" AutoPostBack="false" GroupName='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Not Exists In Update">
<ItemTemplate>
<asp:RadioButton ID="chkExistsInUpdate" runat="server" Text="NotExists" AutoPostBack="false" GroupName='<%# Eval("Id") %>'/>
</ItemTemplate>
</asp:TemplateField>
But, if you need checkboxes anyway (it doesn't make sense for me), you can use jQuery:
function check_one() {
$('#<%= Gridview1.ClientID %> tr').each(function() {
if(jQuery(":checkbox", this)
.filter(function(i) { return this.checked; }).length != 1) {
alert("Plese select only 1 check");
}
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parse a string containing integers into a List I want to let the user enter integers in the following ways:
*
*Numbers separated by commas: 1,3,122,64000,27 etc
*Ranges of numbers: 37-2000
*A mixture of the above: 55,2,1-10000,65000-65007,2182
How can I parse a string that may be in any of the forms above an end up with a List of int?
So for example: 1-5,6,7-8 should give a list containing the ints 1,2,3,4,5,6,7,8
I'm pretty new to C# so some example code would be greatly appreciated. Thanks.
A: String.split splitting by comma , will give you all you need then if a group contains - split for it again and you have the two range values
A: This works:
var query =
from x in text.Split(',')
let y = x.Split('-')
let b = int.Parse(y[0].Trim())
let e = int.Parse(y[y.Length - 1].Trim())
from n in Enumerable.Range(b, e - b + 1)
select n;
var result = query.ToList();
I would suggest adding some error handling, but if your input is in the correct format this works.
** EDIT**: The .NET 2.0 version.
var result = new List<int>();
foreach (var x in text.Split(','))
{
var y = x.Split('-');
var b = int.Parse(y[0].Trim());
var e = int.Parse(y[y.Length - 1].Trim());
for (var n = b; n <= e; n++)
{
result.Add(n);
}
}
Much the same... :-)
A: Tokenise the string based on the ',' then parse that list of individual numbers or ranges.
From memory there is a Split(..) method on List that you can use to get the tokens. Then just test fot the presence of a '-' (if its the first character then its negative, not a range obviously).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PATH environment variable in Linux I want to know how the standard environment variables given by the Linux OS like PATH, HOME are set automatically. Which file(s) are these read from. There should be some file from which these variables are set when a particular user logs in.
A: I would like to add a few more details to what @cnicutar has already mentioned.
Environment variables including PATH can be:
*
*System wide - The values of the environment variables last till the system is up
*Session wide - Lasts till a session lasts (till user logs out)
/etc/profile is meant for system settings for Bourne & Bourne compatible shells. The behavior of /etc/profile may vary across distributions.
For the latest Ubuntu distributions, it is recommended to use /etc/environment for system-wide settings. It is not recommended to use /etc/profile or /etc/bash.bashrc as noted the Ubuntu help.
On Ubuntu machines, /etc/profile is a shell script which sources the scripts in /etc/profile.d and the system-wide bashrc file in /etc/bash.bashrc, whereas /etc/environment is a text file consisting of variable assignments per line which are set into the system-wide environment.
For each user the values of environment variables including PATH (for the shell) can also be manipulated through ~/.profile, ~/.bash_profile, ~./bash_login, and ~/.bashrc where ~ means the user's home directory, like /home/alex/.
To see your current environment variables and their values, you can use printenv.
You can refer to the following link for more details on environment variables on Ubuntu systems: https://help.ubuntu.com/community/EnvironmentVariables
A: There's nothing magic about them, the shell sets them when it starts up.
You should start reading /etc/profile and work up from there. Alternatively, strace might show you what files the shell tries to read when it starts.
For instance, here is how my /etc/profile starts:
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"
export PATH
After that is sources other files which in their turn modify PATH.
A: You can even set and manage your environment variables by yourself by using module enviroment software http://en.wikipedia.org/wiki/Environment_Modules_(software).
To install "module" you can use this command for Centos
sudo yum install environment-modules
For Ubuntu users, you can install it from source:
http://modules.sourceforge.net/
Write a module file to set or prepend environment variables. Then you modules to load this file.
For example, my files name "mypath"
proc ModulesHelp { } {
global version prefix
puts stderr "\t Loads the environment for my installed home folder HOME/local"
}
module-whatis "Loads the environment for my installed home folder HOME/local"
set HOME /home/svu/a0081742
prepend-path PATH $HOME/local/bin
prepend-path LIBRARY_PATH $HOME/local/lib
prepend-path LD_LIBRARY_PATH $HOME/local/lib
prepend-path LD_INCLUDE_PATH $HOME/local/include
prepend-path MANPATH $HOME/local/share/man
Then, you load the file with
module load mypath
Than you can list your loaded modules with
module list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Oracle insert script with condition I have sql insert script like below
insert into table......from table2.;
drop table2.....;
drop table3....;
commit;
is it possible to do condition "insert" must be success before proceed with "drop table2 and table3" in oracle?
A: If you are running under SQLplus :
WHENEVER SQLERROR EXIT SQL.SQLCODE
Also note that the commit operation is optional, as DDL statements (like DROP instructions) will always commit before processing.
A: In sqlplus you can specify "whenever sqlerror exit". So your script will terminate after an error. Alternatively you may want to put you code in a plsql block for more control. Quick example:
begin
begin
insert ...
exception
when others then
dbms_output.put_line(sqlerrm); -- print the error
rais application_error(-20000,'Error in insert statement');
end;
drop 1
drop 2
end;
/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add an app to a page via Graph API? (with Koala gem) Ok, I have a Rails app using the Koala gem. I have manage_pages permissions and I'm able to successfully get the user's pages and access_tokens.
I want to add an application with a Page Tab to one of the user's pages. Basically the equivalent of going to an app's profile, clicking "add to page" and selecting a page to add it to.
I don't see where in the Graph API this is done.
A: If you have the manage pages permission using the Graph API you can install a profile_tab at the end of the current list of installed tabs for a page by issuing an HTTP POST request to PAGE_ID/tabs with a Page Access Token
https://graph.facebook.com/YOUR_PAGE_ID/tabs/create/?app_id=YOUR_APP_ID&access_token=YOUR_TOKEN
Hope that helps.
A: I'm doing it like this:
koala = Koala::Facebook::API.new( page_token )
tabs = koala.get_connections("me", "tabs")
koala.put_connections("me","tabs", {app_id: new_app_id }, {api_version: "v2.3"})
tabs = koala.get_connections("me", "tabs")
inspect tabs and search for the new added tab.
If you want to delete the tab:
koala.delete_connections("me","tabs", {app_id: id_to_be_deleted }, {api_version: "v2.3"})
A: Hey answer that u gave is right.I have also done by same way.
https://graph.facebook.com/pageid/tabs?app_id=applicationid&method=POST &access_token=Page access token`
With this facebook request I am able to add application profile page to my facebook fan page.But I am add comment to that fan page.But that new throught manually and wanted to add comment box inside the fan page.Can I used comment plugin ,how to used that?By application in fbml.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to check version by using xargs command in bash? Please consider the following scenario:
$ find / -type f -name httpd
/opt/httpd.bin/httpd
/etc/rc.d/init.d/httpd
/usr/sbin/httpd
......
I'd like to check each and everyone of the results using the -version option like:
/usr/sbin/httpd -version
But I cannot write the xargs command, is it feasible?
Many thanks in advance.
A: xargs isn't really the right tool for the job, a for loop would work though:
for httpd in $(find / -type f -name httpd)
do
$httpd --version
done
If you have thousands of httpds then you might run into a problem with the length of the $(find...) output but you probably bigger problems on your hands if you have that many httpds.
A: You can use xargs to check the version like this:
find ./ -type f -name httpd | xargs -n1 -I{} bash -c "{} --version"
But I would not recommended, it's cumbersome
You can use:
find ./ -type f -name httpd -exec {} --version \; -print
(with print being optional)
On a side note, make sure that you really want to execute those all the files, /etc/rc.d/init.d/httpd may not know what --version means, some of them may not be executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Trying to implement Render to Texture I'm having trouble implementing render to texture with OpenGL 3.
My issue is that after rendering to the frame buffer, it appears the rendered object becomes deformed, which may imply a bad transformation has occurred somewhere. Which doesn't make sense as the object renders fine when not using my frame buffer (see bottom of post).
The current result is such:
Current result http://k.minus.com/jZVgUuLYRtapv.jpg
And the expected result was this (or something similar, this has just been GIMP'd):
Expected http://k.minus.com/jA5rLM8lmXQYL.jpg
It therefore implies that I'm doing something wrong in my frame buffer set up code, or elsewhere. But I can't see what.
The FBO is set up through the following function:
unsigned int fbo_id;
unsigned int depth_buffer;
int m_FBOWidth, m_FBOHeight;
unsigned int m_TextureID;
void initFBO() {
m_FBOWidth = screen_width;
m_FBOHeight = screen_height;
glGenRenderbuffers(1, &depth_buffer);
glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_FBOWidth, m_FBOHeight);
glGenTextures(1, &m_TextureID);
glBindTexture(GL_TEXTURE_2D, m_TextureID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_FBOWidth, m_FBOHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &fbo_id);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_id);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_TextureID, 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Here is my drawing box code, which just takes a transformation matrix and calls the appropriate functions. The current values of P is a projection matrix, and an identity matrix for the view matrix (V).
void drawBox(const Matrix4& M) {
const Matrix4 MVP = M * V * P;
if (boundshader) {
glUniformMatrix4fv((*boundshader)("MVP"), 1, GL_FALSE, &MVP[0]);
}
glBindVertexArray(vaoID);
glDrawElements(GL_TRIANGLES, sizeof(cube.polygon)/sizeof(cube.polygon[0]), GL_UNSIGNED_INT, 0);
}
void drawStaticBox() {
Matrix4 M(1);
translate(M, Vector3(0,0,-50));
drawBox(M);
}
void drawRotatingBox() {
Matrix4 M(1);
rotate(M, rotation(Vector3(1, 0, 0), rotation_x));
rotate(M, rotation(Vector3(0, 1, 0), rotation_y));
rotate(M, rotation(Vector3(0, 0, 1), rotation_z));
translate(M, Vector3(0,0,-50));
drawBox(M);
}
And the display function called by GLUT.
void OnRender() {
/////////////////////////////////////////
// Render to FBO
glClearColor(0, 0, 0.2f,0);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_id);
glViewport(0, 0, m_FBOWidth, m_FBOHeight);
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
GL_CHECK_ERRORS
colorshader.Use();
boundshader = &colorshader;
drawRotatingBox();
colorshader.UnUse();
/////////////////////////////////////////
// Render to Window
glClearColor(0, 0, 0, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, screen_width, screen_height);
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
GL_CHECK_ERRORS
texshader.Use();
boundshader = &texshader;
glBindTexture(GL_TEXTURE_2D, m_TextureID);
drawStaticBox();
texshader.UnUse();
// Swap le buffers
glutSwapBuffers();
}
And... the obligatory texture shader code
vertex
#version 330
in vec2 vUV;
in vec3 vVertex;
smooth out vec2 vTexCoord;
uniform mat4 MVP;
void main()
{
vTexCoord = vUV;
gl_Position = MVP*vec4(vVertex,1);
}
fragment
#version 330
smooth in vec2 vTexCoord;
out vec4 vFragColor;
uniform sampler2D textureMap;
void main(void)
{
vFragColor = texture(textureMap, vTexCoord);
}
The following is what is rendered when not using the FBO logic:
What is rendered to the FBO http://k.minus.com/jiP7kTOSLLvHk.jpg
... Help?
Any ideas on what I may be doing wrong?
Further source available on request.
A: Without looking closely at your code, this is some example FBO code that works for sure (animates the Teapot to a texture, draws the texture to the sides of a spinning cube).
#include <GL/glew.h>
#include <GL/glut.h>
#include <cmath>
#include <iostream>
using namespace std;
namespace render
{
int width, height;
float aspect;
void init();
void reshape(int width, int height);
void display();
int const fbo_width = 512;
int const fbo_height = 512;
GLuint fb, color, depth;
};
void idle();
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
glutCreateWindow("FBO test");
glutDisplayFunc(render::display);
glutReshapeFunc(render::reshape);
glutIdleFunc(idle);
glewInit();
render::init();
glutMainLoop();
return 0;
}
void idle()
{
glutPostRedisplay();
}
void CHECK_FRAMEBUFFER_STATUS()
{
GLenum status;
status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
switch(status) {
case GL_FRAMEBUFFER_COMPLETE:
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
/* choose different formats */
break;
default:
/* programming error; will fail on all hardware */
throw "Framebuffer Error";
}
}
namespace render
{
float const light_dir[]={1,1,1,0};
float const light_color[]={1,0.95,0.9,1};
void init()
{
glGenFramebuffers(1, &fb);
glGenTextures(1, &color);
glGenRenderbuffers(1, &depth);
glBindFramebuffer(GL_FRAMEBUFFER, fb);
glBindTexture(GL_TEXTURE_2D, color);
glTexImage2D( GL_TEXTURE_2D,
0,
GL_RGBA,
fbo_width, fbo_height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0);
glBindRenderbuffer(GL_RENDERBUFFER, depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, fbo_width, fbo_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth);
CHECK_FRAMEBUFFER_STATUS();
}
void reshape(int width, int height)
{
render::width=width;
render::height=height;
aspect=float(width)/float(height);
glutPostRedisplay();
}
void prepare()
{
static float a=0, b=0, c=0;
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_TEXTURE_2D);
glBindFramebuffer(GL_FRAMEBUFFER, fb);
glViewport(0,0,fbo_width, fbo_height);
glClearColor(1,1,1,0);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, 1, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glLightfv(GL_LIGHT0, GL_POSITION, light_dir);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color);
glTranslatef(0,0,-5);
glRotatef(a, 1, 0, 0);
glRotatef(b, 0, 1, 0);
glRotatef(c, 0, 0, 1);
glutSolidTeapot(0.75);
a=fmod(a+0.1, 360.);
b=fmod(b+0.5, 360.);
c=fmod(c+0.25, 360.);
}
void final()
{
static float a=0, b=0, c=0;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0,0, width, height);
glClearColor(1.,1.,1.,0.);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0,0,-5);
glRotatef(b, 0, 1, 0);
b=fmod(b+0.5, 360.);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, color);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_LIGHTING);
float cube[][5]=
{
{-1, -1, -1, 0, 0},
{ 1, -1, -1, 1, 0},
{ 1, 1, -1, 1, 1},
{-1, 1, -1, 0, 1},
{-1, -1, 1, -1, 0},
{ 1, -1, 1, 0, 0},
{ 1, 1, 1, 0, 1},
{-1, 1, 1, -1, 1},
};
unsigned int faces[]=
{
0, 1, 2, 3,
1, 5, 6, 2,
5, 4, 7, 6,
4, 0, 3, 7,
3, 2, 6, 7,
4, 5, 1, 0
};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 5*sizeof(float), &cube[0][0]);
glTexCoordPointer(2, GL_FLOAT, 5*sizeof(float), &cube[0][3]);
glCullFace(GL_BACK);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_INT, faces);
glCullFace(GL_FRONT);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_INT, faces);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
void display()
{
prepare();
final();
glutSwapBuffers();
}
}
Just for reference to have something that works.
A: Not sure why you're multiplying by a matrix in the shader. Assuming you're wanting to stretch the render-to-texture texture across the screen, you simply need to define 4 vertices, from -1 to 1 on x and y, and pass these into the shader (4 vertex if you're drawing a strip with 2 triangles of course).
In the shader just multiply the vertex by 0.5 and add 0.5 to get the texture coordinates. So you don't need to pass texture coordinates in as you can generate these directly in the vertex shader. The vertices are already in screen space if you define them as -1 to 1, so you don't need to do anything with them except emit them from the vertex shader.
A: As was pointed out by Jari Komppa on GameDev.stackexchange, and neodelphi as a comment on my main post.
The texture coordinates were wrong (or in my case, not passed).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Grouping strings by first character (alpha and numeric) I have a list of strings (product names) from which I need to create a product index (based on first-char of the product name) of the form "0-9", "A", "B", ... "Z".
I am doing this:
Products.GroupBy(p => p.Name[0].ToUpper())
But that doesn't work for the product names which start with "0".."9".
How do I modify the query to group all alphas into different groups ("A".."Z"), as well as all numerics into a single group ("0-9")?
A: You haven't said whether you're using LINQ to SQL or LINQ to Objects or something else. In LINQ to Objects I'd probably use:
Products.GroupBy(p = {
char c = p.Name[0];
return c >= '0' && c <= '9' ? '0' : char.ToUpper(c);
});
(Note that ToUpper is culture-sensitive, by the way - it's not clear whether that's what you want or not.)
In LINQ to SQL (where block lambdas can't be used, as they can't be converted to expression trees) I'd probably use a let clause to do the same sort of thing in a different way:
var query = from product in products
let c = product.Name[0]
group product by c >= '0' && c <= '9' ? '0' : char.ToUpper(c);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PDF generation on iPhone, size of mediaBox When creating a PDF, when you create the mediabox, how do you know what size you want to create it? If I want it to fit a standard 8.5x11 paper so I could email it to someone and they could print it, do I make the mediaBox to be 850,1100? Thanks.
A: The values in mediaBox are points (1/72th of an inch). For letter paper use 612,792 (8.5*72, 11*72).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: submit_tag with javascript function I am new to rails.I want to call a javascript function when click the submit button.I used submit_tag , but the function did not get triggered.I want some thing like the following ,
<%= submit_tag , :onsubmit => "return validateform()" %>
I googled the problem but I couldn't find a solution.Please any one give a solution.
A: You can use something like this on the form tag
<% form_for :bla, :html => { :onsubmit => 'blahblah;' } do |f| %>
A: You can try
<%= submit_tag , :onclick => "return validateform()" %>
OR
You can Use button_to_function
<%= button_to_function "Greeting", "validateform()" %>
And in your Javascript function, if all the validations pass, submit the form.
A: You would do it in the form_tag...
<%= form_tag({:action => :whatever}, {:onSubmit => 'return validateform();'} ) %>
A: try onclick
<%= submit_tag , :onclick => "return validateform();" %>
or if you want to use onsubmit you can use that in your form_tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Struggling with Assembly Language I am having a hard time grasping the concepts of assembly language. I am given this sample code:
ploop: mov ax, 0201h
add al, ah
cmp al, 5
jb ploop
eloop:
The hex value at the end of the loop is 0205, but I'm not sure I understand why.
For the first line, we are moving 0201 into ax, so al = 01 and ah = 02. Then you add ah to al, making al = 03. We compare al to 5 and since 3 < 5, it fits jb and goes through the ploop again. We go through all the steps and at cmp al = 05 == 5, so it no longer fits jb.
Is this the right way of looking at it?
A: Almost correct. Except you probably want it to look like the following instead:
mov ax, 0201h
ploop: add al, ah
cmp al, 5
jb ploop
eloop:
As it will otherwise go into an infinite loop as al and ah are overwritten in each loop iteration.
A: I would almost bet you've transcribed the code incorrectly. As it stands, you have an infinite loop. It needs to be more like this:
mov ax, 0201h
ploop: add al, ah
cmp al, 5
jb ploop
eloop:
As you posted it, ax is being re-loaded with 0201h at the beginning of each iteration of the loop. You're then adding the 02 in ah to the 01 in al. That'll give 3. You compare that to 5 and if it's less than (obviously it always will be) you execute the loop again.
With the label moved, we start with 02 in ah and 01 in al. At each iteration of the loop, however, we add 02 to the current content of al, so it will follow the sequence 1, 3, 5. At each iteration we compare its content to 5, and continue the loop if and only if it's less than (viewed as an unsigned), so the loop with execute three iterations, then stop with al = 5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone Dev - Drawing Application first time user and iPhone Developer Novice. My question focuses on the architecture of my application rather than nitty gritty code. My question to you is: Am I on the right track or do I need to rethink my approach to this part of the application?
I am trying to make a simple "connect the dots" application. My application has working free-hand draw-by-touch functionality and I am using UIButtons to represent each dot.
I've approached this problem by calling for the center property of 2 UIButtons(the dots) and placing conditions to only draw a line if the start/end CGPoints are the center coordinates for these 2 dots. This isn't working!
So my question is:
Is UIButtons the best approach for representing each dot? If so, what functionality should be added to each dot? It seems like a strong candidate since you could call the center property and get it's center coordinate. But since I've run into problems with this, I've considered a single pixel probably isn't big enough to place conditions on.
If UIButtons aren't the best approach for representing each dot, what is a better alternative?
Lastly, I've spent a great amount of time researching the properties and functionality of UIButtons because of this problem. I can't find a good reference to the descriptions of the Sent Events options available through the UIButton. Does anyone know a good blog/reference?
Thanks for your help in advance.
A: UIButton tapping is not advisable. Here is a sample for you to free-hand drawing by touch.
http://www.ifans.com/forums/showthread.php?t=132024
A: Instead of focusing on UIButtons and their events, I removed the UIButtons and focused on the touchesBegan, touchesMoved, and touchesEnd methods. I incorporated CGContext methods to only draw lines when a UITouch is registered at a specific initial location and a specific current location. While I am not sure if this is the most ideal/efficient answer to my problem, it works well and has allowed me to move on to the next phase of my project. If anyone has suggestions to improve this solution, it would be greatly appreciated. Below is a snippet of the code I used for this solution:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if([touch tapCount] == 2) {
image1_.image = nil;
return;
}
initialPoint = [touch locationInView:self.view];
//If initial touch to screen is within 15 pixels of Dot 1, set coordinates to Dot 1
if(initialPoint.x > 36 && initialPoint.x < 66 && initialPoint.y > 161 && initialPoint.y < 191)
{
initialPoint.x = 51.0;
initialPoint.y = 176.0;
}
//If initial touch to screen is within 15 pixels of Dot 2, set coordinates to Dot 2
if(initialPoint.x > 199.5 && initialPoint.x < 229.5 && initialPoint.y > 170.5 && initialPoint.y < 190.5)
{
initialPoint.x = 214.5;
initialPoint.y = 175.5;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentPoint = [touch locationInView:self.view];
//If current touch to screen is within 15 pixels of Dot 2, and the initial touch is
//set to Dot 1, draw line
if(currentPoint.x > 199.5 && currentPoint.x < 229.5 && currentPoint.y > 170.5 && currentPoint.y < 190.5 && initialPoint.x == 51.0 && initialPoint.y == 176.0)
{
currentPoint.x = 214.5;
currentPoint.y = 175.5;
UIGraphicsBeginImageContext(self.view.frame.size);
[image1_.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width,
self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapSquare);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 4.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), initialPoint.x, initialPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
image1_.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lineIsDrawn = YES;
}
//If current touch to screen is within 15 pixels of Dot 3, and the initial touch is
//set to Dot 2, and a line has already been drawn between Dot 1 & Dot 2, draw line
if(currentPoint.x > 155.5 && currentPoint.x < 180.5 && currentPoint.y > 0 && currentPoint.y < 28.5 && initialPoint.x == 214.5 && initialPoint.y == 175.5 && lineIsDrawn == YES)
{
currentPoint.x = 170.5;
currentPoint.y = 13.5;
UIGraphicsBeginImageContext(self.view.frame.size);
[image1_.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width,
self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapSquare);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 4.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), initialPoint.x, initialPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
image1_.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to make IE8 honour opacity on an `:before` pseudo element? I have this simple CSS...
div:before {
content: "G'day";
filter: alpha(opacity=40);
-moz-opacity: .4;
opacity: .4;
}
jsFiddle.
The :before pseudo element has the correct opacity in Firefox 6. In IE8, the opacity is not applied.
Typically, setting the opacity on the div works, but that isn't what I want.
I tried adding display: block but it didn't help.
Whilst I could workaround this, is there any trick to get IE8 to honour the opacity property on a :before (and :after for that matter) pseudo element?
A: I don't think it's possible.
I had the same problem a while back, and I ended up just working around it (by not using :before).
Here's some sound reasoning as to why it's not possible: Why does a filter gradient on a pseudo element not work in IE8?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: equating java classes with different annotations If we have the following condition
Server Domain class
package com.server;
class A {
@Foo
B b;
@Foo
int c;
}
Now on the server we do..
Gson gson = new Gson();
String json = gson.toJson(storeOfListsOfChangedDomainObjectsOnClient);
and send the json to the client ....
Also we take the server domain class, and put it on the client with the same package name, but different annotations, as follows
Client Domain class
package com.server;
class A {
@Bar
B b;
@Bar
int c;
}
on the client we do....
Gson gson = new Gson();
is the following correct ........
com.server.A response = gson.fromJson(json, A.class);
Will the object be equated?
Because otherwise, we will have to take each response class (domain class) of the server and copy each variable individually to the domain class of the client.
Also, the @Foo and @Bar are Hibernate annotation on the Server side, and ORMLite annotations (for Android) on the client side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Capture and monitor the request of the flash client to the server I want to make an auto-play for some flash-based web-game, but I don't know how to capture and monitor the request from the flash client to the server.
Can anyone help me solve this problem
A: You can use FireBug or a debugging proxy like Charles. Flash's requests will show up like normal HTTP requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apple Mach-O Linker Error: Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1 I've searched and searched and am having trouble compiling one of the Jack Audio iPhone projects. I modernized the project and keep getting this when I compile. Can't figure it out.
Ld /Users/zacharywilliams/Library/Developer/Xcode/DerivedData/iPhoneNet-bjquhpgcjgjaitgvrbiuaobtwtfy/Build/Products/Debug-iphoneos/NetJackSlave.app/NetJackSlave normal armv7
cd /Users/zacharywilliams/trunk/jackmp/macosx/iphone
setenv IPHONEOS_DEPLOYMENT_TARGET 4.3
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-g++-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -L/Users/zacharywilliams/Library/Developer/Xcode/DerivedData/iPhoneNet-bjquhpgcjgjaitgvrbiuaobtwtfy/Build/Products/Debug-iphoneos -L/Users/zacharywilliams/trunk/jackmp/macosx/iphone/build/Debug-iphonesimulator -F/Users/zacharywilliams/Library/Developer/Xcode/DerivedData/iPhoneNet-bjquhpgcjgjaitgvrbiuaobtwtfy/Build/Products/Debug-iphoneos -filelist /Users/zacharywilliams/Library/Developer/Xcode/DerivedData/iPhoneNet-bjquhpgcjgjaitgvrbiuaobtwtfy/Build/Intermediates/iPhoneNet.build/Debug-iphoneos/iPhoneNetSlave.build/Objects-normal/armv7/NetJackSlave.LinkFileList -dead_strip libcelt.a -miphoneos-version-min=4.3 -framework Foundation -framework UIKit -framework CoreGraphics -framework AudioToolbox -o /Users/zacharywilliams/Library/Developer/Xcode/DerivedData/iPhoneNet-bjquhpgcjgjaitgvrbiuaobtwtfy/Build/Products/Debug-iphoneos/NetJackSlave.app/NetJackSlave
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1
Thanks for any help!
Zach
A: In my case, I was accidentally importing a .m file.
A: UPDATE: Hey, note the line in your build log:
Couldn't open shared capabilities memory GSCapabilities (No such file or directory).
Here is the solution: What is "Couldn't open shared capabilities memory GSCapabilities (No such file or directory)"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.