text stringlengths 8 267k | meta dict |
|---|---|
Q: Search A For A Document Library or Document In a Document Library in Sharepoint I am new to Share Point. I created a Document Library and added a number of documents to that library. When I use the "Search" feature, I enter the exact name of a document in that document library, but I contiue to get no results. I don't understand why? Thank You!
A: Your administrator must enable searching for your SharePoint site collection. Also, they must setup and make sure the SharePoint search service is running.
Here is another SO thread where they ask a similar question: How to enable search in documents in SharePoint 2010?
The answer points to this article: http://sharepoint.stackexchange.com/questions/3531/sharepoint-2010-search-not-working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding entity in the domain service insert method I have two entities, Parent and Child, at the client side i create Parent and then call context.submitChanges
At the server side in the InsertParent(Parent parent) i do:
InsertParent(Parent parent)
{
Child child = this.ObjectContext.Childs.CreateObject();
parent.child = child;
if ((parent.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(parent, EntityState.Added);
}
else
{
this.ObjectContext.Parents.AddObject(parent);
}
}
Now i'm having two problems.
Before the if else, Parent.id is 0 and after its still 0 but in the database its populated.
The other one is, Child gets saved but Child.ParentId is 0.
I'm not understanding why.
Whats the correct way to achieve this behaviour? should i call SaveChanges() on the context directly?
A: Check to make sure the StoreGeneratedPattern property on Parent.Id in your edmx is set to Identity. That should make sure it gets updated with the new value on inserts.
I'd also wrap this in a transaction so you can add your child after the parent id is set.
using(var scope = new TransactionScope()){
ObjectContext.Parents.AddObject(parent);
ObjectContext.SaveChanges(); //parent.id assigned
parent.child = ObjectContext.Child.CreateObject();
ObjectContext.SaveChanges();
scope.Complete(); // commit transaction
}
A: Yes you should use the SaveChanges() because that's what persist your data into the Database.
Very Easy Example
You also need to check the parents.Id column and childs Id column that they are set as identity and as primary keys, and the relations between the two tables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET Button with no code reloads page in a new window when clicked I have a very simple ASP.NET project. It consists of two pages.
The first page (FirstPage.htm) has the following markup:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function test() {
window.showModalDialog('PageTwo.aspx', '', '');
};
</script>
</head>
<body>
<a href="#" onclick="test();">Test Window</a>
</body>
</html>
The second page (PageTwo.aspx) has this as markup:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PageTwo.aspx.vb" Inherits="MyEmptyWebApp.PageTwo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" />
</div>
<asp:Button ID="Button2" runat="server" Text="Button 2" />
</form>
</body>
</html>
and this as the CodeBehind:
Public Class PageTwo
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
So page one has a hyperlink that loads page two in a popup.
Page 2 has a button that should do nothing. However, when I click on the button a new window pops up and loads Page 2 again.
If I navigate directly to page 2, nothing happens.
I'm thinking I must have some odd configuration either in VS or in IIS that's causing it; but I have no idea what.
The solution is here if you want to download it and look.
A: Modal dialogue windows can not handle asp.net postbacks. check out this link
http://www.eggheadcafe.com/tutorials/aspnet/96c46e09-b383-4330-ae8d-99436cb6c330/aspnet-modaldialog-with-postback-and-return-values-to-parent-page.aspx
hope it helps
ps - here is a msdn for more info on modal dialogue
A: Turn off the AutoPostback property on the button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ Boost Concepts Deprecation Warning The top of this page warns about deprecated a API. Where can I find its replacement then?
A: this code wasn't updated to newer model. here you can find all now supported functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Oracle - Why is SELECT * FROM Foo; so slow? I'm working on some Oracle performance issues with our web app. One thing I've noticed that's seems to obfuscate any sort of tests is that simple queries that return a lot of results are still very slow. One example is:
select * from TPM_PROJECTWORKGROUPS;
When I run it, I get:
5825 record(s) selected [Fetch MetaData: 0ms] [Fetch Data: 59s]
[Executed: 9/22/2011 1:52:38 PM] [Execution: 203ms]
If I understand this correctly, it means the actual query took 203ms to run but it took 59 seconds for that data to be returned to the client, is that was "Fetch" means in this case?
I don't have access to connect to the database machine directly and run the query locally, but is it safe to assume that the culprit is the actual network bandwidth itself? This makes sense since I'm in Seattle and the server is in New York, but still a minute for 5800 rows seems like pretty slow through-put.
Is there any quick advice for a) confirming that network bandwidth is indeed the problem and b) any "gotchas" or things to check for why serializing the data over the wire is so slow? Thanks!
A Few Updates Based On Comments:
SELECT COUNT(*) FROM (select * from TPM_PROJECTWORKGROUPS) t;
Results:
1 record(s) selected [Fetch MetaData: 0ms] [Fetch Data: 0ms]
[Executed: 9/22/2011 2:16:08 PM] [Execution: 219ms]
And if I try selecting only one column:
SELECT PROJECTID FROM TPM_PROJECTWORKGROUPS;
Results:
5825 record(s) selected [Fetch MetaData: 0ms] [Fetch Data: 1m 0s]
[Executed: 9/22/2011 2:17:20 PM] [Execution: 203ms]
Table schema:
PROJECTID (NUMBER)
WORKGROUPID (NUMBER)
A: What API are you using to interact with the database (SQL*Plus, JDBC, ODBC, etc.)? Any API will have some function that specifies how many rows (or how much data) to fetch in a single network round-trip. For example, in SQL*Plus, it's set arraysize N. In JDBC, it's setFetchSize. Other APIs will have similar functions. If you're on a WAN, you generally want to minimize how chatty your application is by increasing the number of rows fetched with each network round trip.
Along the same lines, you'll probably benefit from moving less data over the network and pushing more logic to the server. Do you actually display a grid with 5800 rows of data to the user? Or do you do fetch that data and then perform some processing in the application (i.e. order the data and display the first 100 rows)? If you can push that processing to the database and reduce the amount of data that has to be transmitted over the database, you'll be much better off.
Oracle has options to configure the SDU and TDU as well as a few other networking parameters in SQL*Net. I wouldn't start looking at those options, though, until you've optimized the fetch size and ensured that you're pulling back the least amount of data possible.
A: As you are dealing with a web app, getting something back quick is important.
Investigate the FIRST_ROWS hint. That may be of value to your situation.
A: Selecting a few thousand rows from a table shouldn't take almost a minute. My guess is that you have a performance problem elsewhere in your system. Could be other activity in the DB, or issues with the server/network/storage. Is performance with other queries in your DB similarly slow?
A: Please check table fragmentation. Usually Table Fragmentaion cause more I/O and query goes slow. you can check it using oracle segment advisor and to solve it there are two ways first using oracle shrink table command: is to slow and also lock table, second using oracle move table command, this one is too fast specially if use by oracle parallel option. the only point about move table is it will unused indexes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What does [webView loadRequest:[webView request]] do? I was assuming that it would refresh the page but I have hidden parameters within the page and after [webView loadRequest:[webView request]] these parameters are retained (which is not the case when I refresh the page on Safari; it resets everything to default).
EDIT: [webView loadRequest:[webView request]] behaves differently than [webView reload]. I had an alert with a cancel button on it. When I set Cancel to reload, it reloads the page over and over again. However, loadRequest: reloads the page only once.
A: Why not use UIWebViews -reload if you want to reload the page?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apple - Suspend / refund in-app auto-renewable subscription I have an iPhone/iPad application that offers a monthly subscription to a service. Although, this service is totally useless during 2 months in the whole year.
Is there any way to either suspend all my users subscription for 2 months, or give them a 2 months refund every year so they don't pay for a useless service ?
A: After a good talk with an Apple employee, it is not possible to suspend an auto-renewable product.
Also, 0$ subscriptions do not exist outside NewsStand apps for the moment.
In order to solve our problem, we will have to delete the in-app product in iTunes Connect. This will automatically cancel all active subscriptions we have so the users will not be charged for nothing.
A big downside to this solution is that we will lose all current subscribers, so next year we have to build up a new subscriber bank from scratch.
A: Maybe you can give two months for free to your users instead of refund them.
A: Have you found any better alternative, since posting your answer about canceling all subscribers every year?
In addition to 1-year subscriptions, apple lets you do other terms as well, including 1-month subscriptions, for both renewable and non-renewable subscriptions.
Maybe you could make your in-app UI look as if the user is signing up for a long-term subscription, but behind the scenes, your app only sends a 1-month non-renewable subscription request to apple. Then, each month, your app automatically requests another 1-month subscription, and another... just skip the months you want to skip.
The user fills out the subscription form in your UI 1 time. Your app logic remembers how many times to start a new 1-month subscription.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: JQuery Custom Animation Issue using SetInterval & SetTimeout The problem I'm having is that IE and Safari (Mac OS X not Windows Version) are flickering the images during animation and sometimes not doing the animation at all. Google, Firefox, and Opera don't this issue after load. I think it's redownloading the image each time to cause the flicker.
Here's the test site: http://www.yeoworks.cz.cc/otherdomains/theoasis/
Here's the uncompressed JQuery Code:
$(document).ready(function(){
//LOGO ANIMATION
setInterval( function(){
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr1.png)');
}, 0);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr2.png)');
}, 200);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr3.png)');
}, 300);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr4.png)');
}, 400);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr5.png)');
}, 500);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr4.png)');
}, 600);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr3.png)');
}, 700);
setTimeout(function(){
$('#logoani').css('background-image', 'url(ootr2.png)');
}, 800);
}, 900);
});
Thanks for helping :)
A: If an animated gif (even one with very little palette compression) still doesn't do the trick, I would try a different approach. This may be more trouble than it's worth to you; the bug doesn't happen for me in Safari, and I really think you can get there with a carefully compressed animated gif, but nonetheless...
Instead of changing the url of the background-image each time, perhaps IE & Safari would perform better if all the images existed on the page (positioned absolutely on top of one another), and you called .show() and .hide() respectively.
I would store all these images (or jQuery objects containing <img> tags) in an array, and create a function that runs every 100ms via setInterval. When it runs, .show() the 'next' image in the array, while telling the currently visible one to .hide().
This way, you can make sure that there's always an image visible at any given moment, and there's no flicker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a CLR data type to Sql data type translation method? I was going through the MVC material over at asp.net, and came across the 5 minute introduction video:
http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc
In this video, there was demonstration of creating a model, then having MVC generate a Sql table based on the object/model automatically.
My question is, what mechinism is used to translate the object's CLR datatypes to Sql Server datatypes?
I'd like to create a quick and dirty method to have similar functionality outside of MVC... something as simple as a method returning a Create Table string.
A: Like this maybe?
MSDN - Mapping CLR Parameter Data
Or this?
MSDN - SQL-CLR Type Mapping (LINQ to SQL)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to show grouped value in Extjs 4 grid groupHeader? I have a grid like this
var groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
groupHeaderTpl: 'Invoice: {invoice_number} ({rows.length} Item{[values.rows.length > 1 ? "s" : ""]})'
});
{
xtype : 'grid',
store : Ext.getStore('invoice_items'),
columns : [
{ text: 'Invoice Number', flex: 1, dataIndex: 'invoice_number', hidden:true },
{ text: 'Item Code', flex: 1, dataIndex: 'item_code'},
{ text: 'Description', flex: 1.5, dataIndex: 'description' }
],
features: [groupingFeature]
}
im using hidden filed invoice_number to group this grid and i have the output like this
what i want to do is show the grouped invoice number in the group header. is it possible in extjs4? how to do it?
Regards
A: found the solution. i though i had to put group column name here
groupHeaderTpl: 'Invoice: {invoice_number} ({rows.length} Item{[values.rows.length > 1 ? "s" : ""]})'
but once i replace it with Invoice: {name}
value of the group column shows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: invalid \x escape Module has no __module_name__ defined when loading the following (or any python script for xchat version 2.8.9 on 64 bit windows 7):
__module_name__ = "test.py"
__module_version__ = "0.666"
__module_description__ = "I AM AN EXPERT PROGRAMMER"
import xchat, random, string, re
def test(word, word_eol, userdata):
cmd = word[1]
text = open("E:\\xpy\\nickslol.txt","r")
for line in text:
line = line.rstrip("\r\n")
xchat.command("%s %s" % (cmd, line))
xchat.hook_command("test", test)
[02:31:14] ValueError: invalid \x escape
[02:31:14] Module has no __module_name__ defined
A: Use raw strings for windows pathnames: r"E:\xpy\nickslol.txt"
A: It appears to be an error within xchat. The script works in the C drive, but not in subfolders.
IOError: [Errno 2] No such file or directory: 'C:\test\\startup.py'
Either the single or double backslash should not be there, depending on interpretation. They should definitely be consistent!
A: I recently came across this error. I'm far from an expert programmer, but I realized the problem is the \x in the string.
in python 2.7 (only version I tested)
x = 'C:\Users\xfolder\Desktop' # will give an "invalid \x escape"
x = 'C:\Users\\xfolder\Desktop' # will work properly (notice the stored value after)
I wish I could expand, but hopefully this is somewhat helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing distinct Multiple Parameters in SSRS I'm in a peculiar situation here. I have a report which takes @ProjectID as a parameter and shows all the info related to that project.
Now I have to pass multiple project ids separately as parameters to the report and each report(ProjectID) should show in a distinct page.
I did research on Multivalues parameters but could not find a way to accomplish this. Any advice is much appreciated.
A: Create the @ProjectId parameter as multivalue
In your SQL query use the multivalue parameter using IN eg. WHERE ProjectId IN (@ProjectId)
Add a table group, grouping on ProjectId field. In the group settings enable "Page break at end"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot access NSMutableDictionary outside method where values are passed into it I am trying to set up Index and sections for my uitableview, which I have managed to do.. However now that I am trying to pass my NSDictionary values over to my uitableviewcell my app is crashing when I try to access the NSDictionary outside of the method that I passed the values to it from.
I am thinking that maybe I am not passing the values in correctly or something along the line of that, but I simply cannot figure out why its going this...
Heres my code...
.h
@interface VehicleResultViewController : UITableViewController <NSXMLParserDelegate> {
//......
//Indexed tableview stuff
NSArray *sortedArray;
NSMutableDictionary *arraysByLetter;
NSMutableArray *sectionLetters;
}
//.....
//Indexed tableview stuff
@property (nonatomic, retain) IBOutlet NSArray *sortedArray;
@property (nonatomic, retain) IBOutlet NSMutableDictionary *arraysByLetter;
@property (nonatomic, retain) IBOutlet NSMutableArray *sectionLetters;
//....
.m
//...
//This is where I try to access the NSDictionary to pass it to my uitableviewcells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryNone; //make sure their are no tickes in the tableview
cell.selectionStyle = UITableViewCellSelectionStyleNone; // no blue selection
// Configure the cell...
NSString *value = [self.arraysByLetter objectForKey:[[self.arraysByLetter allKeys] objectAtIndex:indexPath.row]];
cell.textLabel.text = key;
NSLog(@"%@",arraysByLetter);
return cell;
}
//This is where I set NSDictionary
//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSMutableArray *)arrayData
{
//Sort incoming array alphabetically
sortedArray = [arrayData sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
//NSLog(@"%@",sortedArray);
// Dictionary will hold our sub-arrays
arraysByLetter = [NSMutableDictionary dictionary];
sectionLetters = [[NSMutableArray alloc] init];
// Iterate over all the values in our sorted array
for (NSString *value in sortedArray) {
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [value substringWithRange:NSMakeRange(0, 1)];
NSMutableArray *arrayForLetter = [arraysByLetter objectForKey:firstLetter];
if (arrayForLetter == nil) {
arrayForLetter = [NSMutableArray array];
[arraysByLetter setObject:arrayForLetter forKey:firstLetter];
[sectionLetters addObject:firstLetter]; // This will be used to set index and section titles
}
// Add the value to the array for this letter
[arrayForLetter addObject:value];
}
// arraysByLetter will contain the result you expect
NSLog(@"Dictionary: %@", arraysByLetter); //This prints what is currently in the NSDictionary
//Reloads data in table
[self.tableView reloadData];
}
.output of checking the Dictionary with NSLog in the last method above
Dictionary: {
H = (
Honda,
Honda,
Honda,
Honda,
Honda,
Honda,
Honda
);
M = (
Mazda,
Mazda,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi
);
N = (
Nissan,
Nissan,
Nissan,
Nissan,
Nissan,
Nissan,
Nissan
);
T = (
Toyota,
Toyota,
Toyota
);
}
I have debugged the two points (where i set the NSdictionary in the method) and (where I access the NSDictionary in cellforrowatindexpath) and it is defiantly set before I even try to use it.
Any help would be greatly appreciated..
A: //Indexed tableview stuff
@property (nonatomic, retain) NSArray *sortedArray;
@property (nonatomic, retain) NSMutableDictionary *arraysByLetter;
@property (nonatomic, retain) NSMutableArray *sectionLetters;
REMOVE IBOutlet from properties declarations. It's only for Interface Builder controls.
Also correct dictonary allocation - self.arraysByLetter = [NSMutableDictionary dictionary];
A: The NSMutableDictionary that is allocated is autoreleased, therefore when it is called in the other method the NSAutoreleasePool has been drained, and the NSMutableDictionary has been released. If you want to retain the object using the property you have to do it like this:
self.arraysByLetter = [NSMutableDictionary dictionary];
self will set the dictionary using the setter which is declared as retain, so it will be available when you try to use it later on.
As a note any method that does not start with new or alloc or contains copy must return an autoreleased object, which is your case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GNU Binutils' Binary File Descriptor library - format example As in title. I tried reading the BFD's ELF's code, but it's rather not a light reading. I also tried to get something from the documentation, but I would need an example to see how it works. Could anyone point me some easier example for me, to know how to define an executable format?
Edit: Looks like I didn't formulate the question properly. I don't ask "how to create own executable format specification?", nor "where is good ELF documentation?", but "how can I implement my own executable format using GNU BFD?".
A: You did look here http://sourceware.org/binutils/docs-2.21/bfd/index.html and here http://sourceware.org/binutils/binutils-porting-guide.txt?
Also studying the MMO implementation of a BFD backend as mentioned here http://sourceware.org/binutils/docs-2.21/bfd/mmo.html#mmo (source: http://sourceware.org/cgi-bin/cvsweb.cgi/src/bfd/mmo.c?cvsroot=src) might be less complex than starting with ELF ... ;-)
A: I agree that BFD documentation is somewhat lacking. Here are some better sources:
*
*ELF Format
*System V ABI (section 4)
Here are a couple of readable introductions:
*
*Linux Journal
*Dr. Dobbs
And some examples that don't use libbfd:
*
*ELF IO
*ELF Toolchain
*LibELF
A: The DOS COM file is the simplest possible format.
Load up to 64k less 256 bytes at seg:0100h, set DS,ES,SS=seg, SP=FFFFh and jump to seg:0100h
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Salesforce.com - Custom mini page layout for new Line Item out of price book I need to programmatically select the fields or values that are shown when I add a line item to an opportunity.
I.E.
If I add a new item of type "A", in the mini page layout, I need to show Fields "X", "Y", "Z". If I add a new item of type "B", in the mini page layout, I need to show fields "X", "Z".
I'm kind of Salesforce newbie. I don't know where to even start. Just a link to the area of documentation that would explain this would be very helpful.
A: So if I understand correctly, you want the line item related list to show different fields on a row according to a certain field on the line item?
I can't think of anyway to do this with standard functionality, leaving two options I can think of:
*
*Create a custom visualforce page and generated the related list yourself, you can then display different details for each row as it'll be 100% custom — since you're new to the platform I doubt this is will be a particularly viable option.
*Use formula fields on the line item to display different values based on the type of a line, then expose these formula fields on the related list.
For example, Forumla_Field_1__c might will use the CASE() function to switch it's output based on one of the fields:
CASE(Type__c, 'A', Field_X__c, 'B' Field_Y__c);
Of course this won't allow you to display a different number of fields on each row, but it will let you see the values you want.
If I've misunderstood, and all line items on a given opportunity will be of the same type, then you'll want to use record types on the opportunity itself, then you can have a different page layout for each record type, and as such, different fields displayed on the related list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: adding xmlns:rim attribute to serialized class I would like to add a namespace and prefix attribute to my serialzed class so my child elements can reference by using the prefix.
My class looks like this:
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.opengis.net/cat/csw/2.0.2")]
public partial class SearchResultsType
{
private object[] itemsField;
private string resultSetIdField;
private ElementSetType elementSetField;
private bool elementSetFieldSpecified;
...
Right now it's returning this:
<SearchResults recordSchema="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0">
<RegistryPackage id="urn:ogc:def:registryPackage:OGC-CSW-ebRIM-EO::EOProducts" objectType="urn:oasis:names:tc:ebxml-regrep:ObjectType:RegistryObject:RegistryPackage"/>
</SearchResults>
And i want it to loom more like this:
<SearchResults xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" recordSchema="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0">
<rim:RegistryPackage id="urn:ogc:def:registryPackage:OGC-CSW-ebRIM-EO::EOProducts" objectType="urn:oasis:names:tc:ebxml-regrep:ObjectType:RegistryObject:RegistryPackage"/>
</SearchResults>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Draw Network in Matlab I need to draw a network (not a neural network) with 5 nodes and 20 directed edges (an edge connecting each 2 nodes), and I need to be able to control the thickness of each edge. Is there a toolbox in Matlab offering this?
Thanks in advance.
A: Yes, Bioinformatics Toolbox will allow you to do this with the biograph command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Precedence of Logical Operators in C
Possible Duplicate:
why “++x || ++y && ++z” calculate “++x” firstly ? however,Operator “&&” is higher than “||”
If you look at C's precedence table, you'll see that && has higher precedence than ||.
But take a look at the following code:
a=b=c=1;
++a || ++b && ++c;
printf("%d %d %d\n",a,b,c);
It prints out "2 1 1", meaning that the "++a" is evaluated first, and once the program sees a TRUE there it stops right there, because what is on the other side of the || is not important.
But since && has higher precedence than ||, shouldn't "++b && ++c" be evaluated first, and then the result plugged back into "++a || result" ? (in this case the program would print "1 2 2").
A: The precedence rules only say that it will be evaluated like this:
++a || (++b && ++c);
Now comes the short circuiting behavior of the logic operators which says that you have to evaluate terms from left to right and stop when the result is known. The part on the right never gets executed.
A: Precedence and order of evaluation are two completely different things. For logical operator expressions, evaluation is always left-to-right. The expression ++a || ++b && ++c is interpreted as
*
*Evaluate ++a
*If the result of 1 is zero, evaluate ++b && ++c
The expression is parsed as ++a || (++b && ++c); the whole expression is true if either of the subexpressions ++a or ++b && ++c is true.
A: Just try to imagine it with parentheses:
++a || ++b && ++c;
equals
(++a) || (++b && ++c);
which is evaluated from left to right.
if && and || would have the same precedence, it would look like
(++a || ++b) && (++c);
A: && has higher precedence only in parse tree. But compiler optimizes the code as
if( !++a ) {
++b && ++c;
}
A: Your example ++a || ++b && ++c is the same as ++a || (++b && ++c).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Detect user touches on MKMapView in iOS 5 I have a MKMapView in a ViewController and would like to detect users' gestures when he/she touches the map with these methods:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
The app works fine with iOS 3, iOS 4
but when I debug the app with iPhone running on iOS 5, I see this message:
Pre-iOS 5.0 touch delivery method forwarding relied upon. Forwarding -touchesCancelled:withEvent: to <MKAnnotationContainerView: 0x634790; frame = (0 0; 262144 262144); autoresizesSubviews = NO; layer = <CALayer: 0x634710>>
and the code in the above 4 methods are not reached.
Do you know how to fix it?
Thanks.
A: Some form of UIGestureRecognizer can help you out. Here's an example of a tap recognizer being used on a map view; let me know if this isn't what you're looking for.
// in viewDidLoad...
// Create map view
MKMapView *mapView = [[MKMapView alloc] initWithFrame:(CGRect){ CGPointZero, 200.f, 200.f }];
[self.view addSubview:mapView];
_mapView = mapView;
// Add tap recognizer, connect it to the view controller
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapViewTapped:)];
[mapView addGestureRecognizer:tapRecognizer];
// ...
// Handle touch event
- (void)mapViewTapped:(UITapGestureRecognizer *)recognizer
{
CGPoint pointTappedInMapView = [recognizer locationInView:_mapView];
CLLocationCoordinate2D geoCoordinatesTapped = [_mapView convertPoint:pointTappedInMapView toCoordinateFromView:_mapView];
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
/* equivalent to touchesBegan:withEvent: */
break;
case UIGestureRecognizerStateChanged:
/* equivalent to touchesMoved:withEvent: */
break;
case UIGestureRecognizerStateEnded:
/* equivalent to touchesEnded:withEvent: */
break;
case UIGestureRecognizerStateCancelled:
/* equivalent to touchesCancelled:withEvent: */
break;
default:
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: MYSQL- How do I create individual tables for forum posts? For every forum post on my site, I'd like to create a MySQL table with the name of its id, in order to enable user commenting. The know-how will also come in handy when creating a table for each user registered, to enable friend tracking.
There are multiple posts across various sites about doing this. I figured that you need to prepare a statement and then append the $id variable to it- then execute. However, all the posts I've read about the topic were confusing and didn't work for me, so I'd like some advice. I am trying to create a table using PHP.
This is what the query should look like:
mysql_query("CREATE TABLE '$id' (...) ")
How do I prepare a statement? I don't really get it.
Or is there a better way to achieve my purpose than with prepared statements?
Thanks for any advice.
A: Don't create a table for each forum (or forum post, wasn't sure from your question). Simply create a table called comments and have a field in that table called 'forum_id'. When a user goes to create a comment on a forum or forum post, then have populate that field with the ID of the forum the user is commenting on. When pulling all comments back, just get all the comments for a particular forum based on the value of the forum_id field.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: script/server returns development database not configured? Rails 2.3.8 When trying to run server I get:
=> Booting Mongrel
=> Rails 2.3.8 application starting on http://0.0.0.0:3000
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active
_record/connection_adapters/abstract/connection_specification.rb:62:in `establis
h_connection': development database is not configured (ActiveRecord::AdapterNotS
pecified)
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activerecord-2.3
.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:55
:in `establish_connection'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/
initializer.rb:437:in `initialize_database'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/
initializer.rb:141:in `process'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/
initializer.rb:113:in `send'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/
initializer.rb:113:in `run'
from C:/Sites/lbtco/config/environment.rb:13
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/custom_
require.rb:29:in `gem_original_require'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/custom_
require.rb:29:in `require'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activesupport-2.
3.8/lib/active_support/dependencies.rb:156:in `require'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activesupport-2.
3.8/lib/active_support/dependencies.rb:521:in `new_constants_in'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activesupport-2.
3.8/lib/active_support/dependencies.rb:156:in `require'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/
commands/server.rb:84
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/custom_
require.rb:29:in `gem_original_require'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/custom_
require.rb:29:in `require'
from script/server:3
C:\Sites\lbtco>
A: It says it right in the first textblock, your development database is not configured
Run
rake db:migrate
in your console. Maybe you have to edit config/database.yml first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with adding two double values in objective c I'm programming an app for iphone and ipad and my program requires adding two double values to get a single double value. The problems is when one of the double values is fairly large (eg: 2^100) and the other one is very small like 1 or 2, the result of adding those two double values is wrong or it doesn't even do the addition. Does anyone know why that is and if there's a way around it. Thank you.
A: This has nothing to do with obj-c. A double is a 64-bit datatype that stores a floating-point value. In decimal, a double can hold approximately 15.955 digits of precision. However, your 2^100 number has about 30 decimal digits. So if you try and add anything up to about 1 quadrillion to it, you'll find that the addition doesn't work since that falls outside of the precision range of your number.
In order to get around this, you can use NSDecimalNumber, which will hold up to 38 decimal digits of precision.
A: This is a good read for anyone dealing with floating-point numbers:
http://en.wikipedia.org/wiki/Floating_point
The situation you describe is completely normal, and is a natural outcome of how floating point works on computers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++11 to_string() function, where? See the N3242 Working Draft of C++11, chapter 21.5 Numeric Conversions.
There are some useful functions, such as string to_string(int val); mentioned but I don't understand how they're called. Can anyone give me an example please?
A: Sure:
std::string s = std::to_string(123); // now s == "123"
These functions use sprintf (or equivalent) internally.
A: They are called like any other function:
int number = 10;
std::string value;
value = std::to_string(number);
std::cout << value;
To call them you will need a C++ compiler that supports the draft recommendations (VS2010 and GCC4+ I think support them).
A: Those functions are in the header <string>. You just call them like any other function:
#include <string>
std::string answer = std::to_string(42);
GCC 4.5 already supports those functions, you just need to compile with the -std=c++0x flag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: VS 2010 Wcf client utility to my project? I have my own wcf program which is not WCF project , and i want to trun the built in client testing tool for my app.
How do i do it ?
A: Based on this article to launch WCF Test Client without running visual studio, do the following:
You can also invoke the WCF Test Client (WcfTestClient.exe) outside
Visual Studio to test an arbitrary service on the Internet. To locate
the tool, go to the following location:
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\
To use the tool, double-click the file name to open it from this
location, or launch it from a command line.
WCF Test Client takes an arbitrary number of URIs as command line
arguments. These are the URIs of services that can be tested.
wcfTestClient.exe URI1 URI2 …
After the WCF Test Client window is opened, click File->Add Service,
and enter the endpoint address of the service you want to open.
source http://msdn.microsoft.com/en-us/library/bb552364.aspx
FYI, I did a Google search with the phrase run wcf test client to find the article.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Admin route in custom modules All stock magento modules have URL path in backend which has 'admin' (by default) part.
However I was not able to achieve that for a custom module. Is this not possible or done on a purpose?
Thanks
A: The first part of the URL is known as the "frontName".
http://example.magento.com/frontName/controllerName/actionName
Magento only allows a single module to claim a particular frontName. For the admin frontname, that's Adminhtml.
However, Magento 1.3 introduced a configuration syntax that allows you to a tell particular module that's already claimed a front name that it (the module) should check additional modules for controller files. This feature is often called real controller overrides, and while you can use it to replace a particular controller in Magento with your own, you can also use (and should use it) it to setup your own controllers for the admin console. The only caveat here is if Magento uses a controller name that you've already picked in a future version, you'll need to adjust things when you upgrade. (in other words, pick unique names)
If you're interested in the details, I'm in the middle of writing a series on Magento's routing engine, which will give you more detail than you'll ever need to know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Intercept the 'Expression' property of IQueryable Provider and gets its e-sql Normally I can query an entity context using linq in the typical way,
IQueryable<Product> query = from p in db.Products
where p.ProductID > 1
select query;
Now say I wanted to get the expression of this IQueryable, serialize it, and pass it over the wire to be reconstructed on the other end,
Expression ex = query.Expression;
XElement xExpression = serializer.Serialize(ex);
wcfClient.InvokeSomeServiceMethod(xExpression);
How would I reconstruct this on the other end? (the server end, to be specific)
I need to create a new instance of IQueryable and 'set' the expression used by the underlying provider by actually passing in an Expression instance, is this possible? There is no setter on IQueryable by default, of course. More specifically I just need an ObjectQuery so I can call ToTraceString() and get the entity sql on the other end. I cant seem to find any point where I can inject the Expression directly.
Thanks.
A: Really, you have two options.
*
*Don't pass general queries over the wire. The server should have a GetProductsWithProductIdGreaterThan method that the client invokes.
*Look at WCF Data Services.
The third option, the one your requesting, is just hard.= Even if you're extremely fluent in LINQ, WCF, and Expression, it's still extremely difficult.
A: I would suggest you look at InterLINQ. It provides the ability to serialize an expression and transmit over WCF.
I'm using it with NHibernate to achieve a similar outcome to what you're describing and it seems to work well. (There's a bit to get your head around though, so as others have suggested, WCF Data Services / OData would be be quicker/easier).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: parse html tags, based on a class and href tag using beautiful soup I am trying to parse HTML with BeautifulSoup.
The content I want is like this:
<a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a>
i tried and got the following error:
maxx = soup.findAll("href", {"class: "yil-biz-ttl"})
------------------------------------------------------------
File "<ipython console>", line 1
maxx = soup.findAll("href", {"class: "yil-biz-ttl"})
^
SyntaxError: invalid syntax
what i want is the string : http://some-web-url/
A: soup.findAll('a', {'class': 'yil-biz-ttl'})[0]['href']
To find all such links:
for link in soup.findAll('a', {'class': 'yil-biz-ttl'}):
try:
print link['href']
except KeyError:
pass
A: You're missing a close-quote after "class:
maxx = soup.findAll("href", {"class: "yil-biz-ttl"})
should be
maxx = soup.findAll("href", {"class": "yil-biz-ttl"})
also, I don't think you can search for an attribute like href like that, I think you need to search for a tag:
maxx = [link['href'] for link in soup.findAll("a", {"class": "yil-biz-ttl"})]
A: To find all <a/> elements from CSS class "yil-biz-ttl" that have href attribute with anything in it:
from bs4 import BeautifulSoup # $ pip install beautifulsoup4
soup = BeautifulSoup(HTML)
for link in soup("a", "yil-biz-ttl", href=True):
print(link['href'])
At the moment all other answers don't satisfy the above requirements.
A: Well first of all you have a syntax error. You have your quotes wrong in class part.
Try:
maxx = soup.findAll("href", {"class": "yil-biz-ttl"})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Use smartGwt with playframework Please How can I integrate smartGwt 2.3 with play?, I'm using GWT2 [gwt2] module 1.8, but I don't know how to add smartgwt components
A: Well it runs with this configuration
require:
- play
- play -> gwt2 1.8
- com.google.gwt -> gwt-user 2.3.0
- com.google.gwt -> gwt-dev 2.3.0
- com.smartgwt -> smartgwt 2.5
repositories:
- smartgwt:
type: iBiblio
root: "http://www.smartclient.com/maven2/"
contains:
- com.smartgwt -> *
A: I would recommend the way from Raphael Bauer which is described at the google-group. There Play is a restful-server which delivers JSON-Messages. Then you use GWT with RestyGWT. No need to use a special module. So you can use GWT-Extension as you usual do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Syntax error near "COUNT (*)"? I'd like to do an interactive stored procedure
I mean, after execution the user should type a word
I wrote this but it doesn't work..
DELIMITER $$
DROP PROCEDURE IF EXISTS ric_forn$$
CREATE PROCEDURE ric_forn (IN nome_forn VARCHAR(100) , OUT msg VARCHAR(100))
BEGIN
DECLARE num_rec INT;
IF (nome_forn = '') THEN
SET msg = "Attenzione il nome inserito non è valido !";
END IF;
SELECT COUNT (*) INTO num_rec FROM Fornitori WHERE Des_Fornitore = nome_forn;
IF num_rec = 0 THEN
SET msg = "Nessun record trovato !";
ELSE
SELECT Id_Fornitore,Des_Fornitore,Ind_Fornitore WHERE Des_Fornitore = nome_forn;
SET msg = "Records trovati:";
END IF;
END$$
DELIMITER ;
I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '*) INTO num_rec FROM Fornitori WHERE Des_Fornitore = nome_forn;
A: The space between COUNT and (*) is significant. You should put them together, don't leave a space.
SELECT COUNT(*) INTO ...
Exception is if you SET SQL_MODE='IGNORE_SPACE'. Read Function Name Parsing and Resolution for more details.
Your other error is that you forgot the FROM clause in one of your queries:
SELECT Id_Fornitore,Des_Fornitore,Ind_Fornitore WHERE Des_Fornitore = nome_forn;
Should be:
SELECT Id_Fornitore,Des_Fornitore,Ind_Fornitore FROM Fornitori
WHERE Des_Fornitore = nome_forn;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does Yahoo BOSS (version 2) allow automated search queries? As far I know, Yahoo BOSS (version 1) didn't allow this. But with the new payed model, does it mean you're allowed to do automated search queries?
A: With version 2 you're allowed to do an unlimited number of requests (if you pay for that).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHPUnit Version issue and Mock Builder I am facing a version issue with phpunit . When I execute
pear install pear.phpunit.de/PHPUnit
I get an error: phpunit/PHPUnit is already installed and is the same as the released version 3.5.15 install failed
But when I execute phpunit --version, I get
PHPUnit 3.4.5 by Sebastian Bergmann.
I do not understand what is happening here. I stumbled on the issue when all of my mock builder functions (setMethod(), getMockBuilder()...etc) threw a undefined method fatal errors and I figured that these methods are only available in 3.5 and up.
All your help is really appreciated. Thanks.
A: If you're on some flavor of Unix/Linux, what does which phpunit report? This should hopefully lead you to your second installation. You can start by renaming the file returned by which.
A: Chances are you need to upgrade your pear version. It should be 1.9.4 (or higher) to work properly.
Try pear update pear and once pear version shows 1.9.4 try pear install phpunit/PHPUnit. It that doesn't help use --force --alldeps arguments.
That should to the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I order core data fetched results from one datastore based on data in another datastore I'm building an iPhone application where I have two datastores, one for static data and one for dynamic data. I use two separate core data stacks for this. The dynamic data includes an entity and attribute for ID and another attribute for a date. The ID attribute references a matching ID in an entity in the static datastore.
I would like to fetch items from the static store that have ID's in the dynamic datastore and order them based on the dates in the dynamic datastore. I have both googled this, and searched through questions here about cross-store fetched properties, but I have not managed to find a solution to this. I can fetch the correct items from the static store, but not in the correct order, so my question is this: Can I somehow (perhaps with fetched properties) fetch the static items sorted by the dates in the dynamic store, or do I need to sort them in code after I fetch them?
EDIT:
An entity in the static store might be referenced by more than one entity in the dynamic store.
A: You can add a transient property to your entity in the managed object model. Transient properties are calculated on demand, so this would be the appropriate place to do the lookup in the other stores.
Then in your fetch request you simply add a sort descriptor which references the transient property on the target object.
In the implementation for the transient property, look up the matching record in the other store and return the date value.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdNSAttributes.html
It's not clear to me why you have chosen to segregate the data though, and this is an especially fragile paradigm as you will have to either eat the performance hit of maintaining the cross store reference, or risk being unable to locate the record in the dynamic store.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Killing The Application In Android I have an application which shows a notification in the status bar for users to click to get resumed into the activity.
In the application, I will also have a close application button which runs:
android.os.Process.killProcess(android.os.Process.myPid());
When I click the close app button, the app will get killed as long as I didn't enter the app through clicking on the notification.
If I have entered the app by clicking on the application, the application will "blink" for a second and a new copy is shown. I suppose a new copy is shown.
Do anyone happen to know what's causing this?
A: You don't kill apps in android, it isn't the way things work. The user navigates away and the system cleans up whats left when needed. Why do you need a "close" button when the phone already has a Home and Back button?
A: Killing your application's process is a terrible thing. Depending on what your app is doing, you could potentially leave some resources not cleaned up properly because of how you've abruptly killed things. There's no reason to do this on android. Android will do a better job of managing resources/battery life without your help.
If you really want to add a close button your best bet is to take users back to their home screen.
A: You said
@Philipp Reichart i tried replacing
android.os.Process.killProcess(android.os.Process.myPid()); with
finish() but it didn't work. the application wasn't killed
I had a similar situation with one of my applications, and finish() wasn't working so I used .killProcess briefly until I could work out the bugs. But this should not be a permanent solution.
My problem was threads. Make sure all of your threads are properly disposed of when they are finished (close IO streams, db references, cursors, etc...). Once I did this there was no reason for .killProcess as finish() did the job.
Also the Android system was built in with the "back" button to exit and the "home" button to "minimize" (keeps the app in memory). Applications don't need an "exit" button because its already there, which gives you more screen real estate :).
A: have you tried system.exit(0); in the onDestroy() after you call finish() when the user selects the "close" button,..
even though is NOT recommended
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: What can you use HTML5's local storage for? I was wondering what are some of the most creative and useful use cases of HTML5's local storage capabilities.
Have you ever encountered any website that uses that feature in a cool way?
In other words, what are some of the examples of places where storing user data in a browser indefinitely can be used?
Any ideas are appreciated
A: one of the most practical reasons to use it is so that the user has some data pre populated when they start their app, i.e. the UI can show data right away, and then sync up with the server behind the scenes. Combined with an html5 manifest, this is quite powerful juju.
It's also useful for RIAs when the app wants to save data intermittently without going to the server. For example, an RIA word processor, you can store the document to local storage....
A: It's helpful to store your applications data while the computer is offline. Then you can synchronize the data when the computer is online again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Need 12-h time formatting in Excel Consider an Excel sheet with one column of bad data. We have a table that can be used to correct the data. My code runs it by writing a new sheet containing the old sheet plus adding new columns of correct data for them to compare.
This date is fine and works but it makes the date/time into a format with 24-h time.
How can this be changed to use the preferred format?
newSheet.Cells[i + 2, 3] = drugorder.DATE;
newSheet.Cells[i + 2, 3].NumberFormat = "m/d/yyyy h:mm";
A: Apparently, the h specifier in an Excel date format will only use 12-hour time if you include an AM/PM specifier in the number format as well.
The seemingly logical .NumberFormat = "m/d/yyyy h:mm" produces:
2/13/1922 5:19
5/17/1927 21:13
While .NumberFormat = "m/d/yyyy h:mm AM/PM" produces the intended:
2/13/1922 5:19 AM
5/17/1927 9:13 PM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: friend function of std::make_shared() in Visual Studio 2010 (not Boost) how to make friend function of std::make_shared().
I tried:
class MyClass{
public:
friend std::shared_ptr<MyClass> std::make_shared<MyClass>();
//or
//friend std::shared_ptr<MyClass> std::make_shared();
protected:
MyClass();
};
but it does not work (i'am using Visual Studio 2010 SP1)
A: It doesn't work because the VC10 implementation hands off construction to an internal helper function. You can dig through the source code and friend this function if you want.
A: How about adding a static method to your class:
class Foo
{
public:
static shared_ptr<Foo> create() { return std::shared_ptr<Foo>(new Foo); }
private:
// ...
};
Here's a little hackaround:
class Foo
{
struct HideMe { };
Foo() { };
public:
explicit Foo(HideMe) { };
static shared_ptr<Foo> create() { return std::make_shared<Foo>(HideMe());
};
Nobody can use the public constructor other than the class itself. It's essentially a non-interface part of the public interface. Ask the Java people if such a thing has a name :-)
A: If you are okay with delving into the internal implementation details of the compiler that you are using, for VC10/Visual C++ 2010, as @DeadMG mentioned, you can befriend the internal implementation. You'll want to befriend std::tr1::_Ref_count_obj<T>.
I've tested this with
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
A: The class who's internal data you want access to is the one that has to declare other classes as friends as it breaks standard encapsulation.
You cant have std::make_shared make your class a friend, and assuming you're not changing std::make_shared, it shouldn't want your class to be a friend.
So, unless I understand the question wrong - what you're asking can't be done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding a filtering constraint programmatically to a Dojo Enhanced Grid I added the filtering plugin to my Dojox Enhanced Grid. Now I would like to create my own constraint that filters the grid without user input. The normal grid.filter is deactivated if I use the filtering plugin.
Do subclasses like dojox.grid.enhanced.plugins.filter.BooleanExpr offer that functionality and what would the syntax for a simple filter (by ID for example) look like?
A: I had a similar problem and only managed to fix it by running the grid filter periodically in the background with the help of some jQuery. I believe this same method may work for what you're trying to do. Here is some sample code:
Add jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
Put this in the <head> of the page:
<script type="text/javascript">
$(document).ready(function() {
function filterTheDataGrid() {
if (dijit.byId("grid") != undefined) {
dijit.byId("grid").filter({color: "Red"});
}
}
// Run filterTheDataGrid every 1000 milliseconds //
// Lower 1000 for faster refreshing, maybe to 500 milliseconds //
var refreshDataGrid = setInterval(function() { filterTheDataGrid(); }, 1000);
}
</script>
and this:
<script type="text/javascript">
// Setup the layout for the data //
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
</script>
Put this in the <html> of the page:
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" query="{ type: '*' }" clientSort="true" rowsPerPage="40"></div>
and this:
<script type="text/javascript">
function addItemToGrid(formdata) {
// This function is called by a dialog box and gets form data passed to it //
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
}
</script>
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - dynamically using '.filter' on newly added DOM objects I'm using the jQuery template engine to add dynamic DOM elements (specifically DIVs). To control them I use the 'live' method (for 'click' events for example).
At some point I need to find some newly created elements using the 'filter' method. It seems that it won't find the newly created elements.
Any ideas why?
My code is comprised of such DIVs with different data-setid attributes. They are generated using jQuery .tmpl plugin.
I'm using the selector to find the appropriate "ListOfStuff" DIV and add append to him a new "Stuff" DIV.
So it will work on such DIVs generated on server and then served, but won't worked on newly created ones.
<div class="SomeStuffSet" data-setid="MySetID">
-- some stuff here --
<br /><br />
<div class="ListOfStuff">
<div class="Stuff">
My Name
</div>
<div class="Stuff">
My Name
</div>
<div class="Stuff">
My Name
</div>
</div>
</div>
and my selector is like this:
var setdiv = $('div').filter('.SomeStuffSet').filter(function () { return $(this).attr('data-setid') == $('#currentSetID').val(); }).children('.ListOfStuff');
A: I dont think you need a filter you could try this:
$("div.SomeStuffSet[data-setid='" + $("#currentSetID").val() + "'] > div.ListOfStuff");
In regards to your comment:
I believe that you are trying to do this
var setdiv = $("div.SomeStuffSet[data-setid='" + $("#currentSetID").val() + "'] > div.ListOfStuff");
//Code to append newly created object
//...
console.log(setdiv); // My assumption is that you believe setdiv should contain newly created object. This is not correct
//repopulate setdiv with newly create objects
setdiv = $("div.SomeStuffSet[data-setid='" + $("#currentSetID").val() + "'] > div.ListOfStuff");
console.log(setdiv) //now setdiv with contain newly created objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How many collections are possible in a MongoDB without losing performance? I saw that by default, a MongoDB has 24,000 collections available with a 16MB .ns file. If I increase that to 2GB (the max), can I then get 3,000,000 collections in a DB? Will there be any substantial performance decrease?
A: According to documentation large number of collections will not affect performance (almost not).
having a large number of collections has no significant performance
penalty, and results in very good performance
If you need more collection you can increase .ns file via --nssize parameter up to 2GB.
Documentation
A: I think thats the same as another DB... higher, it becomes more slower..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to edit my code to add (instead of replace) the content of a div to another div on toggle using jQuery Hello I have a jQuery example that a thepost-preview div is replaced with the full post. Because I am having some troubles with PHP, instead of replacing the two div, I need the full post to be added right after the post-preview.
In this case, the thepost div content will have the reamining characters of the post.
This is because I am having some issues with substr and strip_tags in PHP.
So my Fiddle is here http://fiddle.jshell.net/r4F8Q/34/ any help is appreciated.
A: try to use appendTo - http://api.jquery.com/appendTo/
A: $('#previewDiv').parent.append($(thePostDivFromPHP))
A: You can put the content on the page and use Html tags to define its structure (e.g. span, p, or div). Then find the pieces using jquery and use jQuery.html() to move the pieces around.
http://fiddle.jshell.net/r4F8Q/35/
var html = expanding
? $content.html()
: $content.find('.intro').html();
$display.html(html);
Or, you can just use jquery to control the visibility of the additional content.
http://fiddle.jshell.net/r4F8Q/37/
$('.toggle').click(function(e) {
var $this = $(this);
var $content = $this.siblings('.post-content').find('.additional');
var expanding = ($this.text() == '(expand)');
var html = expanding
? $content.show()
: $content.hide();
$this.text(expanding ? '(collapse)' : '(expand)')
e.preventDefault();
});
Or, if you really can't get your PHP to structure your content, you can stuff the intro into jQuery.data() and pull the content out of there when collapsing.
http://fiddle.jshell.net/r4F8Q/38/
$('.post-display').each(function() {
var $this = $(this);
$this.data('intro', $this.html());
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to do FTP tunnel over SSH I am writing a JAVA program for work that at some point needs to transfer files from the machine it is running on to another machine. The requirements are such that it can be configured to either do the transfer over FTP, SFTP, or a connection where the authentication is secure but data is transferred unencrypted.
Implementing the first two shouldn't be too bad with third party JAVA libraries. The issue I am having is with the third option. Seems like the only way to do that is by tunneling FTP over SSH.
As I am fairly inexperienced in this matter, wondering if anyone has any helpful suggestions. This can be done using either a reliable JAVA library (preferred) or some other tool that I just call as a separate process from within the program.
thanks
A: You can use Apache Commons VFS for file uploads and downloads. There is FTP and FTPS. The only prerequisite is that your remote system must run an FTP server. You do not have to call some external process. Just make your own application do the work. Remember to be careful with firewalls.
With FTPS only the control session is guaranteed to be encrypted. The data is transfered via regular FTP. Whether it is encrypted or not is up to you. You can use the PROT and CDC commands to control encryption.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to query from a Directed Acyclic Graph with exclusive subsets Question in abstract terms:
I have a directed acyclic graph (DAG) which contains subsets of vertices which are exclusive when queried (only one item per subset should be present in the query's results). When I query the graph structure I would like to get the set of vertices which flow from a given vertex while only selecting a single item from known subsets of the vertices in the graph.
Question in concrete terms:
I have a DAG that stores my assemblies(vertices) and their dependencies(edges). Given an assembly or set of assemblies I need to query to get the set of all involved assemblies and their dependencies. The difficult part is that each assembly has multiple versions and only one instance of an assembly can be loaded into a process. The dependencies for a given assembly change between the various versions of the assembly.
Is there a name for this problem or group of problems? A standard algorithm I can research to find a solution?
Possible solution areas:
A transitive closure seems close to a good solution but the item chosen from the subset (assembly version) will change depending on the path taken through the graph, possibly through multiple branches so you would almost need to trace the path taken through the graph to generate the transitive closure.
A graph database might be able to help out quite a bit but we want to avoid going down that road right now unless we absolutely have to.
A: I think that the set of vertices that flow from a given choice looks confusing because there is actually an underlying optimisation or satisfaction problem: given an assembly A, you can satisfy its dependencies via B1 or B2 or B3, and each of those choices then has its own knock-on consequences.
If we view this as a logic satisfaction problem, then we could consider a problem where assemblies come in only two versions, e.g. A1 or A2. Then a clause such as (a or b or not c) would translate to an upper-level assembly that required A1 or B1 or C2 - possibly indirectly via X1, X2 and X3 - and a conjunction of clauses would translate to an upper-upper level assembly that required all of the upper-level assemblies. So I think that if you could solve the general problem efficiently you could solve 3-SAT efficiently, and then P = NP.
Curiously, if you don't have the restriction that you are allowed only one assembly of each type (A1 or A2 or A3 but more than one at a time) then the problem translates very easily into Horn clauses (Knuth Vol 4 section 7.1.1 P 57) for which the satisfiability problem can be solved efficiently. To do this, you work with the inverse of the natural variables, so that X1 means that A1 is not included. Then if you treat the Horn clause version as a way of relaxing your problem, by ignoring the constraint that at most one version of each assembly can be supported, what you get is a mechanism for telling you that some assembly version A1 cannot be in the solution, because X1 = not A1 is true in the core of the Horn solution, and therefore true in every satisfying assignment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Rails db:migrate fails with SQL error rake db:migrate is failing on my production server, the error is:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'String' at line 1: 'ALTER TABLE looks' ADD 'code' String
My migration code is:
class AddCodeToLook < ActiveRecord::Migration
def self.up
add_column :looks, :code, :String #failing line
end
def self.down
remove_column :looks, :code
end
end
A: Try :string and not :String
A: Not sure if that's just a typo, but :String should be :string in your add_column line.
When you add a column like this, you can use the built-in rails generator to handle the grunt work:
rails g migration AddCodeToLook code:string
A: Per this official Rails documentation, it looks like the issue is that you're not using the right casing for the data type. You should be using :string.
class AddCodeToLook < ActiveRecord::Migration
def self.up
add_column :looks, :code, :string
end
def self.down
remove_column :looks, :code
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: The best way to send data to JavaScript functions from a Microsoft SQL Server Database I have a bunch of location data (longitude and latitude pairs) sitting in a Microsoft SQL Server DB.
I need to plot those points on a Map (OpenLayers+OSM), and the only way to draw on the map is to use JavaScript.
So far, I have no idea how to achieve this goal. The only thing I know is that I do not want to establish a database connection in JavaScript. In other words, I need to somehow use c# to pass the data from database to Javascript. Any suggestions? All help is appreciated!
A: Write a asp.net generic handler page that fetches the data from the database and outputs a json string.
Then with jQuery parse that output and plot.
A: You can make use of WebMethods and JQuery here.
Following blog post with an example should give you an idea how you can easily reach the server side code from client side :
http://tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSDictionary `description` formatting problem -- treats structure like char data I've got a custom class (which resembles an NSArray in concept and, hopefully, formatted appearance) which has a description formatter.
When the output of the formatter is printed (NSLog) by itself it looks fine, but when it's included as an element of an NSDictionary description the NSDictionary formatter seems to decide that it's a character string, not a structure definition, encloses it in quotes, and escapes all of the control characters in the string.
It doesn't do this for a standard NSArray, of course, so I'm wondering how it decides to treat the string one way vs the other.
Eg, rather than having output that looks like:
theChildren = (
{
"@meta.type" = "ns3:location";
"childNumber" = 0;
...
It looks like:
theChildren = "( \n\t\t {\n\t \"@meta.type\" = \"ns3:location\";\n\t \"childNumber\" = 0;
...
Can anyone suggest a way to alter this behavior?
FWIW, I accumulate the description string (with data consisting primarily of the results from calls to NSDictionary description) in an NSMutableString, then do NSString stringFromString at the exit (though I don't know that that does anything).
Added
I think I found the answer (haven't checked yet) buried in the NSDictionary writeup:
Discussion
The returned NSString object contains the string representations of
each of the dictionary’s entries. descriptionWithLocale:indent:
obtains the string representation of a given key or value as follows:
If the object is an NSString object, it is used as is.
If the object responds to descriptionWithLocale:indent:, that
method is invoked to obtain the object’s string representation.
If the object responds to descriptionWithLocale:, that method is
invoked to obtain the object’s string representation.
If none of the above conditions is met, the object’s string
representation is obtained by invoking its description method.
Update
Well, turns out they lie. I implemented descriptionWithLocale:indent: and it never gets called.
Update 9/23
Interestingly, if I make my class a subclass of NSArray then NSDictionary calls descriptionWithLocale:indent: and it formats correctly. Sounds like NSDictionary is "cheating" and testing isKindOfClass rather than respondsToSelector, or else is just prejudiced against non-NS stuff.
It's kind of ugly to have to subclass NSArray, though, in terms of acquiring a lot of behaviors I don't want to mimic, and carrying extra unused data.
Etc
Another option is to convert the escaped string back to its original. This takes a 31-line procedure to handle the basics (\n, \t, \", and \\). The up-side is that I don't need to subclass NSArray. The main downside is that this routine must be inserted in any NSLog call that could display my class. Another minor downside is that the escaped strings were wrappered with quote characters I can't eliminate, but that's hardly noticeable.
Got it #ifdefed for now -- not sure which I'll pick.
A: This is a wonderful security-related "feature" that was introduced in OS X 10.5+ version of syslog().
As explained by an Apple engineer in this post: Who broke NSLog on Leopard?,
That's the behavior of syslog(). From the man page:
Newlines and other non-printable characters embedded in the message
string are printed in an alternate format. This prevents someone from
using non-printable characters to construct misleading log
messages in an output file. Newlines are printed as "\n", tabs are printed as
"\t". Other control characters are printed using a caret ("^")
representation, for example "^M" for carriage return.
The ASL subsystem, which NSLog() writes to, does the same (at least in
Leopard). Writing the XML to a file is a reasonable alternative.
Chris Kane Cocoa Frameworks, Apple
See man syslog for more info.
A: There's no real answer to this question (the "security feature" of OS X doesn't appear to affect iOS console writes), but there are these two work-arounds:
#1: Interestingly, if I make my class a subclass of NSArray then NSDictionary calls descriptionWithLocale:indent: and it formats correctly. Sounds like NSDictionary is "cheating" and testing isKindOfClass rather than respondsToSelector, or else is just prejudiced against non-NS stuff.
It's kind of ugly to have to subclass NSArray, though, in terms of acquiring a lot of behaviors I don't want to mimic, and carrying extra unused data.
Etc
#2: Another option is to convert the escaped string back to its original. This takes a 31-line procedure to handle the basics (\n, \t, \", and \). The up-side is that I don't need to subclass NSArray. The main downside is that this routine must be inserted in any NSLog call that could display my class. Another minor downside is that the escaped strings were wrappered with quote characters I can't eliminate, but that's hardly noticeable.
(Accepted this answer, even though it's not the "real" answer, because my accepted % would suffer otherwise. I ask too many difficult questions, I guess.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Emacs symbol-at-point with C++ scope Has anyone extended symbol-at-point to include, in my use case the C++ namespace, scope as well?
Having the cursor on std::vector should preferably return ("std" "vector").
A: The CEDET toolset includes a set of local context parsers that will do what you want, but it doesn't extend symbol-at-point. Instead it has its own context parser. If you have a version of Emacs with CEDET pre-installed, just enabled semantic-mode, and then use the command semantic-analyze-current-context. It will return a class with the prefix. If you just want the raw prefix for a program, then you can instead use semantic-ctxt-current-symbol to return whatever is under point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: (Converting c# to Java JNA) - GetModuleFileName from hwnd I am trying to do exactly what is being done over here: How do I GetModuleFileName() if I only have a window handle (hWnd)?
But in java instead of C#.
So far I have managed to this:
public static final int PROCESS_QUERY_INFORMATION = 0x0400;
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
int GetWindowThreadProcessId(HWND hwnd, IntByReference pid);
};
public interface Kernel32 extends StdCallLibrary {
Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class);
public Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, int dwProcessId);
public int GetTickCount();
};
public interface psapi extends StdCallLibrary {
psapi INSTANCE = (psapi)Native.loadLibrary("psapi", psapi.class);
int GetModuleFileNameExA (Pointer process, Pointer hModule, byte[] lpString, int nMaxCount);
};
public static String getModuleFilename(HWND hwnd)
{
byte[] exePathname = new byte[512];
Pointer zero = new Pointer(0);
IntByReference pid = new IntByReference();
User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid);
System.out.println("PID is " + pid.getValue());
Pointer process = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_INFORMATION, false, pid.getValue());
int result = psapi.INSTANCE.GetModuleFileNameExA(process, zero, exePathname, 512);
String text = Native.toString(exePathname).substring(0, result);
return text;
}
The window handle that is given is valid, and the PID is always printed successfully. "Process" appears to return a value but the "result" is always zero. Could anyone knowledgeable about JNA kindly show me where my mistake is?
EDIT: Finally, SUCCESS! The problem was this line (where the first value had to be 1040):
Pointer process = Kernel32.INSTANCE.OpenProcess(1040, false, pid.getValue());
A: This may not be the reason it's failing, but I think the dwProcessId parameter should be an int, not IntByReference.
See MSDN (http://msdn.microsoft.com/en-us/library/ms684320(v=VS.85).aspx):
HANDLE WINAPI OpenProcess(
__in DWORD dwDesiredAccess,
__in BOOL bInheritHandle,
__in DWORD dwProcessId
);
It's just a regular DWORD.
Also, you can use GetLastError() to return more information about why the function call failed. Finally, this is a long shot, but your declaration of PROCESS_QUERY_INFORMATION is not included in the code snippet -- make sure it has the correct value (0x0400).
A: why all the hassle with the process id ??
quoting from the documention of GetModuleFilename():
hModule [in, optional]:
A handle to the loaded module whose path is being requested. If
this parameter is NULL, GetModuleFileName retrieves the path of the
executable file of the current process.
if you want the module fileName of the current process, just pass NULL as the process id.
if you want the module filename of another process, you need specific access rights before calling OpenProcess(). changing the access rights is described here, and is quite difficult to achieve (it requires a great amount of steps to lookup the privilege name, get the luid of the privilege, adjust the privileges of the token, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Windows Workflow Custom Sequence Activity I'm working with Windows Workflow 4, and I need to create a C# activity that, basically, inherits from the Sequence activity. I want it to look just like the Sequence activity, so a user can drag and drop other activities onto it from the designer. But, it acts differently in the code (maybe I want to run them in a different order, or do special actions between each one, it shouldn't matter).
How can I do this? I see a similar question was asked about this, and only one person responded with a suggestion that only applies to Windows Workflow 3. In version 4, a sequence activity can't be inherited from, to say the least.
This doesn't seem like a very far fetched concept. A Sequence activity is provided as a built in activity. So, it seems logical that it should be reproducible, or at least inheritable, so I can have a customized version of a Sequence activity.
Anyone have any ideas?
A: The "System.Activities.Core.Presentation.SequenceDesigner" designer is already available in WF 4. One can then compose a Sequence activity and use this designer for the outer class.
Here's a working example:
using System.Activities;
using System.Activities.Statements;
using System.Collections.ObjectModel;
using System.ComponentModel;
[Designer("System.Activities.Core.Presentation.SequenceDesigner, System.Activities.Core.Presentation")]
public class MySeq : NativeActivity
{
private Sequence innerSequence = new Sequence();
[Browsable(false)]
public Collection<Activity> Activities
{
get
{
return innerSequence.Activities;
}
}
[Browsable(false)]
public Collection<Variable> Variables
{
get
{
return innerSequence.Variables;
}
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.AddImplementationChild(innerSequence);
}
protected override void Execute(NativeActivityContext context)
{
context.ScheduleActivity(innerSequence);
}
}
This is forwarding the real behavior on to a private innerSequence, which might make this code seem useless, but note that in the Execute method it gives us a chance to do things before and after execution. If we want to provide customized behavior, we'd have to implement it instead of forwarding to an inner private activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Include 3rd party dll in the Sharepoint project while packaging the wsp In one of my projects I am using a 3rd party dll which is from Codeplex. While I was developing my code in my development box I had used gacutil command to get it added into GAC.
Now, I need to send the wsp for the project to teh Test Team for deployment on our Test box and they do not take individual dll.
How can I package the third party dll along with the wsp that I am sending so that it gets deployed into GAC and is used by the code.
Please let me know.
A: why are you locally using gacutil.exe?
To include external assemblies in your SharePoint project, for example lets take the Ninject.dll, you just add the assembly as reference to your project as you would do in any other CLR project.
To ensure that the Ninject.dll is included in your WSP you have to open the Package Configuration - just open the "Package" node in your SharePoint project and dbl. click the given entry. Scroll down to the end of the screen and open the advanced mode. There you can add an assembly for deployment. Just simply use the "Add Assembly -> Add Assembly from Project Output" Action and select Ninject.dll.
When packaging the next time your custom assembly will be included in your WSP.
Cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Email issue in hudson/Jenkins Some time I get failed notification email in jenkins even though build is passed? How to reslove this issue, I am using jenkins 1.430, using email ext 2.14
Thanks
A: Has issue in the plugin. Had to downgrade it for now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do you manage bdd features and scenarios? We are adopting BDD using specflow. The issue we have is that product owners and managers can not be expected to go into Visual studio / svn and edit features or scenarios.
We can get the pm's to do it all in google docs, and then we can copy and paste them into feature files, but this will be error prone and will get out of sync very quickly.
What is the best practice for managing this?
A: Product owners or business analysts should, in general, not be writing features on their own, as this can lead to poorly structured, untestable scenarios.
A common approach is known as 'the three amigos' - a business stakeholder, developer and tester working together to write scenarios.
It's fine to use Google Docs for the initial draft, but after that the features should be stored in version control, and the PO/BA should collaborate with a developer who has source control access on making changes.
You should make the version-controlled feature files easily accessible for review and reference to business stakeholders by linking to them from your intranet or wiki, or using a tool such as Relish.
A: What we have done in the company I work for is, most of the Business Analysts (which are the ones that write the stories) know how to use SVN, write the stories and even run the tests (in our case it's not Specflow but Cucumber). He is the one that talks with product owners/managers to write the new features/requirements as stories. In other words, delegate the task to someone (either a BA or a QA) who has some experience writing stories or scenarios and be able to run them and troubleshoot if something bad happens. Communication is the base of this. If you don't have this person, well... try to get it :)
A: Matt Wynne on Using Cucumber is a good read. Getting everyone talking ubiquitous language and having a single point of truth for the whole team.
Check out Pickles for outputting your features nicely https://github.com/x97mdr/pickles/wiki
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Best practices for dependent fields in a django model For database indexing purposes, the email field on a model needs to be stored in reverse. I end up needing access to both the reversed and forward version of the email field. I'm curious as to which of the following methods would be considered best practice.
Method A
Override the save method on the model. This method denormalizes the database some and doesn't work with the update method on a queryset. Some need to override forms generated for the model.
class Foo(models.Model):
email_forward = models.CharField(max_length = 320)
email_reversed = models.CharField(max_length = 320)
def save(self, *args, **kwargs):
self.email_reversed = reversed(self.email_forward)
super(Foo, self).save(*args, **kwargs)
Method B
This way has better database normalization. Still allows you to use the update method on querysets. Screws up forms so that you end up having to override all of the default forms generated for the model.
class Foo(models.Model):
_email = models.CharField(max_length = 320)
@property
def email_forward(self):
if not hasattr(self, 'email_f'):
self.email_f = reversed(self._email)
return self.email_f
@email.setter
def email_forward(self, value):
self.email_f = value
self._email = reversed(value)
@propery
def email_reversed(self):
return self._email
Clarification
Any alternative answers need to meet the minimum requirement of having the reversed email stored in the database. This question is however, not so much about finding an answer to this specific problem, but getting feedback on best practices for this sort of scenario where you have two fields which can be computed from one another, but one is required in a frontend context, and the other in a backend context
A: The Model:
class Foo(models.Model):
email = models.CharField(max_length=320)
def _get_email_reversed(self):
return self.email[::-1]
def _set_email_reversed(self, value):
self.email = value[::-1]
email_reversed=property(_get_email_reversed, _set_email_reversed)
And the Form:
class FooForm(forms.ModelForm):
class Meta:
model = Foo
Not sure what you meant by "Screws up the form", but this model form will only have one field - the email. I have also added an example of how the models are used:
def test_foo(self):
foo = Foo()
foo.email = 'moc.elpmaxe@liametset'
self.assertEquals(foo.email_reversed, 'testemail@example.com')
def test_set_foo_reversed(self):
foo = Foo()
foo.email_reversed = 'testemail@example.com'
self.assertEquals(foo.email, 'moc.elpmaxe@liametset')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: fb:visible-to-connection not working? Hi i have created new iFrame APP.
this is code part:
<fb:visible-to-connection>Welcome, fans!<fb:else>Become fan</fb:else></fb:visible-to-connection>
<script src="http://connect.facebook.net/en_US/all.js"></script>
Can anyone help me out??
I also tried doing this with newest Facebook PHP SDK. Unfortunately i can check it first i user accepted the APP, which is not the point in this case.
A: I am almost sure that is not working anymore.
To detect a like or non-liker you can use the signed request to get that data.
It gets passed to a tab when it is loaded.
<?php
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
?>
Then in the body of your HTML:
<?php
if ($data["page"]["liked"]!=1) {
echo('<div id="NON_LIKER_CONTENT"> <img src="nonliker.jpg" width="520"/></div>');
} else {
echo('<div id="LIKER_CONTENT"> <img src="liker.jpg" width="520"/></div>');
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Layout with fixed height and variable width JButtons I look for a LayoutManager that has fixed height JButtons that expand in width to fit the size of their Container. Above the JButtons there should be a JLabel by itself on the line that says "Choose file:". This is intended to work as an accessory to a JFileChooser that lets the user choose recent files. I haven't been able to make it look quite right, I've tried using multiple JPanels and LayoutManagers such as BoxLayout. When using BoxLayout the JButtons only expand as far as they have to to contain their text; but I would like for all of the JButtons to be the same width so they don't look funny.
Note: I've also used other LayoutManagers such as Border and GridLayout but those mostly ignore my size settings and aren't sophisticated enough it would seem. I have to do this by hand, Netbeans etc are not an option.
Working example, but visually incorrect
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Chooser extends JPanel {
public Chooser(){
this.setLayout(new GridLayout(0,1));
JPanel labelPanel = new JPanel();
JLabel label = new JLabel("Choose a file:");
labelPanel.add(label);
labelPanel.setBackground(Color.red);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("long pathname to a file goes here"));
buttonPanel.setBackground(Color.blue);
this.add(labelPanel);
this.add(buttonPanel);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Chooser c = new Chooser();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAccessory(c);
fileChooser.showOpenDialog(null);
}
}
A: What about something where a GridLayout is nested in a BorderLayout (actually in a JScrollPane)...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Chooser extends JPanel {
private static final String[] BUTTON_TEXTS = { "Hello", "Goodbye",
"Hello Goodbye", "Adios", "This is a long String for WTF" };
public Chooser() {
this.setLayout(new BorderLayout());
JPanel labelPanel = new JPanel();
JLabel label = new JLabel("Choose a file:");
labelPanel.add(label);
labelPanel.setBackground(Color.red);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < BUTTON_TEXTS.length; i++) {
buttonPanel.add(new JButton(BUTTON_TEXTS[i]));
}
buttonPanel.add(Box.createVerticalGlue()); // to pad the bottom if needed
buttonPanel.setBackground(Color.blue);
this.add(labelPanel, BorderLayout.PAGE_START);
this.add(new JScrollPane(buttonPanel), BorderLayout.CENTER);
}
public static void main(String[] args) {
Chooser c = new Chooser();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAccessory(c);
fileChooser.showOpenDialog(null);
}
}
Example 2 with a simple JList that places its selection in the file chooser:
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Chooser extends JPanel {
private static final String[] BUTTON_TEXTS = { "Hello", "Goodbye",
"Hello Goodbye", "Adios", "This is a long String for WTF", "Hello",
"Goodbye", "Hello Goodbye", "Adios", "This is a long String for WTF" };
public Chooser(final JFileChooser fileChooser) {
setLayout(new BorderLayout());
JPanel labelPanel = new JPanel();
JLabel label = new JLabel("Choose a file:");
labelPanel.add(label);
labelPanel.setBackground(Color.red);
final JList list = new JList(BUTTON_TEXTS);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedString = list.getSelectedValue().toString();
fileChooser.setSelectedFile(new File(selectedString));
}
});
add(labelPanel, BorderLayout.PAGE_START);
add(new JScrollPane(list), BorderLayout.CENTER);
}
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser();
Chooser c = new Chooser(fileChooser);
fileChooser.setAccessory(c);
fileChooser.showOpenDialog(null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot cast java.lang.Float to float when using Class.cast? I already have a solution, but I don't like it. Also, it would be nice to know your thoughts about this.
You see, elem.get gives back an Object, that is going to be a Float in the case of x and y.
This code throws the Exception described in the title:
String names[] = { "x", "y", "src" };
Class types[] = { float.class, float.class, String.class };
for (int i = 0; i < names.length; i++)
{
if (elem.containsKey(names[i]))
{
par.add(types[i]);
arg.add(types[i].cast(elem.get(names[i])));
}
}
The code is used to define the list of parameters to instantiate an object. Both the parameters and the object's class name are defined in an external data file (but nevermind about that).
The solution, something I'm not fond of (because it loses the flexibility I was trying to attain), has this within the for:
if(types[i] == float.class)
{
float v = (Float)elem.get(names[i]);
arg.add(v);
} else
{
arg.add(types[i].cast(elem.get(names[i])));
break;
}
Other option would be changing float.class to Float.class in types, but I won't do that because that code is used to instantiate objects which have float parameters in their constructors.
Thanks!
A: As the type of args is an ArrayList<Object>, you're not avoiding the boxing anyway:
// This code...
float v = (Float)elem.get(names[i]);
arg.add(v);
// Will actually be equivalent to:
float v = (Float)elem.get(names[i]);
Float boxed = v;
arg.add(boxed);
If the point is to call a constructor by reflection, then you're going to have to pass in a Float for any float parameters - that's just how it works.
So basically, change float.class to Float.class and it should all work fine. EDIT: Ah, except then the par list will have the wrong type. Basically you want to cast with Float.class, but add float.class to the list of parameter types.
You probably want a map from primitive types to wrapper types, like this:
private static final Map<Class<?>>, Class<?>> PRIMITIVE_TYPE_MAP =
buildPrimitiveTypeMap();
private static Map<Class<?>>, Class<?>> buildPrimitiveTypeMap()
{
Map<Class<?>>, Class<?>> map = new HashMap<Class<?>>, Class<?>>();
map.put(float.class, Float.class);
map.put(double.class, Double.class);
// etc
return map;
}
Then:
String names[] = { "x", "y", "src" };
Class types[] = { float.class, float.class, String.class };
for (int i = 0; i < names.length; i++)
{
if (elem.containsKey(names[i]))
{
par.add(types[i]);
// For primitive types, only box to the wrapper type
Class<?> castType = PRIMITIVE_TYPE_MAP.get(types[i]);
if (castType == null)
{
castType = types[i];
}
arg.add(castType.cast(elem.get(names[i])));
}
}
In fact, if you trust that the values are of the right type already, I suspect you can just do:
arg.add(elem.get(names[i]));
After all, you're just casting to a particular type and then losing that type information again... using the cast call does perform a check that the execution-time types are correct though, so you may want to keep it for that reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Uncaught TypeError: Cannot set innerHTML to null Can somebody tell why I get this innerHTML error in the following code?
<html>
<head>
<title>
My Todo List
</title>
</head>
<script type="text/javascript">
var html5rocks = {};
html5rocks.webdb = {};
html5rocks.webdb.db = null;
html5rocks.webdb.open = function() {
var dbSize = 5 * 1024 * 1024; // 5MB
html5rocks.webdb.db = openDatabase('Todo', '1.0', 'todo manager', dbSize);
}
html5rocks.webdb.onError = function(tx, e) {
alert('Something unexpected happened: ' + e.message );
}
html5rocks.webdb.onSuccess = function(tx, r) {
// re-render all the data
// loadTodoItems is defined in Step 4a
html5rocks.webdb.getAllTodoItems(loadTodoItems);
}
html5rocks.webdb.createTable = function() {
html5rocks.webdb.db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS ' +
'todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)', []);
});
}
html5rocks.webdb.addTodo = function(todoText) {
html5rocks.webdb.db.transaction(function(tx){
var addedOn = new Date();
tx.executeSql('INSERT INTO todo(todo, added_on) VALUES (?,?)',
[todoText, addedOn],
html5rocks.webdb.onSuccess,
html5rocks.webdb.onError);
});
}
html5rocks.webdb.getAllTodoItems = function(renderFunc) {
html5rocks.webdb.db.transaction(function(tx) {
tx.executeSql('SELECT * FROM todo', [], renderFunc,
html5rocks.webdb.onError);
});
}
function loadTodoItems(tx, rs) {
var rowOutput = "";
for (var i=0; i < rs.rows.length; i++) {
rowOutput += renderTodo(rs.rows.item(i));
}
var todoItems = document.getElementById('todoItems');
todoItems.innerHTML = rowOutput;
}
function renderTodo(row) {
return '<li>' + row.ID +
'[<a onclick="html5rocks.webdb.deleteTodo(' + row.ID + ');">X</a>]</li>';
}
html5rocks.webdb.deleteTodo = function(id) {
html5rocks.webdb.db.transaction(function(tx) {
tx.executeSql('DELETE FROM todo WHERE ID=?', [id],
html5rocks.webdb.onSuccess, html5rocks.webdb.onError);
});
}
function addTodo() {
var todo = document.getElementById('todo');
html5rocks.webdb.addTodo(todo.value);
todo.value = '';
}
function init() {
html5rocks.webdb.open();
html5rocks.webdb.createTable();
html5rocks.webdb.getAllTodoItems(loadTodoItems);
}
</script>
</head>
<body onload="init()">
</body>
I'm following this tutorial: http://www.html5rocks.com/en/tutorials/webdatabase/todo/
A: What happens if you add the todoItems element in the body along with the form from the article?
<body onload="init()">
<ul id="todoItems"></ul>
<form type="post" onsubmit="addTodo(); return false;">
<input type="text" id="todo" name="todo" placeholder="What do you need to do?" style="width: 200px;">
<input type="submit" value="Add Todo Item">
</form>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Declarative syntax, how do I define a relationship representing the latest object in a many-to-one collection? I'm using SQLAlchemy's declarative syntax and I'd like to specify a relationship that provides the latest (max primary id) element in a collection. I've found this post: How do I define a SQLAlchemy relation representing the latest object in a collection? but I'm having a tough time using this pattern, creating a subquery using Declarative only. Any pointers or help would be greatly appreciated!
General Idea:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(bind=engine, metadata=metadata)
from sqlalchemy import *
from sqlalchemy.orm import *
class NewsPaper(Base):
__tablename__ = "newspapers"
id = Column(Integer, nullable=False, primary_key=True)
name = Column(String(255))
latest_article = relationship("Article",
primaryjoin="(Article.newspaper_id==NewsPaper.id) &"
"(Article.id==SUBQUERY_FOR_LATEST_ID)")
def __repr__(self):
return '''<name={0}>'''.format(self.name)
class Article(Base):
__tablename__ = "articles"
id = Column(Integer, nullable=False, primary_key=True)
title = Column(String(255))
newspaper_id = Column(Integer, ForeignKey('newspapers.id'))
newspaper = relationship("NewsPaper", backref=backref('articles') )
def __repr__(self):
return '''<title={0}>'''.format(self.title)
A: The easiest way is to define the relationship outside the class once all classes are defined.
Remove your definition of latest_article from NewsPaper and add following code after the class Article definition (taken directly from Mike's answer you linked to):
# define the relationship
t_article = Article.__table__
t_newpaper = NewsPaper.__table__
latest_c = (select([t_article.c.id]).
where(t_article.c.newspaper_id == t_newpaper.c.id).
order_by(t_article.c.id.desc()).
limit(1).
correlate(t_newpaper).
as_scalar()
)
NewsPaper.latest_article = relationship("Article",
primaryjoin=and_(
t_article.c.id==latest_c,
t_article.c.newspaper_id==t_newpaper.c.id,
),
uselist=False
)
One note though: the relationship is working directly on the database, and as such it will not include those Article instances which are not yet commited but are part of the session. And most probably they would be the ones that you really want. So just be careful with that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to open a new default browser window in Python when the default is Chrome I have been looking for a way to open a new default browser window from inside Python code.
According to the documentation webbrowser.open_new(url)
Should do that. Unfortunately in case Chrome is the default browser it only opens a new tab.
Is there any way to open the default browser (without knowing what that browser is)?
A: Give this a whirl:
import subprocess
command = "cmd /c start chrome http://www.ebay.com --new-window"
subprocess.Popen(command, shell=True)
A: I have a feeling it's not Python's fault. Firefox and Chrome (and probably IE) all intercept calls to open new windows and changes them to new tabs. Check the settings in your browser for interpreting those calls.
A: import subprocess
def open(url):
cmd = "open " + url
print(cmd)
subprocess.Popen(cmd, shell=True)
A: webbrowser.open('http://www.google.com', new=1)
or
webbrowser.open_new('http://www.google.com')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: events called from inside another function jQuery with underscore template doesn't work I have a function which i used to add elements to a list, I want to have events run on interaction with this list, e.g. click. If I do it using the document object it works well however if I use jQuery with underscore templates the element is successfully appended but the events will not trigger.
var addElement = function(parentElement){
//would work
this.thisElement = document.createElement('li');
parentElement.appendChild(thisElement);
$(this.thisElement).click(function(event){
alert('working');
});
//doensn't work
this.template = _.template($('#fileListEntity').html());
var li = this.template();
$(parentElement).append(li);
$(li).click(function(e) {
alert('notWorking');
});
};
A: are you shore that template() returns a element. if it returns a string (witch most template system do) that click event wont work.
also there's syntactic errors with not closing the click method.
A: so with the help of megakorre this is the answer.
this.template = _.template($('#fileListEntity').html());
var li = $(this.template({name:doc.name}));
$(parentElement).append(li);
li.click(function(e) {
alert('click');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make Gridview read ConnectionString from Session? How can get my SQLDataSource to read the ConnectionString from a session variable?
I know I can do it in code, like this:
protected void Page_Load(object sender, EventArgs e)
{
uxDS.ConnectionString = Session["con"].ToString();
}
But what I really want is something like this?
<asp:SqlDataSource ID="uxDS" ... ConnectionString='<% Session["con"] %>' />
I could have sworn I saw it done somewhere but I can't seem to find it.
A: Have you tried this?
<asp:SqlDataSource ID="uxDS" ... ConnectionString='<%# Session["con"] %>' />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to handle different account types in PHP? I have a 3 tables/models with the relationship illustrated below:
Account
|
----------
| |
User Company
They are all joined by the the Account's PRIMARY KEY, and the User and Company each have very different sets of methods and fields.
Assuming that I only know the "account id", and I need to load an account, I am assuming that the following is a good procedure?
*
*the Account model is loaded by id
*the "account type" is then determined
*either a User or a Company object is loaded into the Account object itself. It could be used like so:
$account->company->company_name();
Somehow this doesn't seem very efficient...can somebody suggest something better?
A: Probably best to have both User and Company extend Account, and with the parent class Account not knowing about the children classes (only the child classes should know about the parent class) so when you need to add more Account subclasses, you don't need to change anything in Account:
class Account {
var $email;
var $password;
function load() {
// load from db
}
}
class User extends Account {
var $first_name;
var $last_name;
function load() {
parent::load();
// load for this class
}
}
class Company extends Account {
var $company_name;
function load() {
parent::load();
// load for this class
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unrecognized selector sent to instance (SIG_ABRT), adding NSString to NSArray I'm brainfarting here. So I have a method that looks through a NSMutableArray that is a property of another class. The objects are NSString. In the debugger I see it says NSCFString for the object I'm trying to add to an array. So I basically do this:
- (NSArray *)GetFileNames {
NSMutableArray *fileNameArray = [[[NSArray alloc] init] autorelease];
for (NSString *str in self.ParentVC.SelectedOptions) {
[fileNameArray addObject:str];
NSLog(@"%@", str); // this works fine
}
return fileNameArray;
}
And I call this function somewhere else by:
NSArray *fileNameArray = [[NSArray alloc] initWithArray:[self GetFileNames]];
But for some reason, I get the unrecognized selector sent to instance and it stops on this line. Am I doing something wrong? Any tips to try to troubleshoot the problem? I already checked the self.ParentVC.SelectedOptions and that shows my NSCFString or NSCFStrings I want. Anything I can do in Instruments for this? Thanks.
A: Replace the second line with
NSMutableArray *fileNameArray = [[[NSMutableArray alloc] init] autorelease];
The real type of the object is what you allocate, not what you declare. In the posted code, the array is not mutable.
A: This line:
NSMutableArray *fileNameArray = [[[NSArray alloc] init] autorelease];
Should be
NSMutableArray *fileNameArray = [[[NSMutableArray alloc] init] autorelease];
Otherwise you're creating an immutable array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java ServerSocket required for UDP communication? I had following question on the exam:
"Let us assume that you want to use UDP for a client. Do you need to create a new socket for managing parallel connections in UDP? Why or why not? What happens if multiple clients connect to that socket?"
The question also referenced a Java class TCPServer.java, which creates ServerSocket and later on in a while(true) loop, it accepts connections and creates Sockets for incoming connection requests from users.
To my mind, TCP Server is only used for TCP connections, so it is not possible to use the same server side code for UDP client.
A: You're on the right track.
ServerSockets are used for TCP connections. DatagramSockets (which are still connectionless) are used for UDP.
And to answer the other part, that is, "What happens if multiple clients connect to that socket?" the answer is:
*
*if it's UDP, then it's fine, because it's connectionless
*if it's TCP, then the ServerSocket should see the connection request, and create a new Socket for two-way communication with that client
To answer the "Why or why not" - UDP is connectionless, and therefore a new Socket isn't used for communication. UDP just receives a DatagramPacket, and either drops it (if the app determines that it's invalid, malformed, etc.), or it replies with a DatagramPacket. In UDP there's no connection, no connection state, and no input/output streams.
A: The question asked you to explain why OR why not. So in essence if you didn't believe that the ServerSocket code would work for UDP then you had to say why. From your last sentence I believe you know the answer to the question, now you just have to write it down with confidence.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generic JQuery Function? I'm using Jeditable to edit dozens of fields such as first_name, last_name, birthday, etc.
My problem is that I'm drowning in detail: I keep having to create a new selector such as $('#edit_first_name').editable or $('#edit_birthday').editable to making the field editable as well as create a bunch of SQL commands specific to each field to insert them once they're edited.
My question is: Is there a way I can create something generic or OO in JQuery so that I don't don't have to endlessly create code that essentially does the same thing?
My guess is I can create some "generic" function that will create $('#edit_someField').editable on the fly by feeding some JSON array, which was created by doing a SELECT on all field names I'm interested in. I imagine that's exactly what JQuery plugins do.
Any direction on how I can accomplish this would be much appreciated.
EDIT
One solution I have come up with is to put the table, column name and id in the id value of whatever I want to edit.
For example, if I want to edit the first_name of id=6 on table Person, then in the id I will put <span class="editable" id="Person:first_name:6">myFirstName</span>. When I send the id to my save.php file, I use a preg_split to insert my data into the table.
A: Mark all your editable input fields with the class "editable". (Change to suit.)
$('.editable').each(function() {
$(this).editable('mysaveurl.php');
});
That's all you need for the basic functionality. Obvious improvements can be made, depending on what else you need. For example, if you are using tooltips, stick them in the title attribute in your HTML, and use them when you call editable().
Your actual PHP/Ruby/whatever code on the server is just going to look at the id parameter coming in, and use that to save to the appropriate field in the database.
A: Just use a class to make them all editable, and using their id (or a attribute that you have attached to the tag) you can specify the field you are updating.
Then just pass the field and the value to your DB.
i don't know the plugin you are using
but, assuming it has some sort of event handling in it...
something like this maybe?
$(".editable").editable({
complete : function() {
var _what = $(this).attr("id");
var _with = $(this).val();
$.post("yourPostPage.php",{what:_what, where:_where});
}
});
Without knowing more about your environment I wouldn't be able to help further.
A: The jQuery way of assigning some common code to a bunch of objects is to either give all the objects the same class so you can just do this:
$(".myEditableFields").editable("enable");
This will call the editable add-on method for all objects in your page with class="myEditableFields".
If you just have a list of IDs, you can just put them all in the single selector like this and they will each get called for the editable jQuery method:
$("#edit_first_name, #edit_birthday, #edit_last_name, #edit_address").editable("enable");
Sometimes, the easy way it to create a select that just identifies all editable fields within a parent div:
$("#editForm input").editable("enable");
This would automatically get all input tags inside the container div with id=editForm.
You can of course, collect common code into your own function in a traditional procedural programming pattern and just call that when needed like this:
function initEditables(sel) {
$(sel).editable("enable");
// any other initialization code you want here or event handlers you want to assign
}
And, then just call it like this as needed:
initEditables("#edit_first_name");
To help further, we would need to know more about what you're trying to do in your code and what your HTML looks like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can we connect iPad2 and iTouch using Gamekit? I have this doubt, can we connect iPad2 and iTouch using Gamekit ? I tried Apples GKTank example along with several others available tutorials regarding the same. But I did not have successful connection between them. Anyone knows why this happened ?
A: Yes you can. There should be no difference between connecting an iPad to an iPod or an iPhone to an iPhone. Are you making sure that both devices have bluetooth turned on or both are on the same wi-fi network?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I know where this instance is deallocated? I got [NSArrayM release] message sent to deallocated instance error. However, the debugger hightlight a line in main source (retval line) instead of the line where this error actually happened. Any idea how to find this bug and fix it ?
Thx for helping,
Stephane
A: You can set conditional breakpoint when an exception occurs - that way debugger will stop exactly in the place of an error.
*
*To do that go to the breakpoints tab in Navigator section (leftmost xcode section).
*Click '+' at the bottom to "Add Exception Breakpoint"
*Add breakpoint (you can choose to catch only objective-c exceptions if you want)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Round array to nearest hundredth and seperate evenly I am pulling 10 integers from a MySQL DB:
I want to be able to determine the largest value then round up to the nearest hundredth. With this I want to then be able to create a list of 10 numbers that are evenly separated down to zero.
In Example :
{ 232, 10, 0, 55, 130, 423, 102, 22, 98, 3 }
Take : 423 => Round up to 500
Then with the number 500 come back with equally separated numbers such as :
500 , 450 , 400, 350, 300, 250, 200, 150, 100, 50, 0
Thank you for the help in advance!
Chris
A: $maximal = max($array);
function roundNearestHundredUp($number)
{
return ceil( $number / 100 ) * 100;
}
$counting = roundNearestHundredUp($maximal);
while($counting >= 0){
echo $counting;
$counting -= 10;
}
A: This should do it:
<?php
$array = array(232, 10, 0, 55, 130, 423, 102, 22, 98, 3);
$max = max($array);
$max_rounded = ceil($max/100)*100;
$diff = ($max_rounded/10);
while($max_rounded >= 0){
echo $max_rounded.' ';
$max_rounded -= $diff;
}
?>
A: You can get the maximum number of your results set by using MySQL's MAX() function. No sense in returning results you don't need:
SELECT MAX(your_column) FROM some_table;
Then use PHP to do the math on the number:
function getChoices($start, $count)
{
$start = ceil($start / 100) * 100;
return range($start, 0, ($start / $count));
}
$choices = getChoices(460, 10);
If you don't want to use MySQL's MAX(): $choices = getChoices(max($results), 10);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: domain class field not being displayed on view page I am unable to view all of the below fields when I run my grails app the " Cost" field is not being displayed on the view page, the fields are displayed on the add page. If I remove the "name" field the "cost" field is then displayed. Is there a field limit that im not aware of ?
package racetrack
class Race {
String name
Date startDate
String city
String state
BigDecimal distance
BigDecimal cost
Integer maxRunners = 100000
static constraints = {
name()
startDate()
city()
state()
distance()
cost()
maxRunners()
}
}
List.gsp -
<%@ page import="racetrack.Race" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'race.label', default: 'Race')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>
</head>
<body>
<div class="nav">
<span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span>
<span class="menuButton"><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></span>
</div>
<div class="body">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<div class="list">
<table>
<thead>
<tr>
<g:sortableColumn property="id" title="${message(code: 'race.id.label', default: 'Id')}" />
<g:sortableColumn property="name" title="${message(code: 'race.name.label', default: 'Name')}" />
<g:sortableColumn property="startDate" title="${message(code: 'race.startDate.label', default: 'Start Date')}" />
<g:sortableColumn property="city" title="${message(code: 'race.city.label', default: 'City')}" />
<g:sortableColumn property="state" title="${message(code: 'race.state.label', default: 'State')}" />
<g:sortableColumn property="distance" title="${message(code: 'race.distance.label', default: 'Distance')}" />
</tr>
</thead>
<tbody>
<g:each in="${raceInstanceList}" status="i" var="raceInstance">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td><g:link action="show" id="${raceInstance.id}">${fieldValue(bean: raceInstance, field: "id")}</g:link></td>
<td>${fieldValue(bean: raceInstance, field: "name")}</td>
<td><g:formatDate date="${raceInstance.startDate}" /></td>
<td>${fieldValue(bean: raceInstance, field: "city")}</td>
<td>${fieldValue(bean: raceInstance, field: "state")}</td>
<td>${fieldValue(bean: raceInstance, field: "distance")}</td>
</tr>
</g:each>
</tbody>
</table>
</div>
<div class="paginateButtons">
<g:paginate total="${raceInstanceTotal}" />
</div>
</div>
</body>
</html>
A: Assuming you're referring to the scaffolded list view, the scaffolding only renders six fields.
The basic logic (from src/templates/scaffolding/list.gsp) is:
props.eachWithIndex { p, i ->
if(i == 0 {
// render the field as a link to the show view
} else if(i < 6) {
// render the field value
}
}
Note that the list of properties includes the id. Since you define six fields in your constraints, the last one's not being displayed (only the id + first five are).
Edit
To "fix" this, you have some options:
*
*Update the scaffolded list view code:
*
*First, run grails install-templates
*Open up src/templates/scaffolding/list.gsp
*Find the code segment above and change the condition
Note that this will change the rendering for all scaffolded and generated list views.
*Generate the view and update it manually.
It looks like you've already generated the view, so you'll just need to update it. Note that if you generate it again, it will overwrite your changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I render @font-face in PhantomJS screen capture? The screen capture is great, but the custom @font-face fonts aren't being rendered. Is it possible to correct this?
A: After doing some research for a bit I found this
http://code.google.com/p/phantomjs/issues/detail?id=247
Looks like SVG works the best.
One problem I ran into while testing a screenshot again after using an SVG version of the font was WebKit caching the old page and still showing the broken fonts. Make sure your server explicitly tells it to not use a cached version, or clean WebKits cache.
A: I've build PhantomJS with Webfonts support for OSX and Linux - You can use the binaries directly -
Download From: http://arunoda.me/blog/phantomjs-webfonts-build.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: On the surface, JPA Criteria Queries are a huge step back from Hibernate Criteria Queries. Is this really the case? How could such a colossal step back be justified!?! Am I missing something? The readability of the entity manager version is just awful.
session().createCriteria(Entity.class).add(Restrictions.eq("id"), id).uniqueResult();
versus
EntityManager em = getEntityManager();
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
Metamodel m = em.getMetamodel();
EntityType<Transaction> Transaction_ = m.entity(Transaction.class);
Root<Transaction> transaction = cq.from(Transaction.class);
// Error here. cannot find symbol. symbol: variable creationDate
cq.where(cb.between(transaction.get(Transaction_.creationDate), startDate, endDate));
// I also tried this:
// cq.where(cb.between(Transaction_.getDeclaredSingularAttribute("creationDate"), startDate, endDate));
List<Transaction> result = em.createQuery(cq).getResultList();
return result;
} finally {
em.close();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I sum an entire field(no grouping)? I have a field called time_elapsed that stores a sql TIME value, a start_date and end_date that are sql DATETIMES, a unique id and a batch_id that is a reference to the batches table. I'm looking to SUM the total of the time_elapsed field for every record in a date range, in the case of the example it is august first until now. If I join the batches table and group by operation_id it gives me the info that I need for individual operation_ids but not for every record combined.
select sum(TIME_TO_SEC(time_elapsed)) from batch_log
where batch_log.start_time between DATE("08-01-2011") and DATE(NOW()) and time_elapsed is not null
A: You possibly just aren't matching any rows with your WHERE clause. Try doing a count(*) instead of a sum to check.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Trying to do a SQL query without using a cursor So I've got a database which maintains all of the data in it in a history database, so that we can change the history date, and go back and look at old data. I need to write a query that adjusts the dates in these history tables for each table. Right now I've got it working as a cursor, but it takes several minutes to run, and I want to see if I can do it without a cursor.
Edit: To be clear, the primary keys that I'm pulling are the primary keys for the non-history tables. The history tables may have multiple entries for the single primary key. (Which is why the inner sql is doing the join that it is)
Here's the cursor:
DECLARE tableID CURSOR FOR
SELECT
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
and COL_NAME(ic.OBJECT_ID, ic.column_id) != 'RecordID'
DECLARE @currentTable varchar(100)
DECLARE @currentID varchar(100)
DECLARE @currSql varchar(max)
OPEN tableID
FETCH FROM tableID
INTO @currentTable, @currentID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @currSql =
'update t1
set t1.EndDate = t2.BeginDate
from hist.' + @currentTable + ' t1 inner join hist.' + @currentTable + ' t2
on t1.' + @currentID + ' = t2.' + @currentID + '
and t2.BeginDate = (select MIN(BeginDate) from hist.' + @currentTable + ' t
where t.BeginDate >= t1.EndDate and t.' + @currentID + ' = t1.' + @currentID + ')'
EXEC(@currSql)
FETCH FROM tableID
INTO @currentTable, @currentID
END
CLOSE tableID
DEALLOCATE tableID
A: I find it very hard to believe that this runs slowly because it's a cursor. You can make the cursor slightly more efficient by saying:
DECLARE CURSOR tableID LOCAL STATIC READ_ONLY FORWARD_ONLY FOR ...
...but I bet if you just print all those SQL commands, copy and paste them into a new window, and execute them manually, that it will still take a lot longer than you'd like. The speed is probably related to the amount of data you're updating (or at least scanning), not because you're using a cursor to generate the commands.
You can generate these commands without explicitly using a cursor, but rather using the metadata tables to build a string, but this will still really use a cursor in the engine... the code is just a lot tidier. I'll post an example shortly.
First, just adding a sample of what the output of your query currently looks like, for say the id column on table1. To help illustrate my comment and how it might be very hard for this update to ever affect any rows:
update t1
set t1.EndDate = t2.BeginDate
from hist.table1 t1
inner join hist.table1 t2
on t1.id = t2.id
and t2.BeginDate = (select MIN(BeginDate) from hist.table1 t
where t.BeginDate >= t1.EndDate and t.id = t1.id);
Perhaps you meant a much simpler query, like:
update hist.table1
set EndDate = BeginDate
where BeginDate >= EndDate;
Or perhaps you meant to reference some other table in the subquery?
Anyway assuming one of the above queries is really what you intend to execute, to generate the first query you could try:
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += CHAR(13) + CHAR(10)
+ N'update t1
set t1.EndDate = t2.BeginDate
from hist.' + QUOTENAME(t.name) + ' AS t1
inner join hist.' + QUOTENAME(t.name) + ' AS t2
on t1.' + QUOTENAME(c.name) + ' = t2.' + QUOTENAME(c.name)
+ 'and t2.BeginDate = (select MIN(BeginDate) from hist.'
+ QUOTENAME(t.name) + ' AS t where t.BeginDate > t1.EndDate and
t.' + QUOTENAME(c.name) + ' = t1.' + QUOTENAME(c.name) + ');'
FROM sys.tables AS t
INNER JOIN sys.indexes AS i
ON t.[object_id] = i.[object_id]
AND i.is_primary_key = 1
INNER JOIN sys.index_columns AS ic
ON t.[object_id] = ic.[object_id]
INNER JOIN sys.columns AS c
ON c.column_id = ic.column_id
AND c.[object_id] = ic.[object_id]
WHERE c.name <> 'RecordID'
AND t.[schema_id] = SCHEMA_ID('hist');
PRINT @sql;
-- EXEC sp_executesql @sql;
And for the second it is a lot simpler:
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += CHAR(13) + CHAR(10)
+ N'UPDATE hist.' + QUOTENAME(t.name)
+ ' SET EndDate = BeginDate
WHERE BeginDate > EndDate;'
FROM sys.tables AS t
WHERE t.schema_id = SCHEMA_ID('hist');
PRINT @sql;
-- EXEC sp_executesql @sql;
Note that I changed the >= to > since if it's already = there's no reason to update. And again, these assume that everything is in the hist schema and all primary keys are single column primary keys. Though I will state again that the first, longer version of the query is much more expensive (two extra clustered index seeks and a very expensive table spool operator) - while not achieving results that are any different, whatsoever, from the shorter version I posted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS 4-way rocker control I need to do some 2-axis adjustment on a web page.
Can anyone point me at the CSS/Javascript for a 4-way rocker switch like the ones on TV remotes?
Thanks!
A: Didn't find anything in my searches of the web, and nobody here had a suggestion, so I wrote one.
Live demo: Resizable 4-Way Rocker Control Widget
See the code: on JSFiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring InitBinder I'm having some trouble setting up an initBinder in Spring MVC. I have a ModelAttribute which has a field which will sometimes display.
public class Model {
private String strVal;
private int intVal;
private boolean boolVal; // Only shows in certain situations
}
How can I setup this initBinder properly? Here is what I have, but whenever I modify the post data I'm able to modify this boolVal regardless of me saying it's not allowed. I'm assuming my trouble is that I can't take the shortcut I'd like to.
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setIgnoreUnknownFields(true);
if (binder.objectName() == MODEL) {
binder.setAllowedFields("*");
if (!somePermissionChecks()) {
binder.setDisallowedFields("boolVal");
}
}
}
The permission check is returning false, thus the call to setDisallowedFields is made. The problem is that I'm still able to fake this value on the UI by adding an input or changing the name of another field or appending it to the POST data.
Is there a quick way to do this, without having to list all the properties by hand?
A: Is the permission check failing during the initialization of the binder? Have you tried without the binder.setAllowedFields("*"); statement?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unruly CSS Pseudo Element Box Shadow I am working on a new layout for a website, and I am extremely close to achieving the result I want. However, there is one problem. I am using an adaptation of the technique described here (http://nicolasgallagher.com/multiple-backgrounds-and-borders-with-css2/demo/backgrounds.html, see the 3 column example just below the gorillas). Basically, my version uses an absolutely positioned CSS pseudo element as the backgrounds for the left column.
My problem arises when I attempt to apply a box-shadow to the pseudo element. The element, and its shadow, always appear on top of my main column.
To make all of this clearer I have created a simple example page here: http://www.3strandsmarketing.com/test4.html
My fear is that since I'm using a pseudo element based on the parent of my main column, it will never be able to sit under it, but I'm hoping there's some way this can be worked around. Any ideas?
A: Ok, the solution here is to not use semi-transparent (rgba) colors for the main column. Otherwise, you will be able to see the drop shadow of the sidebar column through it, ruining the effect of one being on top of the other.
To see the correct effect, visit the example page, and use Firebug or another DOM manipulating tool to change the background color for the #main-content div from rgba(0, 100, 0, 0.2) to rgba(0, 100, 0, 1). You should now see that it is indeed "on top" of the left side bar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: drupal optimization I am getting many 404 and 500 errors on my Drupal site, it is not very complex yet I am using Dreamhost and they are limiting my memory usage I think it is under 158MB, how do I find out what my memory limit is? I do not have access to php.ini. How do I optimize my database for performance or find the greatest memory hogs?
this is the error it is giving me
Fatal error: Allowed memory size of 94371840 bytes exhausted (tried to allocate 71 bytes) in /home/xxxxxxxxxx/xxxxxxxxx/xxxxxxxx/includes/database.mysql.inc
on line 108 before i deleted a number of mmodules "tried to allocate xxxx bytes was much larger
A: Perhaps you could post some information on what specifically module wise you are running? Or what kind of operations your using?
You also should try taking a look at this measurement of module memory usage
There are dozens of memory converters online if you need to convert to bytes/kilobytles to megabytes, but here is a link to one if your lazy :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having trouble with a form drop down list in Ruby on Rails This is my form:
<table>
<tbody>
<% form_for :HhActiveCarrier, @carriers, :url => { :action => "update" } do |f| %>
<% for carrier in @carriers %>
<tr>
<%= render :partial => "summary_detail", :locals => {:carrier => carrier, :f => f} %>
</tr>
<% end %>
</tbody>
</table>
<%= submit_tag "Update" %>
<% end %>
With my partial:
<td class="tn"><%= h(carrier.name.to_s()) -%></td>
<td class="sc"><%= h(carrier.country.to_s()) -%></td>
<td class="sc"><%= select_tag(:country, options_for_select(@countries)) -%></td>
This is the controller where I define the variables:
class ActiveCarriersController < ApplicationController
def index
@carriers = HhActiveCarrier.find(:all)
for carrier in @carriers
country = carrier["country"]
if country.nil?
carrier["country"] = "none"
end
end
@countries = ["USA", "UK", "Canada"]
end
All of this works. However, if I make a change to the drop down list in the form to this:
<td class="sc"><%= f.select("country", @countries) -%></td>
I get this error:
Showing app/views/active_carriers/_summary_detail.rhtml where line #3 raised:
undefined method `country' for #<Array:0xef79a08>
Extracted source (around line #3):
1: <td class="tn"><%= h(carrier.name.to_s()) -%></td>
2: <td class="sc"><%= h(carrier.country.to_s()) -%></td>
3: <td class="sc"><%= f.select("country", @countries) -%></td>
Trace of template inclusion: /app/views/active_carriers/_summary.rhtml, >/app/views/active_carriers/index.rhtml
What am I doing wrong with my form select? I am using Ruby on Rails 2.3.8
Stackoverflow is telling me that I don't have much explanation for all the code i have, so I am just writing stuff. I don't really know what else to explain, so ask questions if you don't understand everything. Also I couldn't quote the error message because Stackoverflow kept telling me I had code that didn't have the code blocks, so I had to put code blocks around the error message.
A: Try this: f.select("carrier", "country", options_for_select(@countries))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change Header on Masterpage depening on what page is being display Ok, I have read some really good suggestions. I have a car dealership website that has a page for each manufacturer. I have created a header for each manufacturer which I have currently in an html file. So when I click on Ford, It will call the masterpage to get the data and I want to create a conditional statement that tells the masterpage to display the Ford page header. Just the same, if I click on Chevy, I want the masterpage to display the Chevy header.
It has been a while since I have created a loop like this and I need some help with the code.
When the pages were in html. my code looked like...
<body bgcolor="#ffffff" topmargin="0" onLoad="StartRotation(); type(); return true" align="center">
<!-- #include file="header-Toyota.html" -->
<!-- #include file="body.html" -->
<!-- #include file="footer.html" -->
</body>
Thanks for any help
A: Layla, I think it'd be a good idea to use WebControls. Learn how to use them, and then just add the WebControl to your MasterPage's header. Insert the Business Rule inside the MasterPage's Load event to decide what WebControl or what Content within your WebControl is going to be load. This is not too hard. If you any more specific questions you can contact me to Guide you through it or to give you more information on the matter.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php login form - security basics again a simple but not very obvious question from me. This time is login in PHP and the session.
AS far as I understand the security side of it:
*
*checking all the variables before sending to MySQL
*using $_POST for hiding info
*and logging the sessions
Well I have some code 'learned/made' but if you could spot out things that I am missing with a little explanation I would very much appreciate and also could be useful for many beginners like me. (I have read so many questions about it but most of the time the answer started - Despite the fact the code is disastrous in many ways, the specific answer to...)
So here there are:
index.php
<html>
<head>
<title>Website</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<ul><li><a href="index.php">HOME</a></li><li><a href="menu1.php">menu1</a></li><li><a href="logout.php">logout</a></li></ul>
</body>
</html>
session.php:
<?php
session_start();
if (!isset($_SESSION["txtUserId"])) {
require "login.php";
exit;
}
login.php
require_once('db_connect.php');
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
// check if the user id and password combination is correct
$random = '$%hgy5djk3tgbG^bhk';;
$logname=htmlspecialchars($_POST['txtUserId']);
$pass=sha1(($_POST['txtPassword']).$random)
$sql = "SELECT user, pass FROM users WHERE username= :login";
$stmt = $db->prepare($sql);
$stmt->bindvalue( ':login', $logname);
$stmt->execute();
if $stmt['pass']==$pass {
// set the session
$_SESSION['basic_is_logged_in'] = true;
header('Location: main.php');
exit;
}
else {
$errorMessage = 'Sorry, wrong user id / password';
require "login.php";
}
}
?>
<html>
<head>
<title>Login ...</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($errorMessage != '') {
?>
<p align="center"><strong><font color="#990000"><?php echo $errorMessage; ?></font></strong></p>
<?php
}
?>
<form method="post" name="frmLogin" id="frmLogin">
<table width="400" border="1" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="150">User Id</td>
<td><input name="txtUserId" type="text" id="txtUserId"></td>
</tr>
<tr>
<td width="150">Password</td>
<td><input name="txtPassword" type="password" id="txtPassword"></td>
</tr>
<tr>
<td width="150"> </td>
<td><input type="submit" name="btnLogin" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
db_connect.php:
<?php
$hostname = "localhost";
$username = "name";
$password = "pass";
try {
$pdo = new PDO("mysql:host=$hostname; dbname=dbnamehere", $username, $password);
//echo "Connected to database"; // check for connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
A: For starters, your code will run an infinite and broken loop if a login error occurs. You require a file from within itself which would not work. I am impressed you took the time however to properly understand some security basics and have implemented PDO into your DB calls and properly escaping your user input with prepare statements.
edit
I am assuming your login page actually exists on index.php. As opposed to 'echoing' statements from your login.php script, I would allow the entire script to process, capturing any errors in a known $_SESSION variable, perhaps:
$_SESSION['login_valid_error'] = "some text".
At the end of the script,
if(isset($_SESSION['login_valid_error']) && !empty($_SESSION['login_valid_error'])) {
header(...) //take the person to logged in page
} else {
header('Location: index.php');
}
then back on index.php, just above your form create an error notice section (with some css) which if page is loaded and the variable exists, echo it:
<?php
if(isset($_SESSION['login_valid_error'])) {
echo '<div class="error">'. $_SESSION['login_valid_error'] .'</div>';
unset($_SESSION['login_valid_error']);
}
?>
making sure to unset the variable once the page is loaded (any new attempts on the page will collect new errors.
I would also consider using something like phpass link is here. It may seem a bit overwhelming at first but download the code and look at the samples. It is actually very easy to integrate and will allow you to skip worry about salting/hashing your user input for things like passwords.
A: The $_POST variable only hides the data from the user, but it doesn't add any security other than obscurity.
Security considerations should include (at least) a unique token in your form (all forms!) to prevent cross site scripting, validating the token, encrypting the request to the login form (at least), encrypting and salting (unique, unstored salt) your user passwords, as well as validating and sanitizing all user entered-data.
I recommend using a well supported MVC framework, which will handle much of the security for you.
Here are some videos of exactly what you are trying to do, using the CodeIgniter MVC framework:
*
*http://heybigname.com/2011/07/28/codeigniter-2-sparks-php-activerecord-part-1-installation/
*http://heybigname.com/2011/08/03/codeigniter-2-sparks-php-activerecord-part-2-the-user-model/
*http://heybigname.com/2011/08/17/codeigniter-2-sparks-php-activerecord-part-3-login/
And the Hello World and Blog examples:
*
*http://codeigniter.com/tutorials/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is it possible to create an empty multidimensional array in javascript/jquery? I am trying to create a very basic Flickr gallery using the Flickr API. What I want to achieve is sorting my pictures by tag. What I am using is jQuery.getJSON() so that I can parse the API response of flickr.photosets.getPhotos.
The data I am interested in getting from Flickr is the tag and the URL associated to each photo. The problem with this is that the only logical way out of this for me is creating a multidimensional array of the following format:
Array['tag1'] => ['URL_1', 'URL_2', 'URL_3', 'URL_n'];
However, I cannot find any way to achieve this. My code looks like this:
$.getJSON('http://api.flickr.com/services/rest/?api_key=xxx&method=flickr.photosets.getPhotos&user_id=xxx&format=json&extras=tags%2C+url_l%2C+url_sq&nojsoncallback=1&photoset_id=xxx',
function(data) {
var imageArray = [];
$.each(data.photoset.photo, function(i, item) {
imageArray[item.tags] = [item.url_sq,];
});
});
I am aware that the code might look awkward, but I've tried everything and there's no way I can figure this out.
A: var arr = [];
arr[0] = [];
arr[0][0] = [];
arr[0][0][0] = "3 dimentional array"
Multi dimentional arrays have a lot of gaps unless they are used properly. A two dimensional array is called a matrix.
I believe your data contains a space seperate string called "tags" containing the tags and a single url.
var tagObject = {};
data.photoset.photo.forEach(function(val) {
val.tags.split(" ").forEach(function(tag) {
if (!tagObject[tag]) {
tagObject[tag] = [];
}
tagObject[tag].push(val.url_sq);
});
});
console.log(tagObject);
/*
{
"sea": ["url1", "url2", ...],
"things": ["url4", ...],
...
}
*/
I don't know how it returns multiple tags.
A: I think the syntax you are attempting to achieve is something like the following:
var item = {"tags":"blah","url_sq":"example.com"}; // for sake of example.
var imageArray = [];
$.each(data.photoset.photo, function(i, item) {
imageArray.push({"tags":item.tags,"url":item.url_sq});
});
and then reference it like this:
imageArray[0].tags
imageArray[0].url
imageArray[1].tags
imageArray[1].url
...
A: JavaScript doesn't have true multidimensional arrays (heck, it doesn't even have true regular arrays...), but, like most languages, it instead uses arrays of arrays. However, to me it looks like you need an object (kinda similar to PHP's arrays) containing arrays.
var data = {
tag1: ['URL_1', 'URL_2', 'URL_3', 'URL_n']
};
// Then accessed like:
data.tag1; // ['URL_1', ...]
data.tag1[0]; // 'URL_1'
data.tag1[1]; // 'URL_2'
// etc.
So, you're problem would look something like this:
var tags = {};
$.each(data.photoset.photo, function (i, item) {
$.each(item.tags.split(" "), function (i, tag) {
if (!tags[tag])
tags[tag] = [];
tags[tag].push(item.url_sq);
});
});
// tags is now something like:
// {
"foo": ["/url.html", "/other-url/", ...],
"bar": ["/yes-im-a-lisp-programmer-and-thats-why-i-hypenate-things-that-others-might-underscore-or-camelcase/", ...],
...
//}
A: Maybe something like that in your each:
if ( imageArray[item.tags] != null ){
imageArray[item.tags][imageArray[item.tags].length] = item.url_sq;
}else{
imageArray[item.tags] = [];
}
A: Yes it is! I found this to be quite fast. I might stretch to say that it could be the fastest way possible to generate a N Dimensional array of Ns lengths resulting in empty arrays using JavaScript. (i.e. an arbitrary number of dimensions each with an arbitrary length)
Even though the definition of an array in JavaScript is foggy at best.
function createNDimArray(dimensions) {
var t, i = 0, s = dimensions[0], arr = new Array(s);
if ( dimensions.length < 3 ) for ( t = dimensions[1] ; i < s ; ) arr[i++] = new Array(t);
else for ( t = dimensions.slice(1) ; i < s ; ) arr[i++] = createNDimArray(t);
return arr;
}
Usages:
var arr = createNDimArray([3, 2, 3]);
// arr = [[[,,],[,,]],[[,,],[,,]],[[,,],[,,]]]
console.log(arr[2][1]); // in FF: Array [ <3 empty slots> ]
console.log("Falsy = " + (arr[2][1][0]?true:false) ); // Falsy = false
If you care to read more; check my answer to this question.
A: Yes, it's possible to have multidimensional arrays in javascript.
Here are one-liners for 5x5 matrix:
Array(5).fill(0).map(() => new Array(5).fill(0))
Or
[...Array(5)].map(x=>Array(5).fill(0))
A: I think something like this should do what you want
var imageArray = [];
$.each(data.photoset.photo, function(i, item) {
// if the tag is new, then create an array
if(!imageArray[item.tags])
imageArray[item.tags] = [];
// push the item url onto the tag
imageArray[item.tags].push(item.url_sq);
});
A: You can simply try this one for 2d js array:
let myArray = [[]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: When should I choose SAX over StAX? Streaming xml-parsers like SAX and StAX are faster and more memory efficient than parsers building a tree-structure like DOM-parsers. SAX is a push parser, meaning that it's an instance of the observer pattern (also called listener pattern). SAX was there first, but then came StAX - a pull parser, meaning that it basically works like an iterator.
You can find reasons why to prefer StAX over SAX everywhere, but it usually boils down to: "it's easier to use".
In the Java tutorial on JAXP StAX is vaguely presented as the middle between DOM and SAX: "it's easier than SAX and more efficient than DOM". However, I never found any clues that StAX would be slower or less memory efficient than SAX.
All this made me wonder: are there any reasons to choose SAX instead of StAX?
A: OverviewXML documents are hierarchical documents, where the same element names and namespaces might occur in several places, having different meaning, and in infinitive depth (recursive). As normal, the solution to big problems, is to divide them into small problems. In the context of XML parsing, this means parsing specific parts of XML in methods specific to that XML. For example, one piece of logic would parse an address:
<Address>
<Street>Odins vei</Street>
<Building>4</Building>
<Door>b</Door>
</Address>
i.e. you would have a method
AddressType parseAddress(...); // A
or
void parseAddress(...); // B
somewhere in your logic, taking XML inputs arguments and returning an object (result of B can be fetched from a field later).
SAX
SAX 'pushes' XML events, leaving it up to you to determine where the XML events belong in your program / data.
// method in stock SAX handler
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
// .. your logic here for start element
}
In case of an 'Building' start element, you would need to determine that you are actually parsing an Address and then route the XML event to the method whose job it is to interpret Address.
StAX
StAX 'pulls' XML events, leaving it up to you to determine where in your program / data to receive the XML events.
// method in standard StAX reader
int event = reader.next();
if(event == XMLStreamConstants.START_ELEMENT) {
// .. your logic here for start element
}
Of course, you would always want to receive a 'Building' event in in the method whose job it is to interpret Address.
Discussion
The difference between SAX and StAX is that of push and pull. In both cases, the parse state must be handled somehow.
This translates to method B as typical for SAX, and method A for StAX. In addition, SAX must give B individual XML events, while StAX can give A multiple events (by passing an XMLStreamReader instance).
Thus B first check the previous state of the parsing and then handle each individual XML event and then store the state (in a field). Method A can just handle the XML events all at once by accessing the XMLStreamReader multiple times until satisfied.
Conclusion
StAX lets you structure your parsing (data-binding) code according to the XML structure; so in relation to SAX, the 'state' is implicit from the program flow for StAX, whereas in SAX, you always need to preserve some kind of state variable + route the flow according to that state, for most event calls.
I recommend StAX for all but the simplest documents. Rather move to SAX as an optimization later (but you'll probably want to go binary by then).
Follow this pattern when parsing using StAX:
public MyDataBindingObject parse(..) { // provide input stream, reader, etc
// set up parser
// read the root tag to get to level 1
XMLStreamReader reader = ....;
do {
int event = reader.next();
if(event == XMLStreamConstants.START_ELEMENT) {
// check if correct root tag
break;
}
// add check for document end if you want to
} while(reader.hasNext());
MyDataBindingObject object = new MyDataBindingObject();
// read root attributes if any
int level = 1; // we are at level 1, since we have read the document header
do {
int event = reader.next();
if(event == XMLStreamConstants.START_ELEMENT) {
level++;
// do stateful stuff here
// for child logic:
if(reader.getLocalName().equals("Whatever1")) {
WhateverObject child = parseSubTreeForWhatever(reader);
level --; // read from level 1 to 0 in submethod.
// do something with the result of subtree
object.setWhatever(child);
}
// alternatively, faster
if(level == 2) {
parseSubTreeForWhateverAtRelativeLevel2(reader);
level --; // read from level 1 to 0 in submethod.
// do something with the result of subtree
object.setWhatever(child);
}
} else if(event == XMLStreamConstants.END_ELEMENT) {
level--;
// do stateful stuff here, too
}
} while(level > 0);
return object;
}
So the submethod uses about the same approach, i.e. counting level:
private MySubTreeObject parseSubTree(XMLStreamReader reader) throws XMLStreamException {
MySubTreeObject object = new MySubTreeObject();
// read element attributes if any
int level = 1;
do {
int event = reader.next();
if(event == XMLStreamConstants.START_ELEMENT) {
level++;
// do stateful stuff here
// for child logic:
if(reader.getLocalName().equals("Whatever2")) {
MyWhateverObject child = parseMySubelementTree(reader);
level --; // read from level 1 to 0 in submethod.
// use subtree object somehow
object.setWhatever(child);
}
// alternatively, faster, but less strict
if(level == 2) {
MyWhateverObject child = parseMySubelementTree(reader);
level --; // read from level 1 to 0 in submethod.
// use subtree object somehow
object.setWhatever(child);
}
} else if(event == XMLStreamConstants.END_ELEMENT) {
level--;
// do stateful stuff here, too
}
} while(level > 0);
return object;
}
And then eventually you reach a level in which you will read the base types.
private MySetterGetterObject parseSubTree(XMLStreamReader reader) throws XMLStreamException {
MySetterGetterObject myObject = new MySetterGetterObject();
// read element attributes if any
int level = 1;
do {
int event = reader.next();
if(event == XMLStreamConstants.START_ELEMENT) {
level++;
// assume <FirstName>Thomas</FirstName>:
if(reader.getLocalName().equals("FirstName")) {
// read tag contents
String text = reader.getElementText()
if(text.length() > 0) {
myObject.setName(text)
}
level--;
} else if(reader.getLocalName().equals("LastName")) {
// etc ..
}
} else if(event == XMLStreamConstants.END_ELEMENT) {
level--;
// do stateful stuff here, too
}
} while(level > 0);
// verify that all required fields in myObject are present
return myObject;
}
This is quite straightforward and there is no room for misunderstandings. Just remember to decrement level correctly:
A. after you expected characters but got an END_ELEMENT in some tag which should contain chars (in the above pattern):
<Name>Thomas</Name>
was instead
<Name></Name>
The same is true for a missing subtree too, you get the idea.
B. after calling subparsing methods, which are called on start elements, and returns AFTER the corresponding end element, i.e. the parser is at one level lower than before the method call (the above pattern).
Note how this approach totally ignores 'ignorable' whitespace too, for more robust implementation.
Parsers
Go with Woodstox for most features or Aaalto-xml for speed.
A: To generalize a bit, I think StAX can be as efficient as SAX. With the improved design of StAX I can't really find any situation where SAX parsing would be preferred, unless working with legacy code.
EDIT: According to this blog Java SAX vs. StAX StAXoffer no schema validation.
A: @Rinke: I guess only time I think of preferring SAX over STAX in case when you don't need to handle/process XML content; for e.g. only thing you want to do is check for well-formedness of incoming XML and just want to handle errors if it has...in this case you can simply call parse() method on SAX parser and specify error handler to handle any parsing problem....so basically STAX is definitely preferrable choice in scenarios where you want to handle content becasue SAX content handler is too difficult to code...
one practical example of this case may be if you have series of SOAP nodes in your enterprise system and an entry level SOAP node only lets those SOAP XML pass thru next stage which are well-formedness, then I don't see any reason why I would use STAX. I would just use SAX.
A: It's all a balance.
You can turn a SAX parser into a pull parser using a blocking queue and some thread trickery so, to me, there is much less difference than there first seems.
I believe currently StAX needs to be packaged through a third-party jar while SAX comes free in javax.
I recently chose SAX and built a pull parser around it so I did not need to rely on a third-party jar.
Future versions of Java will almost certainly contain a StAX implementation so the problem goes away.
A: StAX enables you to create bidirectional XML parsers that are fast. It proves a better alternative to other methods, such as DOM and SAX, both in terms of performance and usability
You can read more about StAX in Java StAX Tutorials
A: Most of the information provided by those answers are somewhat outdated... there have been a comprehensive study of all XML parsing libs in this 2013 research paper... read it and you will easily see the clear winner (hint: there is only one true winner)...
http://recipp.ipp.pt/bitstream/10400.22/1847/1/ART_BrunoOliveira_2013.pdf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "86"
} |
Q: implicitly converting lambda to boost::function I'm trying to make a implicit lambda convertible to lambda function by the following code:
#include <boost/function.hpp>
struct Bla {
};
struct Foo {
boost::function< void(Bla& )> f;
template <typename FnType>
Foo( FnType fn) : f(fn) {}
};
#include <iostream>
int main() {
Bla bla;
Foo f( [](Bla& v) -> { std::cout << " inside lambda " << std::endl; } );
};
However, i'm getting this error with g++
$ g++ --version
g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
$ g++ -std=c++0x test.cpp `pkg-config --cflags boost-1.46` -o xtest `pkg-config --libs boost-1.46`
test.cpp: In function ‘int main()’:
test.cpp:21: error: expected primary-expression before ‘[’ token
test.cpp:21: error: expected primary-expression before ‘]’ token
test.cpp:21: error: expected primary-expression before ‘&’ token
test.cpp:21: error: ‘v’ was not declared in this scope
test.cpp:21: error: expected unqualified-id before ‘{’ token
any idea how can i achieve the above? or if i can achieve it at all?
UPDATE trying with g++ 4.5
$ g++-4.5 --version
g++-4.5 (Ubuntu/Linaro 4.5.1-7ubuntu2) 4.5.1
$ g++-4.5 -std=c++0x test.cpp `pkg-config --cflags boost-1.46` -o xtest `pkg-config --libs boost-1.46`
test.cpp: In function ‘int main()’:
test.cpp:20:22: error: expected type-specifier before ‘{’ token
A: You are missing a void:
Foo f( [](Bla& v) -> void { std::cout << " inside lambda " << std::endl; } );
// ^ here
Or, as @ildjarn pointed out, you can simply omit the return type:
Foo f( [](Bla& v) { std::cout << " inside lambda " << std::endl; } );
With either of these lines, your code compiles fine using MinGW g++ 4.5.2 and Boost v1.46.1.
A: Your lambda syntax is wrong. you have the '->' in there but don't specify the return type. You probably mean:
Foo f( [](Bla& v) { std::cout << " inside lambda " << std::endl; } );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing custom variables via paypal (IPN Question) I've been trying back and forth with this and I finally got PayPal working the way it should. However, i need to pass some variables (user_id, and some small details (numbers) about the product).
Is there any way i can pass custom variables? or variable? I've been looking around on Google and it looks like people is saying different things about this. Some says it not allowed, and some says it's not a problem at all.
Got an example maybe? i assume I'll need a hidden form of some sort?
A: Take a look at the custom variable: HTML Variables for Website Payments Standard. Typically, what I do, is store any info I need in a database and reference it with the PayPal txn_id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with Jquery, .getJSON in IE7-8 I have a jquery script that creates image rollovers for counties in a state. The script queries an XML document for county x/y coordinates and information, then displays this information when the county on the state image is hovered over. Additionally, a random county and county information is displayed until one of the counties is hovered on; Once the viewer hovers off of the county, the random display resumes.
The script works great in FireFox and Chrome, but not in Internet Explorer 7 - 8. In IE, the random display works, but about 75% of the counties will not respond to the hover functionality, with apparently no pattern as to why they won't respond (as I said, they work great in other browsers).
//____________________________________________________________________________________________________________ CONSTANTS
var DATA_SOURCE = '/CountyData.js'; // URL of the page that serves JSON county data
var IMAGE_PATH = '/images/counties/'; // Relative path to the county image folder
var CSS_WRAPPER_CLASS = 'countyWrapper'; // CSS class to apply to each county's wrapper <div>
var CSS_IMAGE_CLASS = 'countyImage'; // CSS class to apply to <img> tags
var CSS_INFO_CLASS = 'countyInfo'; // CSS class to apply to info <div> tags
var ROTATION_INTERVAL = 10; // seconds to show each random county while rotating
//____________________________________________________________________________________________________ PRIVATE VARIABLES
var _isHovering = false;
var _autoSelectedCounty = null;
//______________________________________________________________________________________________________ FUN BEGINS HERE
function highlightRandomCounty() {
// only show a new county if we're not hovering over another one
if (!_isHovering) {
var children = $('#map-holder').children('div');
var randomIndex = parseInt(Math.random() * children.length);
_autoSelectedCounty = $(children[randomIndex]).children('img')[0];
hideAllCounties();
showCounty(_autoSelectedCounty);
}
}
function showCounty(countyImage) {
$(countyImage).stop().animate({ opacity: 1.0 }, 500);
$(countyImage).siblings().animate({ opacity: 1.0 }, 500);
}
function hideCounty(countyImage) {
$(countyImage).stop().animate({ opacity: 0.0 }, 0);
$(countyImage).siblings().animate({ opacity: 0.0 }, 0);
}
function hideAllCounties() {
var counties = $('#map-holder').children('div');
for (var i = 0; i < counties.length; i++) {
hideCounty($(counties[i]).children('img')[0]);
}
}
$(document).ready(function() {
// show the pre-loader
var preloader = document.createElement('div');
$('#map-holder').append(preloader);
$(preloader).attr('id', 'preloader');
//testing var
var countyCount = 1;
$.getJSON(DATA_SOURCE, function(data) {
$.each(data.countyData, function(i, item) {
// create the container <div> and append it to the page
var container = document.createElement('div');
$('#map-holder').append(container);
// configure the container
$(container).attr('id', 'div' + item.data_county);
$(container).attr('class', CSS_WRAPPER_CLASS);
$(container).attr('style', 'left:'+ item.data_x + 'px; top:' + item.data_y + 'px;');
// create the <img> and append it to the container
var countyImage = document.createElement('img');
$(container).append(countyImage);
// configure the image
$(countyImage).attr('id', item.data_county + 'Image');
$(countyImage).attr('class', CSS_IMAGE_CLASS);
$(countyImage).attr('src', IMAGE_PATH + item.data_county_image + '.png');
$(countyImage).load(function() {
// wait for the image loads before setting these properties
$(this).attr('width', countyImage.width);
$(this).attr('height', countyImage.height);
});
$(countyImage).hover(function() {
_isHovering = true;
hideCounty(_autoSelectedCounty);
showCounty($(this));
},
function() {
_isHovering = false;
hideCounty($(this));
});
$(countyImage).click(function() {
window.location.href = item.factsLink;
});
// create the info <div> and append it to the container
var countyInfo = document.createElement('div');
$(container).append(countyInfo);
$(countyInfo).attr('id', item.data_county + 'Info');
$(countyInfo).attr('class', CSS_INFO_CLASS);
// Handle county naming exceptions
var countyName = item.data_county.toUpperCase();
if (countyName == 'SAINTJOYVILLE') {
countyName = 'ST. JOYVILLE';
} else {
if (countyName.indexOf("SAINT") > -1) {
countyName = "ST. " + countyName.substr(5);
}
countyName += " COUNTY";
}
if (item.story_link == 'no') {
$(countyInfo).html('<strong>' + countyName + '</strong><br />' + item.data_total_students + ' Students<br />' + item.data_total_alumni + ' Alumni<br />' + '$' + item.economicImpact + ' Impact<br />Click For More...');
} else {
$(countyInfo).html('<strong>' + countyName + '</strong><br />' + item.data_total_students + ' Students<br />' + item.data_total_alumni + ' Alumni<br />' + '$' + item.economicImpact + 'Impact<br /><strong>Latest story:</strong><br /><img src="' + item.story_link + '" alt="story" height="75" width="110"><br />' + item.story_title + '<br />Click For More...');
}
});
});
// hide the pre-loader
$('#preloader').animate({ opacity: 0.0 }, 1000);
//randomly rotate through the counties
setInterval(highlightRandomCounty, ROTATION_INTERVAL * 1000);
});
Is there something that I need to enable/disable in order for this to function correctly in IE? Perhaps some sort of .getJSON/caching issue in IE? Any information is greatly appreciated.
A: There are a few known issues with IE treating all ajax request as regular web requests. So things get cached.
You can try....
$.ajaxSetup({ cache: false });
$.getJSON("/MyQueryUrl",
function(data) {
// do stuff with callback data
$.ajaxSetup({ cache: true });
});
Also, if you are using ASP.NET
on the server side set cacheability
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
A: If it's totally random, my gut reaction is that IE is failing to set up the hover correctly when the image hasn't loaded yet. Try moving your hover setup into the load() callback function, after you set width and height.
EDIT: Based on your new information, I recommend changing the top line of your script to end in ".json" instead of ".js". Your current web host may (correctly) return your JSON response as mime-type x-javascript instead of json, which could definitely confuse IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find the date for the upcoming weekend in Ruby? so I wanted to have an option called Weekend Delivery, but I can't seem to find any nifty Date#method that can help determine the date (like 2011-09-24) for Saturday, say.
So far I come up with:
today = Date.today
sat = today + (6-today.wday) # 6 being the 6th day of the week with 1 being Monday
Not that it's not short enough, but I thought if there are any built-in or Gem method that does something like Date.this_sat, Date.this_thur, Date.this_weekend, it would be nice..
Thanks!
A: Use the Chronic gem, it is fantastic!
gem install chronic
Here is an example:
require 'chronic'
Chronic.parse('this Saturday noon')
#=> Sat Sep 24 12:00:00 PDT 2011
I edited the output to reflect the newest gem version since I am using an older version.
A: Well, ActiveSupport has an end_of_week method. Subtract 1 and you're there: weekend!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle unique constraint and unique index Could someone clarify what is the purpose of having unique index without unique constraint (Oracle)?
For example,
create table test22(id int, id1 int, tmp varchar(20));
create unique index idx_test22 on test22(id);
insert into test22(id, id1, tmp) values (1, 2, 'aaa'); // ok
insert into test22(id, id1, tmp) values (1, 2, 'aaa'); // fails, ORA-00001: unique
// constraint (TEST.IDX_TEST22) violated
So far it looks like there is a constraint. But
create table test33(id int not null primary key,
test22_id int not null,
foreign key(test22_id) references test22(id) );
also fails with "ORA-02270: no matching unique or primary key for this column-list".
I'm totally confused by this behaviour. Is there a constraint or not?
There are many articles that explain why it's possible to have a unique constraint without unique index; that is clear and makes perfect sense. However, I don't understand the reason for unique index without constraint.
A: A constraint and an index are separate logical entities. A unique constraint, for example, is visible in USER_CONSTRAINTS (or ALL_CONSTRAINTS or DBA_CONSTRAINTS). An index is visible in USER_INDEXES (or ALL_INDEXES or DBA_INDEXES).
A unique constraint is enforced by an index though it is possible (and sometimes necessary) to enforce a unique constraint using a non-unique index. A deferrable unique constraint, for example, is enforced using a non-unique index. If you create a non-unique index on a column and subsequently create a unique constraint, you can also use that non-unique index to enforce the unique constraint.
In practice, a unique index acts very much like a unique, non-deferrable constraint in that it raises the same error that a unique constraint raises since the implementation of unique constraints uses the index. But it is not quite the same because there is no constraint. So, as you've seen, there is no unique constraint so you cannot create a foreign key constraint that references the column.
There are cases where you can create a unique index that you cannot create a unique constraint. A function-based index, for example, that enforces conditional uniqueness. If I wanted to create a table that supported logical deletes but ensure that COL1 is unique for all non-deleted rows
SQL> ed
Wrote file afiedt.buf
1 CREATE TABLE t (
2 col1 number,
3 deleted_flag varchar2(1) check( deleted_flag in ('Y','N') )
4* )
SQL> /
Table created.
SQL> create unique index idx_non_deleted
2 on t( case when deleted_flag = 'N' then col1 else null end);
Index created.
SQL> insert into t values( 1, 'N' );
1 row created.
SQL> insert into t values( 1, 'N' );
insert into t values( 1, 'N' )
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.IDX_NON_DELETED) violated
SQL> insert into t values( 1, 'Y' );
1 row created.
SQL> insert into t values( 1, 'Y' );
1 row created.
But if we're talking about a straight unique non-function based index, there are probably relatively few cases where it really makes more sense to create the index rather than creating the constraint. On the other hand, there are relatively few cases where it makes much difference in practice. You'd almost never want to declare a foreign key constraint that referenced a unique constraint rather than a primary key constraint so you rarely lose something by only creating the index and not creating the constraint.
A: As was already explained in other answers: constraints and the indexes are different entities. But they lack precise definitions and official comments on the topic. Before we discuss the relationship between these two entities lets take a look at their purpose independent of each other.
Purpose of a constraint1:
Use a constraint to define an integrity constraint-- a rule that restricts the values in a database.
The purposes of an index2:
You can create indexes on columns to speed up queries. Indexes provide faster access to data for operations that return a small portion of a table's rows.
In general, you should create an index on a column in any of the following situations:
*
*The column is queried frequently.
*A referential integrity constraint exists on the column.
*A UNIQUE key integrity constraint exists on the column.
Now we know what constraints and indexes are, but what is the relationship between them?
The relationship between indexes and constraints is3:
*
*a constraint MIGHT create an index or use an existing index to efficient enforce itself. For example, a PRIMARY KEY constraint will either create an index (unique or non-unique depending) or it will find an existing suitable index and use it.
*an index has nothing to do with a constraint. An index is an index.
So, a constraint MIGHT create/use and index. An INDEX is an INDEX, nothing more, nothing less.
So sum this up and directly address the following sentence from your question:
However, I don't understand the reason for unique index without constraint.
Indexes speed up queries and integrity checks (constraints). Also for conditional uniqueness a unique (functional) index is used as this cannot be achieved with a constraint.
Hopefully this brings a little bit more clarification to the whole topic, but there is one aspect of the original question that remains unanswered:
Why did the following error occur when no constraint existed:
ORA-00001: unique constraint (TEST.IDX_TEST22) violated
The answer is simple: there is no constraint and the error message misnames it!
See the official "Oracle Ask TOM" comment 4 on the same problem:
It isn't a constraint. the error message "misnames" it.
If it were a constraint, you could create a foreign key to it -- but you cannot.
Hope it helps.
Links:
1 Oracle 10g Documentation on Constraints
2 Oracle 10g Documentation on Selecting an Index Strategy
3 4 "Oracle Ask TOM" answer to a similar problem
A: Another point which may be useful in this context is :
Disabling/Dropping an existing unique constraint do not drop the underlying unique index. You got to drop the unique index explicitly.
A: You can not make conditional uniqueness by declaring a unique constraint, But you can do it by declaring a unique index.
Supporse if you try to execute below:
alter table test22
add constraint test22_u
unique (id, case when tmp = 'aaa' then null else tmp end);
ORA-00904: : invalid identifier
But if you can do it by using the unique index
create unique index test22_u
on test22 ( customer_id,
case when is_default = 'Y' then null else address_id end)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Deserialize google geocoding XML using Datacontract in C# I have the following Google geocoding XML
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</formatted_address>
<address_component>
<long_name>1600</long_name>
<short_name>1600</short_name>
<type>street_number</type>
</address_component>
<address_component>
<long_name>Amphitheatre Pkwy</long_name>
<short_name>Amphitheatre Pkwy</short_name>
<type>route</type>
</address_component>
....
<geometry>
<location>
<lat>37.4217550</lat>
<lng>-122.0846330</lng>
</location>
<location_type>ROOFTOP</location_type>
<viewport>
<southwest>
<lat>37.4188514</lat>
<lng>-122.0874526</lng>
</southwest>
<northeast>
<lat>37.4251466</lat>
<lng>-122.0811574</lng>
</northeast>
</viewport>
</geometry>
</result>
</GeocodeResponse>
And the following object
[DataContract(Namespace = "")]
public class GeocodeResponse
{
[DataMember(Name = "status", Order = 1)]
public string Status { get; set; }
[DataMember(Name = "result", Order = 2)]
public List<Result> Results { get; set; }
[DataContract(Name = "result", Namespace = "")]
public class Result
{
[DataMember(Name = "geometry")]
public CGeometry Geometry { get; set; }
[DataContract(Name = "geometry", Namespace = "")]
public class CGeometry
{
[DataMember(Name = "location")]
public CLocation Location { get; set; }
[DataContract(Name = "location", Namespace = "")]
public class CLocation
{
[DataMember(Name = "lat", Order = 1)]
public double Lat { get; set; }
[DataMember(Name = "lng", Order = 2)]
public double Lng { get; set; }
}
}
}
}
I am trying to deserialize using the following method
DataContractSerializer serializer = new DataContractSerializer(typeof(GeocodeResponse));
var response = (GeocodeResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
After deserialization, Results is always empty. What am I doing wrong?
UPDATE:
Changed Result element. Getting another error now:
There was an error deserializing the object of type GeocodeResponse. The data at the root level is invalid. Line 1, position 1.
...
[DataMember(Name = "result", Order = 2)]
public CResult Result { get; set; }
[DataContract]
public class CResult
{
...
I am able to Deserialize the original object using JSON like below.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeocodeResponse));
A: You can't really use the DataContractSerializer (DCS) to deserialize the response from that request, you need to use the XmlSerializer. DCS doesn't support unwrapped collections, which is what the response contains - like the one shown below.
<a>
<b/>
<c/>
<c/>
<c/>
</a>
The DCS only supports collections when they're wrapped in their own element:
<a>
<b/>
<cs>
<c/>
<c/>
<c/>
</cs>
</a>
The XmlSerializer does support such collections. The code below shows a partial class structure for deserializing a response from the Google geocoding XML.
public class StackOverflow_7521821
{
[XmlRoot(ElementName = "GeocodeResponse", Namespace = "")]
public class GeocodeResponse
{
[XmlElement(ElementName = "status")]
public GeocodeResponseStatusCode Status;
[XmlElement(ElementName = "result")]
public List<GeocodeResponseResult> Results;
}
[XmlType(Namespace = "")]
public class GeocodeResponseResult
{
[XmlElement(ElementName = "type")]
public List<string> Types;
[XmlElement(ElementName = "formatted_address")]
public string FormattedAddress;
[XmlElement(ElementName = "address_component")]
public List<GeocodeResponseAddressComponent> AddressComponents;
[XmlElement(ElementName = "geometry")]
public GeocodeResponseResultGeometry Geometry;
}
[XmlType(Namespace = "")]
public class GeocodeResponseAddressComponent
{
[XmlElement(ElementName = "long_name")]
public string LongName;
[XmlElement(ElementName = "short_name")]
public string ShortName;
[XmlElement(ElementName = "type")]
public List<string> Types;
}
[XmlType(Namespace = "")]
public class GeocodeResponseResultGeometry
{
[XmlElement(ElementName = "location")]
public Location Location;
[XmlElement(ElementName = "location_type")]
public GeocodeResponseResultGeometryLocationType LocationType;
[XmlElement(ElementName = "viewport")]
public GeocodeResponseResultGeometryViewport Viewport;
}
[XmlType(Namespace = "")]
public class GeocodeResponseResultGeometryViewport
{
[XmlElement(ElementName = "southwest")]
public Location Southwest;
[XmlElement(ElementName = "northeast")]
public Location Northeast;
}
public enum GeocodeResponseStatusCode
{
OK,
ZERO_RESULTS,
OVER_QUERY_LIMIT,
REQUEST_DENIED,
INVALID_REQUEST,
}
public enum GeocodeResponseResultGeometryLocationType
{
ROOFTOP,
RANGE_INTERPOLATED,
GEOMETRIC_CENTER,
APPROXIMATE,
}
[XmlType(Namespace = "")]
public class Location
{
[XmlElement(ElementName = "lat")]
public string Lat;
[XmlElement(ElementName = "lng")]
public string Lng;
}
public static void Test()
{
XmlSerializer xs = new XmlSerializer(typeof(GeocodeResponse));
WebClient c = new WebClient();
byte[] response = c.DownloadData("http://maps.googleapis.com/maps/api/geocode/xml?address=1+Microsoft+Way,+Redmond,+WA&sensor=true");
MemoryStream ms = new MemoryStream(response);
GeocodeResponse geocodeResponse = (GeocodeResponse)xs.Deserialize(ms);
Console.WriteLine(geocodeResponse);
c = new WebClient();
response = c.DownloadData("http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");
ms = new MemoryStream(response);
geocodeResponse = (GeocodeResponse)xs.Deserialize(ms);
Console.WriteLine(geocodeResponse);
}
}
A: You don't want to use List<Result> if there is only one <result> tag with everything inside of it. I removed List from my test code and it Results is no longer empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jqplot highlighting stacked column chart I have a stacked column chart .
For highlighting any of the individual slices, we can make use of the "highlightColors" option, but if I have to highlight the entire bar is there any option available for the same. My current code looks like this:
seriesDefaults : {
renderer : $.jqplot.BarRenderer,
rendererOptions : {
barWidth : this.barWidth,
barMargin : this.barMargin,
highlightColors : '#fffefe'
}
This needs to be modified in such a way that the entire bar gets highlighted. Please advise
A: I made something for it.
The solution involves custom painting over the highlight canvas.
The sample is here.
It was integrated into a sample I made for a question asking how to add sums on top of a stacked bar chart, details are here. I also upgraded its code, so now it is 'bar chart orientation friendly'.
Just in case the JS code is also below:
$(document).ready(function() {
var ins = [2, 2, 3, 5];
var outs = [2, 4, 3, 5];
var swaps = [2, 2, 6, 5];
var passes = [2, 4, 6, 5];
var data = [ins, outs, swaps, passes, [3, 3, 3, 3]];
var series = [
{
label: 'IN',
pointLabels: {
labels: [2, 2, 3, 5]
}},
{
label: 'OUT',
pointLabels: {
labels: [2, 4, 3, 5]
}},
{
label: 'SWAP',
pointLabels: {
labels: [2, 2, 6, 5]
}},
{
label: 'PASS',
pointLabels: {
labels: [2, 4, 6, 5]
}},
{
label: 'INVISIBLE',
pointLabels: {
labels: ['∑ 8', '∑ 12', '∑ 18', '∑ 20']
},
show: false,
shadowAngle: 90,//for horizontal use (180 istead of 90)
rendererOptions: {
shadowDepth: 25,
shadowOffset: 2.5,
shadowAlpha: 0.01
}}
];
var ticks = ['Oi', 'Bike', 'Car', 'Truck'];
var plot = $.jqplot('chart', data, {
stackSeries: true,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barMargin: 20
//for horizontal uncomment this
// ,barDirection: 'horizontal'
},
pointLabels: {
show: true,
stackedValue: false,
location: 's'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
//for horiozontal use the below instead
/*
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
*/
},
legend: {
show: true,
location: 'ne',
placement: 'outside'
},
series: series,
title: "Oi title"
});
//color used for tooltip title
var color = 'rgb(50%,50%,100%)';
//start span of a tooltip's title
var spanStart = '<span style="font-size:14px;font-weight:bold;color:' + color + ';">';
$('#chart').bind('jqplotDataHighlight', function(ev, seriesIndex, pointIndex, data) {
var chart_left = $('#chart').offset().left;
var chart_top = $('#chart').offset().top;
var x = ev.pageX;
var y = ev.pageY;
var left = x;
var top = y;
var chartTooltipHTML = spanStart;
if (plot.axes.xaxis.u2p && plot.axes.yaxis.u2p) { // pierenderer do not have u2p
left = chart_left + plot.axes.xaxis.u2p(data[0]); // convert x axis units to pixels on grid
top = chart_top + plot.axes.yaxis.u2p(data[1]); // convert y axis units to pixels on grid
}
var barWidth = plot.series[0].barWidth;
//tells if the bar chart is vertical
var isVertical = false;
if (plot.series[0].barDirection === "vertical")
isVertical = true;
if (isVertical) left -= barWidth / 2;
else top -= barWidth / 2;
//for stacked chart
if(isVertical){
top = chart_top;
var sum = 0;
for (var i = 0; i < seriesIndex + 1; i++)
sum += plot.series[i].data[pointIndex][1];
top += plot.axes.yaxis.u2p(sum);
}else{
left = chart_left;
var sum = 0;
for (var i = 0; i < seriesIndex + 1; i++)
sum += plot.series[i].data[pointIndex][0];
left += plot.axes.xaxis.u2p(sum);
}
var seriesName = plot.series[seriesIndex].label;
console.log("seriesName = " + seriesName + " seriesIndex = " + seriesIndex + " pointIndex= " + pointIndex + " data= "+data+ " plot.series[seriesIndex].data= " + plot.series[seriesIndex].data[pointIndex]);
chartTooltipHTML += 'My custom tooltip: </span>'
+ '<br/><b>Count:</b> ' + data[1] //data[1] has count of movements
+ '<br/><b>Movement type:</b> ' + seriesName;
//start of part highlighting whole bar --- all bars (other than this bar is related to custom tooltip)
//for painting just grab the first highlight canvas as there could be 'n' of them where 'n' is the number of series, I think
var drawingCanvas = $(".jqplot-barRenderer-highlight-canvas")[0];
var rX = chart_left + plot.axes.xaxis.u2p(data[0]) - $(drawingCanvas).offset().left - barWidth/2;
var rY = chart_top + plot.axes.yaxis.u2p(data[1]) - $(drawingCanvas).offset().top - barWidth/2;
var rW = 0;
var rH = barWidth;
if (isVertical){
rW = rH;
rH = 0;
}
for(var i = 0; i < plot.series.length; i++){
if (isVertical) {
rH += plot.series[i].data[pointIndex][1];
}else{
rW += plot.series[i].data[pointIndex][0];
}
}
var canvasLeft = parseInt($(drawingCanvas).css('left'),10);
var canvasTop = parseInt($(drawingCanvas).css('top'),10);
if(isVertical){
rY = plot.axes.yaxis.u2p(rH) - canvasTop;//- $(drawingCanvas).offset().top;
rH = drawingCanvas.height - plot.axes.yaxis.u2p(rH) + canvasTop;//$(drawingCanvas).css('top').;
}else{
rX = 0;
rW = plot.axes.xaxis.u2p(rW) - canvasLeft;
}
console.log("rX= "+rX+"; rY= "+rY+"; rW= "+rW+"; rH = "+ rH + " drawingCanvas.height= "+drawingCanvas.height);
var context = drawingCanvas.getContext('2d');
context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height); context.strokeStyle = "#000000";
context.strokeRect(rX, rY, rW, rH);
//end of part doing custom painting of frame around all bars
var ct = $('#chartTooltip');
ct.css({
left: left,
top: top
}).html(chartTooltipHTML).show();
if (plot.series[0].barDirection === "vertical") {
var totalH = ct.height() + ct.padding().top + ct.padding().bottom + ct.border().top + ct.border().bottom;
ct.css({
top: top - totalH
});
}
});
// Bind a function to the unhighlight event to clean up after highlighting.
$('#chart').bind('jqplotDataUnhighlight', function(ev, seriesIndex, pointIndex, data) {
$('#chartTooltip').empty().hide();
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to press a button with java-script event inside a web-page by code for iOS (iPhone)? I am writing an application for iOS (iPhone).
How to press a button with java-script event inside a web-page? I need to write a code to press this button. Then the event will be executed. And I'll take result of it's work.
Thanks a lot for help!
A: You can use:
document.getElementById('id-of-button').click();
This will perform a click event on the button.
EDIT: to run JavaScript in a UIWebView use the stringByEvaluatingJavaScript: method. Eg:
[webView stringByEvaluatingJavaScript:@"document.getElementById('id-of-button').click();"];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: javascript regular expression validator I have a text box named id. I need to form a text box validator where I want the id number in the text box to be of the format a letter, followed by 3 numbers (each in range 0-8), a separator "+" or "-", and another 4 numbers (each 0-9).
Can anyone tell me how I could write this regular expression validator in javascript...
Any help is appreciated. Thanks
A: As they pointed out above, this would be a great exercise to learn how to do regexes yourself. However, in the interest of being helpful, here is the regex you need:
/^[a-zA-Z][0-8]{3}[-+][0-9]{4}$/
A: The regular expression you're looking for (assuming by "letter" you mean "latin lower- or upper-case letter") is:
/^[a-zA-Z][0-8]{3}[+-][0-9]{4}$/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is there a MonoTouch wrapper for UIImage-DSP library? I'm searching for a MonoTouch wrapper (or a complete port) of this library:
https://github.com/gdawg/uiimage-dsp
UIImage Image Processing extensions using the vDSP/Accelerate framework.
Fast Image Blur/Sharpen/Emboss/Matrix operations for UIImage.
REQUIRES IOS 4.0 and The Accelerate framework.
Thanks in advance.
A: You won't find bindings for it - at least not in it's actual form. Quote from the URL you supplied:
Copy the UIImage+DSP.h and UIImage+DSP.m classes into your project
So it's not yet a library. Someone could maybe it one from the code but, until then, you won't find bindings for it.
As for a complete port the next quote
these aren't quite as fast
makes it sounds like translating the code to C# (lots of array, bounds checks... even if they could be eliminated with unsafe code) is not the best option. I suggest you keep looking at another (OpenGL-ES maybe?) solution - like your previous question here: How to do a motion blur effect on an UIImageView in Monotouch?
Maybe even add a bounty once you get enough reputation points :-)
A: I wrote a native port of the blur and tint UIImage categories from WWDC for Monotouch.
*
*https://github.com/lipka/MonoTouch.UIImageEffects
It uses the Accelerate.framework - you can possible extend on it if it doesn't exactly suit your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use Panels + CTools Page Manager Node Template with Views Row Style Node I have used Panels + CTools Page Manager to configure the 'Node template' (node_view) for a particular content type. When viewing these nodes at /node/% the Page Manager's node template renders the nodes just fine.
However, when trying to display a 'Row style: Node' version of these nodes with a View, the nodes are rendered using my default node.tpl.php file.
How do you setup Views 'Row style: Node' to utilize the Panels + CTools Page Manager Node Template?
A: There are two approaches that might work. Both require Drupal experience or research.
*
*IF you add CSS styling to the view or panel, you can then create custom CSS for your theme.
*You can try defining a Theme listed in Views in the Advanced column, under others. Some of the template files exist, and others are only suggestions (They have two underscores between words instead of one). If you put a copy of a selected tpl.php file in your theme folder it will override the main one and you can make changes there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WMI causing memory leak(when run in multiple threads) My question is similar to Periodical WMI Query Causes Memory Leak? but with threads.
I am writing a simple application to monitor process and memory information from a number of servers. However there is a memory leak. I have whittled down the problem to the following simple Console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
public static void dummyQuery(string ip, string query)
{
ConnectionOptions connOptions = new ConnectionOptions();
ManagementScope mgtScope = new ManagementScope(@"\\" + ip + @"\ROOT\CIMV2", connOptions);
mgtScope.Connect();
ObjectQuery queryo = new ObjectQuery(query);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(mgtScope, queryo))
{
using (ManagementObjectCollection moc = searcher.Get())
{
}
}
}
static void Main(string[] args)
{
Console.ReadKey();
int times = 10000;
for (int i = 0; i < times; i++)
{
Thread t = new Thread(o => dummyQuery("xxxxxxxxx", @"SELECT WorkingSetSize FROM Win32_Process WHERE name='W3WP.exe'"));
//t.IsBackground = true;
t.Start();
System.Threading.Thread.Sleep(50);
}
Console.ReadKey();
//GC.Collect();
Console.ReadKey();
}
}
}
Is there a way to run WMI queries from threads safely?
This is extracted from a much more complicated wpf application that checks the status of many servers much like the dummyQuery method. That application leaks memory at a disturbingly fast rate related to WMI calls. This sample looks like it is not leaking memory (Jim Mischel had a better way of checking this). I will install a profiler and take another look at the original app.
A: I Know that this is might be considered a dead thread but it was top of the search list when I was looking for a solution to the ManagementObjectSearcher memory leak issue that I was having.
My application is a multithreaded application that was calling WMI on the main thread as part of the initialisation process. The application then spawned multiple thread non of which used WMI. However, the application kept leaking memory when run as a Windows service (it was OK if it was run as a standard executable).
Putting [MTAThread] attribute on the Main entrypoint resolved the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apartment Fire- Time Machine did not back up XCode projects? My apartment burned down a few days ago and my beloved MacBook Pro was one of the many electronic casualties. While I of course back up (using Time Machine) and my backup drive managed to survive, much to my dismay many of the most important files seem to be missing from my Time Machine backups. Namely, all of my recent XCode projects. In fact, the entire directory (titled "Re-Programming") which housed all of my development projects is inexplicably missing from my latest backups.
Curiously, it seems that some of my older backups do contain the missing folder (May 10 has the folder, while May 19 through the latest do not).
I would have wanted to try Migration Assistant to bring my files over to a friend's computer but I'm unable to because my backups were made in Lion and he is using Snow Leopard. I'm fairly certain it wouldn't help though (not only is the directory missing, but a search for certain header files I remember the filename of don't show up in Search).
I've done some googling and it seems Time Machine does not backup XCode build folders to save space. This makes sense as it would take up a lot of space and are easily recreated by building your projects. But why on earth would Time Machine not backup my oh-so-important XCode project files?
The plot thickens though. Even if, for some strange reason Time Machine has a bug that prevents it from backing up XCode projects, what about other projects? I had some Android projects in there too, maybe even some old HTML/CSS/PHP happenings. What happened to those, and why the ENTIRE directory, not just the XCode projects? And why did it USED TO backup my most important directory and suddenly stopped without my knowledge back in May?
Am I missing something here? Perhaps they were placed in a weird place that isn't obvious to me? Any help is appreciated.
A: Sorry to hear that. I believe TimeMachine backups are just a .sparsebundle files. You should be able to mount the file directly and browse through it to see if you can find any of your project files.
A: https://superuser.com/questions/147998/backing-up-my-xcode-projects
I am not sure about Time Machine but here are some alternatives!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Stretch Grid to window size I've just started learning C# WPF with a basic empty project and I want to make a grid, with a background image, which stretches exactly over the window.
The way it is now, the grid stretches, but not the way I want it. For example my background image is 1000x1000px and my window size is 1700x1200px so the grid stretches to 1200x1200px (it keeps the aspect ratio of the image. I don't want this, I want it simply to stretch all over the window.
Here is my code:
<Window x:Class="Backgammon.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="auto" Width="auto">
<Grid VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" MinWidth="510" />
</Grid.ColumnDefinitions>
<Image Source="C:\Users\Edy\Pictures\cool-wallpapers1.jpg" Stretch="UniformToFill" HorizontalAlignment="Left"></Image>
<Button Height="33" HorizontalAlignment="Right" Margin="0,0,12,12" Name="button1" VerticalAlignment="Bottom" Width="145" Click="button1_Click" ClipToBounds="False">Connect</Button>
<ListBox Margin="12,12,0,149" Name="listBox1" HorizontalAlignment="Left" Width="225" />
</Grid>
Any help would be great, thanks.
A: Try
<Grid Width="{Binding ActualWidth,
RelativeSource = {RelativeSource AncestorType = {x:Type Window}}}"
Height="{Binding ActualHeight,
RelativeSource ={RelativeSource AncestorType = {x:Type Window}}}">
A: Got it figured out. It was the <Grid.ColumnDefinitions> that messed things up for me. Deleted that and it worked :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Reading and writing files in Cyrillic in c++ I have to first read a file in Cyrillic, then randomly pick random number of lines and write modified text to a different file. No problem with Latin letter, but I run into a problem with Cyrillic text, because I get some rubbish. So this is how I tried to do the thing.
Say, file input.txt is
ааааааа
ббббббб
ввввввв
I have to read it, and put every line into a vector:
vector<wstring> inputVector;
wstring inputString, result;
wifstream inputStream;
inputStream.open("input.txt");
while(!inputStream.eof())
{
getline(inputStream, inputString);
inputVector.push_back(inputString);
}
inputStream.close();
srand(time(NULL));
int numLines = rand() % inputVector.size();
for(int i = 0; i < numLines; i++)
{
int randomLine = rand() % inputVector.size();
result += inputVector[randomLine];
}
wofstream resultStream;
resultStream.open("result.txt");
resultStream << result;
resultStream.close();
So how can I do work with Cyrillic so it produces readable things, not just symbols?
A: Because you saw something like ■a a a a a a a 1♦1♦1♦1♦1♦1♦1♦ 2♦2♦2♦2♦2♦2♦2♦ printed to the console, it appears that input.txt is encoded in a UTF-16 encoding, probably UTF-16 LE + BOM. You can use your original code if you change the encoding of the file to UTF-8.
The reason for using UTF-8 is that, regardless of the char type of the file stream, basic_fstream's underlying basic_filebuf uses a codecvt object to convert a stream of char objects to/from a stream of objects of the char type; i.e. when reading, the char stream that is read from the file is converted to a wchar_t stream, but when writing, a wchar_t stream is converted to a char stream that is then written to the file. In the case of std::wifstream, the codecvt object is an instance of the standard std::codecvt<wchar_t, char, mbstate_t>, which generally converts UTF-8 to UCS-16.
As explained on the MSDN documentation page for basic_filebuf:
Objects of type basic_filebuf are created with an internal buffer of type char * regardless of the char_type specified by the type parameter Elem. This means that a Unicode string (containing wchar_t characters) will be converted to an ANSI string (containing char characters) before it is written to the internal buffer.
Similarly, when reading a Unicode string (containing wchar_t characters), the basic_filebuf converts the ANSI string read from the file to the wchar_t string returned to getline and other read operations.
If you change the encoding of input.txt to UTF-8, your original program should work correctly.
For reference, this works for me:
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main()
{
using namespace std;
vector<wstring> inputVector;
wstring inputString, result;
wifstream inputStream;
inputStream.open("input.txt");
while(!inputStream.eof())
{
getline(inputStream, inputString);
inputVector.push_back(inputString);
}
inputStream.close();
srand(time(NULL));
int numLines = rand() % inputVector.size();
for(int i = 0; i < numLines; i++)
{
int randomLine = rand() % inputVector.size();
result += inputVector[randomLine];
}
wofstream resultStream;
resultStream.open("result.txt");
resultStream << result;
resultStream.close();
return EXIT_SUCCESS;
}
Note that the encoding of result.txt will also be UTF-8 (generally).
A: Why would you use wifstream -- are you confident that your file consists of a sequence of (system-dependent) wide characters? Almost certainly that is not the case. (Most notably because the system's wide character set isn't actually definite outside the scope of a C++ program).
Instead, just read the input byte stream as it is and echo it accordingly:
std::ifstream infile(thefile);
std::string line;
std::vector<std::string> input;
while (std::getline(infile, line)) // like this!!
{
input.push_back(line);
}
// etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Class Library - References - Reusability with Copy Local? I have a class library project, lets call it CoreLib.
CoreLib has two references to 3rd party DLL files 1.dll and 2.dll
Because I love reusability so much, I want to be able to use CoreLib in as many places as possible/needed.
So if I had a project called BigProjectA and another project called BigProjectB and they needed to leverage the functionality provided by CoreLib, all I would have to do is add a reference to CoreLib in those projects (BigProjectA and BigProjectB).
That is fine, except when I go to copy over my output folder (bin directory) to another person's computer, I can't guarantee that they have 1.dll and 2.dll on their machines.
For that, I just set Copy Local to True for 1.dll and 2.dll references in the CoreLib project.
When building the CoreLib project I can see 1.dll, 2.dll, and CoreLib.dll files. That is PERFECT!
But in the projects referencing CoreLib, only CoreLib.dll is copied over, not 1.dll and 2.dll.
Am I missing something? Copy Local set to True, but only copies for the CoreLib project. So even though they are in the same solution, and I'm adding CoreLib as a project reference to the other projects, I still dont see 1.dll and 2.dll copying out to the other bin/Debug, bin/Release folders of the other projects (BigProjectA and BigProjectB).
Is there an easy solution?
A: The easy solution is to either:
*
*reference 1.DLL and 2.DLL in projects which have a binary reference to CoreData.DLL
*Add CoreData as a project reference to BigProjectA and BigProjectB instead of as a binary reference
In the first scenario, CoreData's dependencies are not automatically output by the compiler. If the CoreData project is added to the solution, its dependencies will be output. Hence, to use CoreData as a binary reference, you must also reference its dependencies.
A: There is nothing wrong. In projects BigProjectA and BigProjectB you have a references to only CoreLib, so they "care" about coping only it, cause they have no any clue about it's dependencies. What you can do to resolve these kind of issue, is to add for example PostBuildVEent in your BigProject.. to copy also CoreLib dependencies.
Or add reference to CoreLib project, if you can.
Another solution, is to consider DI like a technique to avoid strong coupling of references. So, if in BigProjectA or B you don't care about functionality provided by 3rd party libraries in CoreLib, for you should be enough to just copy CoreLib.
A: Good answers guys....but I actually just ended up using ILMerge. Seemed safer/less annoying.
Thank you though
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Transparent mouse emulation on iOS Safari Is there a (small) js module which can be included to make an existing (mouse-based) webapp (instantly) usable on the Mobile Safari?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best Practice for Emailing Customer Address Book Contacts? A question I am sure has been asked before but as opposed to 'how do I...', I am curious what the best practice is for programmers looking to implement a 'mass email' option on our website when an existing customer authorizes (via gmail api, yahoo mail api, etc) their own contact list.
Goal
The idea is simple: a user wants to share something about his/her site. They can of course use social media or select to import/email their existing contact list from say Gmail, Yahoo, AOL, or CSV then in turn an email is sent to each recipient with marketing message.
Problems I see
*
*We use the basic version (free) of Google Apps currenlty for one site. This limits us to I think around 500 emails at a time and a threshold per day. Users not only will be limited in how many contacts they can upload but also ->
*I fear of being 'blacklisted' possibly sending out hundreds/thousands of emails at a time. We are on a pretty tight budge to start so using something like mailchimp for delivery is just too expensive
Primary Question
What is the proper method of the 'share by email' functionality which you see on so many sites today. This is typically noticed next to facebook share buttons, twitter tweet buttons and more. The 'ShareThis' functionality mentioned below seems like a viable option but given the edit by Blake below, clearly Google's Contact API was in some way meant for this.
Update to original post
I am not sure how this is coming across as spam given so many large websites allows for 'sharing' things via email. I am trying to solve what I consider a fairly basic problem but if others see differently then additional suggestions are welcome. Calling this spam, however, is not accurate given we did not obtain the email addresses unethically or illegally and I would plan on allow an opt-out/unsubscribe option (with tracking for any future attempts).
Direct From the Google Contacts Data API:
Here are some of the things you can do with the Contacts Data API:
*
*Synchronize Google contacts with contacts on a mobile device
*Maintain relationships between people in social applications
*Give users the ability to communicate directly with their friends from external applications using phone, email, and IM
A: I'm not a laywer, and I think you should NOT do this. But from my experience, as long as:
*
*the data come from the user.
*the submitting action is triggered by the user
*you do not store the email that come from the user
... the law consider that the user have send the email(s), but using your service (your SMTP server).
Further reading: http://www.webhostingtalk.com/archive/index.php/t-201195.html
A: If I absolutely needed to build this, I'd go with a Google AppEngine site, with a web service that accepts incoming requests (better make sure this is secure to avoid people using this as a way to spam!). You can send 2000 messages/day for free, and above that it's $0.10/ 1000 Emails.
Also consider using ShareThis. This provides several ways to share content (also social media), and allows a user to user his/her Google + Yahoo address books.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: slideDown div inside a function not working For now I'm trying to slide down the msg_general div, I will later append a json response to it, however the problem is it will just show but not slidedown.
The function:
function createGeneralMsg(msg) {
$('#msg_general').slideDown(200);
}
Where I call it (inside a .click functon):
.......
$.ajax({
type: "POST",
url: action_link,
data: data_string,
dataType: 'json',
success:
function(msg) {
if($('.delete-link').hasClass('delete-page')) {
window.location = 'index.php';
}
if($('.delete-link').hasClass('delete-news')) {
createGeneralMsg(msg);
}
}
}, 'json');
.......
slideDown() will work anywhere else, when I test this for example:
$('.test').click(function() {
$('#msg_general').slideDown(200);
});
Any help would be greatly appreciated.
A: try to call it on coplate event :
var _msg;
$.ajax({
type: "POST",
url: action_link,
data: data_string,
dataType: 'json',
success:
function(msg) {
if($('.delete-link').hasClass('delete-page')) {
window.location = 'index.php';
}
}
},
complete : function() {
if($('.delete-link').hasClass('delete-news')) {
createGeneralMsg(_msg);
}
},
//code goes on here...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521861",
"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.